Bug Summary

File:lib/Target/X86/X86ISelLowering.cpp
Warning:line 14384, column 47
The result of the '/' expression is undefined

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -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 -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-9/lib/clang/9.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-9~svn362543/build-llvm/lib/Target/X86 -I /build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86 -I /build/llvm-toolchain-snapshot-9~svn362543/build-llvm/include -I /build/llvm-toolchain-snapshot-9~svn362543/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/include/clang/9.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-9/lib/clang/9.0.0/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-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-9~svn362543/build-llvm/lib/Target/X86 -fdebug-prefix-map=/build/llvm-toolchain-snapshot-9~svn362543=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2019-06-05-060531-1271-1 -x c++ /build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp -faddrsig
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 "Utils/X86ShuffleDecode.h"
16#include "X86CallingConv.h"
17#include "X86FrameLowering.h"
18#include "X86InstrBuilder.h"
19#include "X86IntrinsicsInfo.h"
20#include "X86MachineFunctionInfo.h"
21#include "X86TargetMachine.h"
22#include "X86TargetObjectFile.h"
23#include "llvm/ADT/SmallBitVector.h"
24#include "llvm/ADT/SmallSet.h"
25#include "llvm/ADT/Statistic.h"
26#include "llvm/ADT/StringExtras.h"
27#include "llvm/ADT/StringSwitch.h"
28#include "llvm/Analysis/EHPersonalities.h"
29#include "llvm/CodeGen/IntrinsicLowering.h"
30#include "llvm/CodeGen/MachineFrameInfo.h"
31#include "llvm/CodeGen/MachineFunction.h"
32#include "llvm/CodeGen/MachineInstrBuilder.h"
33#include "llvm/CodeGen/MachineJumpTableInfo.h"
34#include "llvm/CodeGen/MachineModuleInfo.h"
35#include "llvm/CodeGen/MachineRegisterInfo.h"
36#include "llvm/CodeGen/TargetLowering.h"
37#include "llvm/CodeGen/WinEHFuncInfo.h"
38#include "llvm/IR/CallSite.h"
39#include "llvm/IR/CallingConv.h"
40#include "llvm/IR/Constants.h"
41#include "llvm/IR/DerivedTypes.h"
42#include "llvm/IR/DiagnosticInfo.h"
43#include "llvm/IR/Function.h"
44#include "llvm/IR/GlobalAlias.h"
45#include "llvm/IR/GlobalVariable.h"
46#include "llvm/IR/Instructions.h"
47#include "llvm/IR/Intrinsics.h"
48#include "llvm/MC/MCAsmInfo.h"
49#include "llvm/MC/MCContext.h"
50#include "llvm/MC/MCExpr.h"
51#include "llvm/MC/MCSymbol.h"
52#include "llvm/Support/CommandLine.h"
53#include "llvm/Support/Debug.h"
54#include "llvm/Support/ErrorHandling.h"
55#include "llvm/Support/KnownBits.h"
56#include "llvm/Support/MathExtras.h"
57#include "llvm/Target/TargetOptions.h"
58#include <algorithm>
59#include <bitset>
60#include <cctype>
61#include <numeric>
62using namespace llvm;
63
64#define DEBUG_TYPE"x86-isel" "x86-isel"
65
66STATISTIC(NumTailCalls, "Number of tail calls")static llvm::Statistic NumTailCalls = {"x86-isel", "NumTailCalls"
, "Number of tail calls", {0}, {false}}
;
67
68static cl::opt<bool> ExperimentalVectorWideningLegalization(
69 "x86-experimental-vector-widening-legalization", cl::init(false),
70 cl::desc("Enable an experimental vector type legalization through widening "
71 "rather than promotion."),
72 cl::Hidden);
73
74static cl::opt<int> ExperimentalPrefLoopAlignment(
75 "x86-experimental-pref-loop-alignment", cl::init(4),
76 cl::desc("Sets the preferable loop alignment for experiments "
77 "(the last x86-experimental-pref-loop-alignment bits"
78 " of the loop header PC will be 0)."),
79 cl::Hidden);
80
81static cl::opt<bool> MulConstantOptimization(
82 "mul-constant-optimization", cl::init(true),
83 cl::desc("Replace 'mul x, Const' with more effective instructions like "
84 "SHIFT, LEA, etc."),
85 cl::Hidden);
86
87/// Call this when the user attempts to do something unsupported, like
88/// returning a double without SSE2 enabled on x86_64. This is not fatal, unlike
89/// report_fatal_error, so calling code should attempt to recover without
90/// crashing.
91static void errorUnsupported(SelectionDAG &DAG, const SDLoc &dl,
92 const char *Msg) {
93 MachineFunction &MF = DAG.getMachineFunction();
94 DAG.getContext()->diagnose(
95 DiagnosticInfoUnsupported(MF.getFunction(), Msg, dl.getDebugLoc()));
96}
97
98X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
99 const X86Subtarget &STI)
100 : TargetLowering(TM), Subtarget(STI) {
101 bool UseX87 = !Subtarget.useSoftFloat() && Subtarget.hasX87();
102 X86ScalarSSEf64 = Subtarget.hasSSE2();
103 X86ScalarSSEf32 = Subtarget.hasSSE1();
104 MVT PtrVT = MVT::getIntegerVT(TM.getPointerSizeInBits(0));
105
106 // Set up the TargetLowering object.
107
108 // X86 is weird. It always uses i8 for shift amounts and setcc results.
109 setBooleanContents(ZeroOrOneBooleanContent);
110 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
111 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
112
113 // For 64-bit, since we have so many registers, use the ILP scheduler.
114 // For 32-bit, use the register pressure specific scheduling.
115 // For Atom, always use ILP scheduling.
116 if (Subtarget.isAtom())
117 setSchedulingPreference(Sched::ILP);
118 else if (Subtarget.is64Bit())
119 setSchedulingPreference(Sched::ILP);
120 else
121 setSchedulingPreference(Sched::RegPressure);
122 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
123 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
124
125 // Bypass expensive divides and use cheaper ones.
126 if (TM.getOptLevel() >= CodeGenOpt::Default) {
127 if (Subtarget.hasSlowDivide32())
128 addBypassSlowDiv(32, 8);
129 if (Subtarget.hasSlowDivide64() && Subtarget.is64Bit())
130 addBypassSlowDiv(64, 32);
131 }
132
133 if (Subtarget.isTargetKnownWindowsMSVC() ||
134 Subtarget.isTargetWindowsItanium()) {
135 // Setup Windows compiler runtime calls.
136 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
137 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
138 setLibcallName(RTLIB::SREM_I64, "_allrem");
139 setLibcallName(RTLIB::UREM_I64, "_aullrem");
140 setLibcallName(RTLIB::MUL_I64, "_allmul");
141 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
142 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
143 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
144 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
145 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
146 }
147
148 if (Subtarget.isTargetDarwin()) {
149 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
150 setUseUnderscoreSetJmp(false);
151 setUseUnderscoreLongJmp(false);
152 } else if (Subtarget.isTargetWindowsGNU()) {
153 // MS runtime is weird: it exports _setjmp, but longjmp!
154 setUseUnderscoreSetJmp(true);
155 setUseUnderscoreLongJmp(false);
156 } else {
157 setUseUnderscoreSetJmp(true);
158 setUseUnderscoreLongJmp(true);
159 }
160
161 // If we don't have cmpxchg8b(meaing this is a 386/486), limit atomic size to
162 // 32 bits so the AtomicExpandPass will expand it so we don't need cmpxchg8b.
163 // FIXME: Should we be limitting the atomic size on other configs? Default is
164 // 1024.
165 if (!Subtarget.hasCmpxchg8b())
166 setMaxAtomicSizeInBitsSupported(32);
167
168 // Set up the register classes.
169 addRegisterClass(MVT::i8, &X86::GR8RegClass);
170 addRegisterClass(MVT::i16, &X86::GR16RegClass);
171 addRegisterClass(MVT::i32, &X86::GR32RegClass);
172 if (Subtarget.is64Bit())
173 addRegisterClass(MVT::i64, &X86::GR64RegClass);
174
175 for (MVT VT : MVT::integer_valuetypes())
176 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
177
178 // We don't accept any truncstore of integer registers.
179 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
180 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
181 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
182 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
183 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
184 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
185
186 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
187
188 // SETOEQ and SETUNE require checking two conditions.
189 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
190 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
191 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
192 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
193 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
194 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
195
196 // Integer absolute.
197 if (Subtarget.hasCMov()) {
198 setOperationAction(ISD::ABS , MVT::i16 , Custom);
199 setOperationAction(ISD::ABS , MVT::i32 , Custom);
200 }
201 setOperationAction(ISD::ABS , MVT::i64 , Custom);
202
203 // Funnel shifts.
204 for (auto ShiftOp : {ISD::FSHL, ISD::FSHR}) {
205 setOperationAction(ShiftOp , MVT::i16 , Custom);
206 setOperationAction(ShiftOp , MVT::i32 , Custom);
207 if (Subtarget.is64Bit())
208 setOperationAction(ShiftOp , MVT::i64 , Custom);
209 }
210
211 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
212 // operation.
213 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
214 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
215 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
216
217 if (Subtarget.is64Bit()) {
218 if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512())
219 // f32/f64 are legal, f80 is custom.
220 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
221 else
222 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
223 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
224 } else if (!Subtarget.useSoftFloat()) {
225 // We have an algorithm for SSE2->double, and we turn this into a
226 // 64-bit FILD followed by conditional FADD for other targets.
227 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
228 // We have an algorithm for SSE2, and we turn this into a 64-bit
229 // FILD or VCVTUSI2SS/SD for other targets.
230 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
231 } else {
232 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Expand);
233 }
234
235 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
236 // this operation.
237 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
238 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
239
240 if (!Subtarget.useSoftFloat()) {
241 // SSE has no i16 to fp conversion, only i32.
242 if (X86ScalarSSEf32) {
243 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
244 // f32 and f64 cases are Legal, f80 case is not
245 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
246 } else {
247 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
248 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
249 }
250 } else {
251 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
252 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Expand);
253 }
254
255 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
256 // this operation.
257 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
258 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
259
260 if (!Subtarget.useSoftFloat()) {
261 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
262 // are Legal, f80 is custom lowered.
263 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
264 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
265
266 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
267 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
268 } else {
269 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
270 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Expand);
271 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Expand);
272 }
273
274 // Handle FP_TO_UINT by promoting the destination to a larger signed
275 // conversion.
276 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
277 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
278 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
279
280 if (Subtarget.is64Bit()) {
281 if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512()) {
282 // FP_TO_UINT-i32/i64 is legal for f32/f64, but custom for f80.
283 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
284 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
285 } else {
286 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
287 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
288 }
289 } else if (!Subtarget.useSoftFloat()) {
290 // Since AVX is a superset of SSE3, only check for SSE here.
291 if (Subtarget.hasSSE1() && !Subtarget.hasSSE3())
292 // Expand FP_TO_UINT into a select.
293 // FIXME: We would like to use a Custom expander here eventually to do
294 // the optimal thing for SSE vs. the default expansion in the legalizer.
295 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
296 else
297 // With AVX512 we can use vcvts[ds]2usi for f32/f64->i32, f80 is custom.
298 // With SSE3 we can use fisttpll to convert to a signed i64; without
299 // SSE, we're stuck with a fistpll.
300 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
301
302 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
303 }
304
305 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
306 if (!X86ScalarSSEf64) {
307 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
308 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
309 if (Subtarget.is64Bit()) {
310 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
311 // Without SSE, i64->f64 goes through memory.
312 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
313 }
314 } else if (!Subtarget.is64Bit())
315 setOperationAction(ISD::BITCAST , MVT::i64 , Custom);
316
317 // Scalar integer divide and remainder are lowered to use operations that
318 // produce two results, to match the available instructions. This exposes
319 // the two-result form to trivial CSE, which is able to combine x/y and x%y
320 // into a single instruction.
321 //
322 // Scalar integer multiply-high is also lowered to use two-result
323 // operations, to match the available instructions. However, plain multiply
324 // (low) operations are left as Legal, as there are single-result
325 // instructions for this in x86. Using the two-result multiply instructions
326 // when both high and low results are needed must be arranged by dagcombine.
327 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
328 setOperationAction(ISD::MULHS, VT, Expand);
329 setOperationAction(ISD::MULHU, VT, Expand);
330 setOperationAction(ISD::SDIV, VT, Expand);
331 setOperationAction(ISD::UDIV, VT, Expand);
332 setOperationAction(ISD::SREM, VT, Expand);
333 setOperationAction(ISD::UREM, VT, Expand);
334 }
335
336 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
337 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
338 for (auto VT : { MVT::f32, MVT::f64, MVT::f80, MVT::f128,
339 MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
340 setOperationAction(ISD::BR_CC, VT, Expand);
341 setOperationAction(ISD::SELECT_CC, VT, Expand);
342 }
343 if (Subtarget.is64Bit())
344 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
345 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
346 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
347 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
348 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
349
350 setOperationAction(ISD::FREM , MVT::f32 , Expand);
351 setOperationAction(ISD::FREM , MVT::f64 , Expand);
352 setOperationAction(ISD::FREM , MVT::f80 , Expand);
353 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
354
355 // Promote the i8 variants and force them on up to i32 which has a shorter
356 // encoding.
357 setOperationPromotedToType(ISD::CTTZ , MVT::i8 , MVT::i32);
358 setOperationPromotedToType(ISD::CTTZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
359 if (!Subtarget.hasBMI()) {
360 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
361 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
362 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Legal);
363 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Legal);
364 if (Subtarget.is64Bit()) {
365 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
366 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Legal);
367 }
368 }
369
370 if (Subtarget.hasLZCNT()) {
371 // When promoting the i8 variants, force them to i32 for a shorter
372 // encoding.
373 setOperationPromotedToType(ISD::CTLZ , MVT::i8 , MVT::i32);
374 setOperationPromotedToType(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
375 } else {
376 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
377 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
378 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
379 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
380 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
381 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
382 if (Subtarget.is64Bit()) {
383 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
384 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
385 }
386 }
387
388 // Special handling for half-precision floating point conversions.
389 // If we don't have F16C support, then lower half float conversions
390 // into library calls.
391 if (Subtarget.useSoftFloat() || !Subtarget.hasF16C()) {
392 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
393 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
394 }
395
396 // There's never any support for operations beyond MVT::f32.
397 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
398 setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
399 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
400 setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
401
402 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
403 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
404 setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
405 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
406 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
407 setTruncStoreAction(MVT::f80, MVT::f16, Expand);
408
409 if (Subtarget.hasPOPCNT()) {
410 setOperationPromotedToType(ISD::CTPOP, MVT::i8, MVT::i32);
411 } else {
412 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
413 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
414 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
415 if (Subtarget.is64Bit())
416 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
417 else
418 setOperationAction(ISD::CTPOP , MVT::i64 , Custom);
419 }
420
421 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
422
423 if (!Subtarget.hasMOVBE())
424 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
425
426 // These should be promoted to a larger select which is supported.
427 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
428 // X86 wants to expand cmov itself.
429 for (auto VT : { MVT::f32, MVT::f64, MVT::f80, MVT::f128 }) {
430 setOperationAction(ISD::SELECT, VT, Custom);
431 setOperationAction(ISD::SETCC, VT, Custom);
432 }
433 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
434 if (VT == MVT::i64 && !Subtarget.is64Bit())
435 continue;
436 setOperationAction(ISD::SELECT, VT, Custom);
437 setOperationAction(ISD::SETCC, VT, Custom);
438 }
439
440 // Custom action for SELECT MMX and expand action for SELECT_CC MMX
441 setOperationAction(ISD::SELECT, MVT::x86mmx, Custom);
442 setOperationAction(ISD::SELECT_CC, MVT::x86mmx, Expand);
443
444 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
445 // NOTE: EH_SJLJ_SETJMP/_LONGJMP are not recommended, since
446 // LLVM/Clang supports zero-cost DWARF and SEH exception handling.
447 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
448 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
449 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
450 if (TM.Options.ExceptionModel == ExceptionHandling::SjLj)
451 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
452
453 // Darwin ABI issue.
454 for (auto VT : { MVT::i32, MVT::i64 }) {
455 if (VT == MVT::i64 && !Subtarget.is64Bit())
456 continue;
457 setOperationAction(ISD::ConstantPool , VT, Custom);
458 setOperationAction(ISD::JumpTable , VT, Custom);
459 setOperationAction(ISD::GlobalAddress , VT, Custom);
460 setOperationAction(ISD::GlobalTLSAddress, VT, Custom);
461 setOperationAction(ISD::ExternalSymbol , VT, Custom);
462 setOperationAction(ISD::BlockAddress , VT, Custom);
463 }
464
465 // 64-bit shl, sra, srl (iff 32-bit x86)
466 for (auto VT : { MVT::i32, MVT::i64 }) {
467 if (VT == MVT::i64 && !Subtarget.is64Bit())
468 continue;
469 setOperationAction(ISD::SHL_PARTS, VT, Custom);
470 setOperationAction(ISD::SRA_PARTS, VT, Custom);
471 setOperationAction(ISD::SRL_PARTS, VT, Custom);
472 }
473
474 if (Subtarget.hasSSEPrefetch() || Subtarget.has3DNow())
475 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
476
477 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
478
479 // Expand certain atomics
480 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
481 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
482 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
483 setOperationAction(ISD::ATOMIC_LOAD_ADD, VT, Custom);
484 setOperationAction(ISD::ATOMIC_LOAD_OR, VT, Custom);
485 setOperationAction(ISD::ATOMIC_LOAD_XOR, VT, Custom);
486 setOperationAction(ISD::ATOMIC_LOAD_AND, VT, Custom);
487 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
488 }
489
490 if (!Subtarget.is64Bit())
491 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
492
493 if (Subtarget.hasCmpxchg16b()) {
494 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
495 }
496
497 // FIXME - use subtarget debug flags
498 if (!Subtarget.isTargetDarwin() && !Subtarget.isTargetELF() &&
499 !Subtarget.isTargetCygMing() && !Subtarget.isTargetWin64() &&
500 TM.Options.ExceptionModel != ExceptionHandling::SjLj) {
501 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
502 }
503
504 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
505 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
506
507 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
508 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
509
510 setOperationAction(ISD::TRAP, MVT::Other, Legal);
511 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
512
513 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
514 setOperationAction(ISD::VASTART , MVT::Other, Custom);
515 setOperationAction(ISD::VAEND , MVT::Other, Expand);
516 bool Is64Bit = Subtarget.is64Bit();
517 setOperationAction(ISD::VAARG, MVT::Other, Is64Bit ? Custom : Expand);
518 setOperationAction(ISD::VACOPY, MVT::Other, Is64Bit ? Custom : Expand);
519
520 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
521 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
522
523 setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
524
525 // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
526 setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
527 setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
528
529 if (!Subtarget.useSoftFloat() && X86ScalarSSEf64) {
530 // f32 and f64 use SSE.
531 // Set up the FP register classes.
532 addRegisterClass(MVT::f32, Subtarget.hasAVX512() ? &X86::FR32XRegClass
533 : &X86::FR32RegClass);
534 addRegisterClass(MVT::f64, Subtarget.hasAVX512() ? &X86::FR64XRegClass
535 : &X86::FR64RegClass);
536
537 for (auto VT : { MVT::f32, MVT::f64 }) {
538 // Use ANDPD to simulate FABS.
539 setOperationAction(ISD::FABS, VT, Custom);
540
541 // Use XORP to simulate FNEG.
542 setOperationAction(ISD::FNEG, VT, Custom);
543
544 // Use ANDPD and ORPD to simulate FCOPYSIGN.
545 setOperationAction(ISD::FCOPYSIGN, VT, Custom);
546
547 // These might be better off as horizontal vector ops.
548 setOperationAction(ISD::FADD, VT, Custom);
549 setOperationAction(ISD::FSUB, VT, Custom);
550
551 // We don't support sin/cos/fmod
552 setOperationAction(ISD::FSIN , VT, Expand);
553 setOperationAction(ISD::FCOS , VT, Expand);
554 setOperationAction(ISD::FSINCOS, VT, Expand);
555 }
556
557 // Lower this to MOVMSK plus an AND.
558 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
559 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
560
561 } else if (!useSoftFloat() && X86ScalarSSEf32 && (UseX87 || Is64Bit)) {
562 // Use SSE for f32, x87 for f64.
563 // Set up the FP register classes.
564 addRegisterClass(MVT::f32, &X86::FR32RegClass);
565 if (UseX87)
566 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
567
568 // Use ANDPS to simulate FABS.
569 setOperationAction(ISD::FABS , MVT::f32, Custom);
570
571 // Use XORP to simulate FNEG.
572 setOperationAction(ISD::FNEG , MVT::f32, Custom);
573
574 if (UseX87)
575 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
576
577 // Use ANDPS and ORPS to simulate FCOPYSIGN.
578 if (UseX87)
579 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
580 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
581
582 // We don't support sin/cos/fmod
583 setOperationAction(ISD::FSIN , MVT::f32, Expand);
584 setOperationAction(ISD::FCOS , MVT::f32, Expand);
585 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
586
587 if (UseX87) {
588 // Always expand sin/cos functions even though x87 has an instruction.
589 setOperationAction(ISD::FSIN, MVT::f64, Expand);
590 setOperationAction(ISD::FCOS, MVT::f64, Expand);
591 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
592 }
593 } else if (UseX87) {
594 // f32 and f64 in x87.
595 // Set up the FP register classes.
596 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
597 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
598
599 for (auto VT : { MVT::f32, MVT::f64 }) {
600 setOperationAction(ISD::UNDEF, VT, Expand);
601 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
602
603 // Always expand sin/cos functions even though x87 has an instruction.
604 setOperationAction(ISD::FSIN , VT, Expand);
605 setOperationAction(ISD::FCOS , VT, Expand);
606 setOperationAction(ISD::FSINCOS, VT, Expand);
607 }
608 }
609
610 // Expand FP32 immediates into loads from the stack, save special cases.
611 if (isTypeLegal(MVT::f32)) {
612 if (UseX87 && (getRegClassFor(MVT::f32) == &X86::RFP32RegClass)) {
613 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
614 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
615 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
616 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
617 } else // SSE immediates.
618 addLegalFPImmediate(APFloat(+0.0f)); // xorps
619 }
620 // Expand FP64 immediates into loads from the stack, save special cases.
621 if (isTypeLegal(MVT::f64)) {
622 if (UseX87 && getRegClassFor(MVT::f64) == &X86::RFP64RegClass) {
623 addLegalFPImmediate(APFloat(+0.0)); // FLD0
624 addLegalFPImmediate(APFloat(+1.0)); // FLD1
625 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
626 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
627 } else // SSE immediates.
628 addLegalFPImmediate(APFloat(+0.0)); // xorpd
629 }
630
631 // We don't support FMA.
632 setOperationAction(ISD::FMA, MVT::f64, Expand);
633 setOperationAction(ISD::FMA, MVT::f32, Expand);
634
635 // Long double always uses X87, except f128 in MMX.
636 if (UseX87) {
637 if (Subtarget.is64Bit() && Subtarget.hasMMX()) {
638 addRegisterClass(MVT::f128, Subtarget.hasVLX() ? &X86::VR128XRegClass
639 : &X86::VR128RegClass);
640 ValueTypeActions.setTypeAction(MVT::f128, TypeSoftenFloat);
641 setOperationAction(ISD::FABS , MVT::f128, Custom);
642 setOperationAction(ISD::FNEG , MVT::f128, Custom);
643 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Custom);
644 }
645
646 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
647 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
648 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
649 {
650 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended());
651 addLegalFPImmediate(TmpFlt); // FLD0
652 TmpFlt.changeSign();
653 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
654
655 bool ignored;
656 APFloat TmpFlt2(+1.0);
657 TmpFlt2.convert(APFloat::x87DoubleExtended(), APFloat::rmNearestTiesToEven,
658 &ignored);
659 addLegalFPImmediate(TmpFlt2); // FLD1
660 TmpFlt2.changeSign();
661 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
662 }
663
664 // Always expand sin/cos functions even though x87 has an instruction.
665 setOperationAction(ISD::FSIN , MVT::f80, Expand);
666 setOperationAction(ISD::FCOS , MVT::f80, Expand);
667 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
668
669 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
670 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
671 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
672 setOperationAction(ISD::FRINT, MVT::f80, Expand);
673 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
674 setOperationAction(ISD::FMA, MVT::f80, Expand);
675 setOperationAction(ISD::LROUND, MVT::f80, Expand);
676 setOperationAction(ISD::LLROUND, MVT::f80, Expand);
677 setOperationAction(ISD::LRINT, MVT::f80, Expand);
678 setOperationAction(ISD::LLRINT, MVT::f80, Expand);
679 }
680
681 // Always use a library call for pow.
682 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
683 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
684 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
685
686 setOperationAction(ISD::FLOG, MVT::f80, Expand);
687 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
688 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
689 setOperationAction(ISD::FEXP, MVT::f80, Expand);
690 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
691 setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
692 setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
693
694 // Some FP actions are always expanded for vector types.
695 for (auto VT : { MVT::v4f32, MVT::v8f32, MVT::v16f32,
696 MVT::v2f64, MVT::v4f64, MVT::v8f64 }) {
697 setOperationAction(ISD::FSIN, VT, Expand);
698 setOperationAction(ISD::FSINCOS, VT, Expand);
699 setOperationAction(ISD::FCOS, VT, Expand);
700 setOperationAction(ISD::FREM, VT, Expand);
701 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
702 setOperationAction(ISD::FPOW, VT, Expand);
703 setOperationAction(ISD::FLOG, VT, Expand);
704 setOperationAction(ISD::FLOG2, VT, Expand);
705 setOperationAction(ISD::FLOG10, VT, Expand);
706 setOperationAction(ISD::FEXP, VT, Expand);
707 setOperationAction(ISD::FEXP2, VT, Expand);
708 }
709
710 // First set operation action for all vector types to either promote
711 // (for widening) or expand (for scalarization). Then we will selectively
712 // turn on ones that can be effectively codegen'd.
713 for (MVT VT : MVT::vector_valuetypes()) {
714 setOperationAction(ISD::SDIV, VT, Expand);
715 setOperationAction(ISD::UDIV, VT, Expand);
716 setOperationAction(ISD::SREM, VT, Expand);
717 setOperationAction(ISD::UREM, VT, Expand);
718 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
719 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
720 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
721 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
722 setOperationAction(ISD::FMA, VT, Expand);
723 setOperationAction(ISD::FFLOOR, VT, Expand);
724 setOperationAction(ISD::FCEIL, VT, Expand);
725 setOperationAction(ISD::FTRUNC, VT, Expand);
726 setOperationAction(ISD::FRINT, VT, Expand);
727 setOperationAction(ISD::FNEARBYINT, VT, Expand);
728 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
729 setOperationAction(ISD::MULHS, VT, Expand);
730 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
731 setOperationAction(ISD::MULHU, VT, Expand);
732 setOperationAction(ISD::SDIVREM, VT, Expand);
733 setOperationAction(ISD::UDIVREM, VT, Expand);
734 setOperationAction(ISD::CTPOP, VT, Expand);
735 setOperationAction(ISD::CTTZ, VT, Expand);
736 setOperationAction(ISD::CTLZ, VT, Expand);
737 setOperationAction(ISD::ROTL, VT, Expand);
738 setOperationAction(ISD::ROTR, VT, Expand);
739 setOperationAction(ISD::BSWAP, VT, Expand);
740 setOperationAction(ISD::SETCC, VT, Expand);
741 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
742 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
743 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
744 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
745 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
746 setOperationAction(ISD::TRUNCATE, VT, Expand);
747 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
748 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
749 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
750 setOperationAction(ISD::SELECT_CC, VT, Expand);
751 for (MVT InnerVT : MVT::vector_valuetypes()) {
752 setTruncStoreAction(InnerVT, VT, Expand);
753
754 setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
755 setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
756
757 // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
758 // types, we have to deal with them whether we ask for Expansion or not.
759 // Setting Expand causes its own optimisation problems though, so leave
760 // them legal.
761 if (VT.getVectorElementType() == MVT::i1)
762 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
763
764 // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
765 // split/scalarized right now.
766 if (VT.getVectorElementType() == MVT::f16)
767 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
768 }
769 }
770
771 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
772 // with -msoft-float, disable use of MMX as well.
773 if (!Subtarget.useSoftFloat() && Subtarget.hasMMX()) {
774 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
775 // No operations on x86mmx supported, everything uses intrinsics.
776 }
777
778 if (!Subtarget.useSoftFloat() && Subtarget.hasSSE1()) {
779 addRegisterClass(MVT::v4f32, Subtarget.hasVLX() ? &X86::VR128XRegClass
780 : &X86::VR128RegClass);
781
782 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
783 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
784 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Custom);
785 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
786 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
787 setOperationAction(ISD::VSELECT, MVT::v4f32, Custom);
788 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
789 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
790 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
791 }
792
793 if (!Subtarget.useSoftFloat() && Subtarget.hasSSE2()) {
794 addRegisterClass(MVT::v2f64, Subtarget.hasVLX() ? &X86::VR128XRegClass
795 : &X86::VR128RegClass);
796
797 // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
798 // registers cannot be used even for integer operations.
799 addRegisterClass(MVT::v16i8, Subtarget.hasVLX() ? &X86::VR128XRegClass
800 : &X86::VR128RegClass);
801 addRegisterClass(MVT::v8i16, Subtarget.hasVLX() ? &X86::VR128XRegClass
802 : &X86::VR128RegClass);
803 addRegisterClass(MVT::v4i32, Subtarget.hasVLX() ? &X86::VR128XRegClass
804 : &X86::VR128RegClass);
805 addRegisterClass(MVT::v2i64, Subtarget.hasVLX() ? &X86::VR128XRegClass
806 : &X86::VR128RegClass);
807
808 for (auto VT : { MVT::v2i8, MVT::v4i8, MVT::v8i8,
809 MVT::v2i16, MVT::v4i16, MVT::v2i32 }) {
810 setOperationAction(ISD::SDIV, VT, Custom);
811 setOperationAction(ISD::SREM, VT, Custom);
812 setOperationAction(ISD::UDIV, VT, Custom);
813 setOperationAction(ISD::UREM, VT, Custom);
814 }
815
816 setOperationAction(ISD::MUL, MVT::v2i8, Custom);
817 setOperationAction(ISD::MUL, MVT::v2i16, Custom);
818 setOperationAction(ISD::MUL, MVT::v2i32, Custom);
819 setOperationAction(ISD::MUL, MVT::v4i8, Custom);
820 setOperationAction(ISD::MUL, MVT::v4i16, Custom);
821 setOperationAction(ISD::MUL, MVT::v8i8, Custom);
822
823 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
824 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
825 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
826 setOperationAction(ISD::MULHU, MVT::v4i32, Custom);
827 setOperationAction(ISD::MULHS, MVT::v4i32, Custom);
828 setOperationAction(ISD::MULHU, MVT::v16i8, Custom);
829 setOperationAction(ISD::MULHS, MVT::v16i8, Custom);
830 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
831 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
832 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
833 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
834 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
835 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Custom);
836
837 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
838 setOperationAction(ISD::SMAX, VT, VT == MVT::v8i16 ? Legal : Custom);
839 setOperationAction(ISD::SMIN, VT, VT == MVT::v8i16 ? Legal : Custom);
840 setOperationAction(ISD::UMAX, VT, VT == MVT::v16i8 ? Legal : Custom);
841 setOperationAction(ISD::UMIN, VT, VT == MVT::v16i8 ? Legal : Custom);
842 }
843
844 setOperationAction(ISD::UADDSAT, MVT::v16i8, Legal);
845 setOperationAction(ISD::SADDSAT, MVT::v16i8, Legal);
846 setOperationAction(ISD::USUBSAT, MVT::v16i8, Legal);
847 setOperationAction(ISD::SSUBSAT, MVT::v16i8, Legal);
848 setOperationAction(ISD::UADDSAT, MVT::v8i16, Legal);
849 setOperationAction(ISD::SADDSAT, MVT::v8i16, Legal);
850 setOperationAction(ISD::USUBSAT, MVT::v8i16, Legal);
851 setOperationAction(ISD::SSUBSAT, MVT::v8i16, Legal);
852 setOperationAction(ISD::UADDSAT, MVT::v4i32, Custom);
853 setOperationAction(ISD::USUBSAT, MVT::v4i32, Custom);
854 setOperationAction(ISD::UADDSAT, MVT::v2i64, Custom);
855 setOperationAction(ISD::USUBSAT, MVT::v2i64, Custom);
856
857 if (!ExperimentalVectorWideningLegalization) {
858 // Use widening instead of promotion.
859 for (auto VT : { MVT::v8i8, MVT::v4i8, MVT::v2i8,
860 MVT::v4i16, MVT::v2i16 }) {
861 setOperationAction(ISD::UADDSAT, VT, Custom);
862 setOperationAction(ISD::SADDSAT, VT, Custom);
863 setOperationAction(ISD::USUBSAT, VT, Custom);
864 setOperationAction(ISD::SSUBSAT, VT, Custom);
865 }
866 }
867
868 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
869 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
870 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
871
872 // Provide custom widening for v2f32 setcc. This is really for VLX when
873 // setcc result type returns v2i1/v4i1 vector for v2f32/v4f32 leading to
874 // type legalization changing the result type to v4i1 during widening.
875 // It works fine for SSE2 and is probably faster so no need to qualify with
876 // VLX support.
877 setOperationAction(ISD::SETCC, MVT::v2i32, Custom);
878
879 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
880 setOperationAction(ISD::SETCC, VT, Custom);
881 setOperationAction(ISD::CTPOP, VT, Custom);
882 setOperationAction(ISD::ABS, VT, Custom);
883
884 // The condition codes aren't legal in SSE/AVX and under AVX512 we use
885 // setcc all the way to isel and prefer SETGT in some isel patterns.
886 setCondCodeAction(ISD::SETLT, VT, Custom);
887 setCondCodeAction(ISD::SETLE, VT, Custom);
888 }
889
890 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
891 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
892 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
893 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
894 setOperationAction(ISD::VSELECT, VT, Custom);
895 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
896 }
897
898 // We support custom legalizing of sext and anyext loads for specific
899 // memory vector types which we can load as a scalar (or sequence of
900 // scalars) and extend in-register to a legal 128-bit vector type. For sext
901 // loads these must work with a single scalar load.
902 for (MVT VT : MVT::integer_vector_valuetypes()) {
903 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
904 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
905 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
906 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
907 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
908 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
909 }
910
911 for (auto VT : { MVT::v2f64, MVT::v2i64 }) {
912 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
913 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
914 setOperationAction(ISD::VSELECT, VT, Custom);
915
916 if (VT == MVT::v2i64 && !Subtarget.is64Bit())
917 continue;
918
919 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
920 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
921 }
922
923 // Custom lower v2i64 and v2f64 selects.
924 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
925 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
926 setOperationAction(ISD::SELECT, MVT::v4i32, Custom);
927 setOperationAction(ISD::SELECT, MVT::v8i16, Custom);
928 setOperationAction(ISD::SELECT, MVT::v16i8, Custom);
929
930 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
931 setOperationAction(ISD::FP_TO_SINT, MVT::v2i32, Custom);
932 setOperationAction(ISD::FP_TO_SINT, MVT::v2i16, Custom);
933
934 // Custom legalize these to avoid over promotion or custom promotion.
935 setOperationAction(ISD::FP_TO_SINT, MVT::v2i8, Custom);
936 setOperationAction(ISD::FP_TO_SINT, MVT::v4i8, Custom);
937 setOperationAction(ISD::FP_TO_SINT, MVT::v8i8, Custom);
938 setOperationAction(ISD::FP_TO_SINT, MVT::v2i16, Custom);
939 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
940 setOperationAction(ISD::FP_TO_UINT, MVT::v2i8, Custom);
941 setOperationAction(ISD::FP_TO_UINT, MVT::v4i8, Custom);
942 setOperationAction(ISD::FP_TO_UINT, MVT::v8i8, Custom);
943 setOperationAction(ISD::FP_TO_UINT, MVT::v2i16, Custom);
944 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
945
946 // By marking FP_TO_SINT v8i16 as Custom, will trick type legalization into
947 // promoting v8i8 FP_TO_UINT into FP_TO_SINT. When the v8i16 FP_TO_SINT is
948 // split again based on the input type, this will cause an AssertSExt i16 to
949 // be emitted instead of an AssertZExt. This will allow packssdw followed by
950 // packuswb to be used to truncate to v8i8. This is necessary since packusdw
951 // isn't available until sse4.1.
952 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom);
953
954 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
955 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
956
957 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
958
959 // Fast v2f32 UINT_TO_FP( v2i32 ) custom conversion.
960 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
961
962 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
963 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
964
965 // We want to legalize this to an f64 load rather than an i64 load on
966 // 64-bit targets and two 32-bit loads on a 32-bit target. Similar for
967 // store.
968 setOperationAction(ISD::LOAD, MVT::v2f32, Custom);
969 setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
970 setOperationAction(ISD::LOAD, MVT::v4i16, Custom);
971 setOperationAction(ISD::LOAD, MVT::v8i8, Custom);
972 setOperationAction(ISD::STORE, MVT::v2f32, Custom);
973 setOperationAction(ISD::STORE, MVT::v2i32, Custom);
974 setOperationAction(ISD::STORE, MVT::v4i16, Custom);
975 setOperationAction(ISD::STORE, MVT::v8i8, Custom);
976
977 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
978 setOperationAction(ISD::BITCAST, MVT::v4i16, Custom);
979 setOperationAction(ISD::BITCAST, MVT::v8i8, Custom);
980 if (!Subtarget.hasAVX512())
981 setOperationAction(ISD::BITCAST, MVT::v16i1, Custom);
982
983 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
984 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
985 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
986
987 if (ExperimentalVectorWideningLegalization) {
988 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
989
990 setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom);
991 setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom);
992 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Custom);
993 setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom);
994 setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom);
995 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom);
996 } else {
997 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i64, Custom);
998 }
999
1000 // In the customized shift lowering, the legal v4i32/v2i64 cases
1001 // in AVX2 will be recognized.
1002 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1003 setOperationAction(ISD::SRL, VT, Custom);
1004 setOperationAction(ISD::SHL, VT, Custom);
1005 setOperationAction(ISD::SRA, VT, Custom);
1006 }
1007
1008 setOperationAction(ISD::ROTL, MVT::v4i32, Custom);
1009 setOperationAction(ISD::ROTL, MVT::v8i16, Custom);
1010
1011 // With AVX512, expanding (and promoting the shifts) is better.
1012 if (!Subtarget.hasAVX512())
1013 setOperationAction(ISD::ROTL, MVT::v16i8, Custom);
1014 }
1015
1016 if (!Subtarget.useSoftFloat() && Subtarget.hasSSSE3()) {
1017 setOperationAction(ISD::ABS, MVT::v16i8, Legal);
1018 setOperationAction(ISD::ABS, MVT::v8i16, Legal);
1019 setOperationAction(ISD::ABS, MVT::v4i32, Legal);
1020 setOperationAction(ISD::BITREVERSE, MVT::v16i8, Custom);
1021 setOperationAction(ISD::CTLZ, MVT::v16i8, Custom);
1022 setOperationAction(ISD::CTLZ, MVT::v8i16, Custom);
1023 setOperationAction(ISD::CTLZ, MVT::v4i32, Custom);
1024 setOperationAction(ISD::CTLZ, MVT::v2i64, Custom);
1025
1026 // These might be better off as horizontal vector ops.
1027 setOperationAction(ISD::ADD, MVT::i16, Custom);
1028 setOperationAction(ISD::ADD, MVT::i32, Custom);
1029 setOperationAction(ISD::SUB, MVT::i16, Custom);
1030 setOperationAction(ISD::SUB, MVT::i32, Custom);
1031 }
1032
1033 if (!Subtarget.useSoftFloat() && Subtarget.hasSSE41()) {
1034 for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
1035 setOperationAction(ISD::FFLOOR, RoundedTy, Legal);
1036 setOperationAction(ISD::FCEIL, RoundedTy, Legal);
1037 setOperationAction(ISD::FTRUNC, RoundedTy, Legal);
1038 setOperationAction(ISD::FRINT, RoundedTy, Legal);
1039 setOperationAction(ISD::FNEARBYINT, RoundedTy, Legal);
1040 }
1041
1042 setOperationAction(ISD::SMAX, MVT::v16i8, Legal);
1043 setOperationAction(ISD::SMAX, MVT::v4i32, Legal);
1044 setOperationAction(ISD::UMAX, MVT::v8i16, Legal);
1045 setOperationAction(ISD::UMAX, MVT::v4i32, Legal);
1046 setOperationAction(ISD::SMIN, MVT::v16i8, Legal);
1047 setOperationAction(ISD::SMIN, MVT::v4i32, Legal);
1048 setOperationAction(ISD::UMIN, MVT::v8i16, Legal);
1049 setOperationAction(ISD::UMIN, MVT::v4i32, Legal);
1050
1051 // FIXME: Do we need to handle scalar-to-vector here?
1052 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1053
1054 // We directly match byte blends in the backend as they match the VSELECT
1055 // condition form.
1056 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
1057
1058 // SSE41 brings specific instructions for doing vector sign extend even in
1059 // cases where we don't have SRA.
1060 for (auto VT : { MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1061 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, VT, Legal);
1062 setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Legal);
1063 }
1064
1065 if (!ExperimentalVectorWideningLegalization) {
1066 // Avoid narrow result types when widening. The legal types are listed
1067 // in the next loop.
1068 for (MVT VT : MVT::integer_vector_valuetypes()) {
1069 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
1070 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
1071 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
1072 }
1073 }
1074
1075 // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
1076 for (auto LoadExtOp : { ISD::SEXTLOAD, ISD::ZEXTLOAD }) {
1077 setLoadExtAction(LoadExtOp, MVT::v8i16, MVT::v8i8, Legal);
1078 setLoadExtAction(LoadExtOp, MVT::v4i32, MVT::v4i8, Legal);
1079 if (!ExperimentalVectorWideningLegalization)
1080 setLoadExtAction(LoadExtOp, MVT::v2i32, MVT::v2i8, Legal);
1081 setLoadExtAction(LoadExtOp, MVT::v2i64, MVT::v2i8, Legal);
1082 setLoadExtAction(LoadExtOp, MVT::v4i32, MVT::v4i16, Legal);
1083 setLoadExtAction(LoadExtOp, MVT::v2i64, MVT::v2i16, Legal);
1084 setLoadExtAction(LoadExtOp, MVT::v2i64, MVT::v2i32, Legal);
1085 }
1086
1087 // i8 vectors are custom because the source register and source
1088 // source memory operand types are not the same width.
1089 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1090 }
1091
1092 if (!Subtarget.useSoftFloat() && Subtarget.hasXOP()) {
1093 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64,
1094 MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 })
1095 setOperationAction(ISD::ROTL, VT, Custom);
1096
1097 // XOP can efficiently perform BITREVERSE with VPPERM.
1098 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 })
1099 setOperationAction(ISD::BITREVERSE, VT, Custom);
1100
1101 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64,
1102 MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 })
1103 setOperationAction(ISD::BITREVERSE, VT, Custom);
1104 }
1105
1106 if (!Subtarget.useSoftFloat() && Subtarget.hasAVX()) {
1107 bool HasInt256 = Subtarget.hasInt256();
1108
1109 addRegisterClass(MVT::v32i8, Subtarget.hasVLX() ? &X86::VR256XRegClass
1110 : &X86::VR256RegClass);
1111 addRegisterClass(MVT::v16i16, Subtarget.hasVLX() ? &X86::VR256XRegClass
1112 : &X86::VR256RegClass);
1113 addRegisterClass(MVT::v8i32, Subtarget.hasVLX() ? &X86::VR256XRegClass
1114 : &X86::VR256RegClass);
1115 addRegisterClass(MVT::v8f32, Subtarget.hasVLX() ? &X86::VR256XRegClass
1116 : &X86::VR256RegClass);
1117 addRegisterClass(MVT::v4i64, Subtarget.hasVLX() ? &X86::VR256XRegClass
1118 : &X86::VR256RegClass);
1119 addRegisterClass(MVT::v4f64, Subtarget.hasVLX() ? &X86::VR256XRegClass
1120 : &X86::VR256RegClass);
1121
1122 for (auto VT : { MVT::v8f32, MVT::v4f64 }) {
1123 setOperationAction(ISD::FFLOOR, VT, Legal);
1124 setOperationAction(ISD::FCEIL, VT, Legal);
1125 setOperationAction(ISD::FTRUNC, VT, Legal);
1126 setOperationAction(ISD::FRINT, VT, Legal);
1127 setOperationAction(ISD::FNEARBYINT, VT, Legal);
1128 setOperationAction(ISD::FNEG, VT, Custom);
1129 setOperationAction(ISD::FABS, VT, Custom);
1130 setOperationAction(ISD::FCOPYSIGN, VT, Custom);
1131 }
1132
1133 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1134 // even though v8i16 is a legal type.
1135 setOperationPromotedToType(ISD::FP_TO_SINT, MVT::v8i16, MVT::v8i32);
1136 setOperationPromotedToType(ISD::FP_TO_UINT, MVT::v8i16, MVT::v8i32);
1137 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1138
1139 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1140 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1141
1142 if (!Subtarget.hasAVX512())
1143 setOperationAction(ISD::BITCAST, MVT::v32i1, Custom);
1144
1145 // In the customized shift lowering, the legal v8i32/v4i64 cases
1146 // in AVX2 will be recognized.
1147 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1148 setOperationAction(ISD::SRL, VT, Custom);
1149 setOperationAction(ISD::SHL, VT, Custom);
1150 setOperationAction(ISD::SRA, VT, Custom);
1151 }
1152
1153 // These types need custom splitting if their input is a 128-bit vector.
1154 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1155 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1156 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1157 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1158
1159 setOperationAction(ISD::ROTL, MVT::v8i32, Custom);
1160 setOperationAction(ISD::ROTL, MVT::v16i16, Custom);
1161
1162 // With BWI, expanding (and promoting the shifts) is the better.
1163 if (!Subtarget.hasBWI())
1164 setOperationAction(ISD::ROTL, MVT::v32i8, Custom);
1165
1166 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1167 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1168 setOperationAction(ISD::SELECT, MVT::v8i32, Custom);
1169 setOperationAction(ISD::SELECT, MVT::v16i16, Custom);
1170 setOperationAction(ISD::SELECT, MVT::v32i8, Custom);
1171 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1172
1173 for (auto VT : { MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1174 setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
1175 setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
1176 setOperationAction(ISD::ANY_EXTEND, VT, Custom);
1177 }
1178
1179 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1180 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1181 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1182 setOperationAction(ISD::BITREVERSE, MVT::v32i8, Custom);
1183
1184 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1185 setOperationAction(ISD::SETCC, VT, Custom);
1186 setOperationAction(ISD::CTPOP, VT, Custom);
1187 setOperationAction(ISD::CTLZ, VT, Custom);
1188
1189 // The condition codes aren't legal in SSE/AVX and under AVX512 we use
1190 // setcc all the way to isel and prefer SETGT in some isel patterns.
1191 setCondCodeAction(ISD::SETLT, VT, Custom);
1192 setCondCodeAction(ISD::SETLE, VT, Custom);
1193 }
1194
1195 if (Subtarget.hasAnyFMA()) {
1196 for (auto VT : { MVT::f32, MVT::f64, MVT::v4f32, MVT::v8f32,
1197 MVT::v2f64, MVT::v4f64 })
1198 setOperationAction(ISD::FMA, VT, Legal);
1199 }
1200
1201 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1202 setOperationAction(ISD::ADD, VT, HasInt256 ? Legal : Custom);
1203 setOperationAction(ISD::SUB, VT, HasInt256 ? Legal : Custom);
1204 }
1205
1206 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1207 setOperationAction(ISD::MUL, MVT::v8i32, HasInt256 ? Legal : Custom);
1208 setOperationAction(ISD::MUL, MVT::v16i16, HasInt256 ? Legal : Custom);
1209 setOperationAction(ISD::MUL, MVT::v32i8, Custom);
1210
1211 setOperationAction(ISD::MULHU, MVT::v8i32, Custom);
1212 setOperationAction(ISD::MULHS, MVT::v8i32, Custom);
1213 setOperationAction(ISD::MULHU, MVT::v16i16, HasInt256 ? Legal : Custom);
1214 setOperationAction(ISD::MULHS, MVT::v16i16, HasInt256 ? Legal : Custom);
1215 setOperationAction(ISD::MULHU, MVT::v32i8, Custom);
1216 setOperationAction(ISD::MULHS, MVT::v32i8, Custom);
1217
1218 setOperationAction(ISD::ABS, MVT::v4i64, Custom);
1219 setOperationAction(ISD::SMAX, MVT::v4i64, Custom);
1220 setOperationAction(ISD::UMAX, MVT::v4i64, Custom);
1221 setOperationAction(ISD::SMIN, MVT::v4i64, Custom);
1222 setOperationAction(ISD::UMIN, MVT::v4i64, Custom);
1223
1224 setOperationAction(ISD::UADDSAT, MVT::v32i8, HasInt256 ? Legal : Custom);
1225 setOperationAction(ISD::SADDSAT, MVT::v32i8, HasInt256 ? Legal : Custom);
1226 setOperationAction(ISD::USUBSAT, MVT::v32i8, HasInt256 ? Legal : Custom);
1227 setOperationAction(ISD::SSUBSAT, MVT::v32i8, HasInt256 ? Legal : Custom);
1228 setOperationAction(ISD::UADDSAT, MVT::v16i16, HasInt256 ? Legal : Custom);
1229 setOperationAction(ISD::SADDSAT, MVT::v16i16, HasInt256 ? Legal : Custom);
1230 setOperationAction(ISD::USUBSAT, MVT::v16i16, HasInt256 ? Legal : Custom);
1231 setOperationAction(ISD::SSUBSAT, MVT::v16i16, HasInt256 ? Legal : Custom);
1232
1233 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32 }) {
1234 setOperationAction(ISD::ABS, VT, HasInt256 ? Legal : Custom);
1235 setOperationAction(ISD::SMAX, VT, HasInt256 ? Legal : Custom);
1236 setOperationAction(ISD::UMAX, VT, HasInt256 ? Legal : Custom);
1237 setOperationAction(ISD::SMIN, VT, HasInt256 ? Legal : Custom);
1238 setOperationAction(ISD::UMIN, VT, HasInt256 ? Legal : Custom);
1239 }
1240
1241 for (auto VT : {MVT::v16i16, MVT::v8i32, MVT::v4i64}) {
1242 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, VT, Custom);
1243 setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Custom);
1244 }
1245
1246 if (HasInt256) {
1247 // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1248 // when we have a 256bit-wide blend with immediate.
1249 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1250
1251 // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1252 for (auto LoadExtOp : { ISD::SEXTLOAD, ISD::ZEXTLOAD }) {
1253 setLoadExtAction(LoadExtOp, MVT::v16i16, MVT::v16i8, Legal);
1254 setLoadExtAction(LoadExtOp, MVT::v8i32, MVT::v8i8, Legal);
1255 setLoadExtAction(LoadExtOp, MVT::v4i64, MVT::v4i8, Legal);
1256 setLoadExtAction(LoadExtOp, MVT::v8i32, MVT::v8i16, Legal);
1257 setLoadExtAction(LoadExtOp, MVT::v4i64, MVT::v4i16, Legal);
1258 setLoadExtAction(LoadExtOp, MVT::v4i64, MVT::v4i32, Legal);
1259 }
1260 }
1261
1262 for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1263 MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64 }) {
1264 setOperationAction(ISD::MLOAD, VT, Legal);
1265 setOperationAction(ISD::MSTORE, VT, Legal);
1266 }
1267
1268 // Extract subvector is special because the value type
1269 // (result) is 128-bit but the source is 256-bit wide.
1270 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64,
1271 MVT::v4f32, MVT::v2f64 }) {
1272 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1273 }
1274
1275 // Custom lower several nodes for 256-bit types.
1276 for (MVT VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64,
1277 MVT::v8f32, MVT::v4f64 }) {
1278 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1279 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1280 setOperationAction(ISD::VSELECT, VT, Custom);
1281 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1282 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1283 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1284 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Legal);
1285 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1286 setOperationAction(ISD::STORE, VT, Custom);
1287 }
1288
1289 if (HasInt256)
1290 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1291
1292 if (HasInt256) {
1293 // Custom legalize 2x32 to get a little better code.
1294 setOperationAction(ISD::MGATHER, MVT::v2f32, Custom);
1295 setOperationAction(ISD::MGATHER, MVT::v2i32, Custom);
1296
1297 for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1298 MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64 })
1299 setOperationAction(ISD::MGATHER, VT, Custom);
1300 }
1301 }
1302
1303 // This block controls legalization of the mask vector sizes that are
1304 // available with AVX512. 512-bit vectors are in a separate block controlled
1305 // by useAVX512Regs.
1306 if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512()) {
1307 addRegisterClass(MVT::v1i1, &X86::VK1RegClass);
1308 addRegisterClass(MVT::v2i1, &X86::VK2RegClass);
1309 addRegisterClass(MVT::v4i1, &X86::VK4RegClass);
1310 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1311 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1312
1313 setOperationAction(ISD::SELECT, MVT::v1i1, Custom);
1314 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v1i1, Custom);
1315 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i1, Custom);
1316
1317 setOperationPromotedToType(ISD::FP_TO_SINT, MVT::v8i1, MVT::v8i32);
1318 setOperationPromotedToType(ISD::FP_TO_UINT, MVT::v8i1, MVT::v8i32);
1319 setOperationPromotedToType(ISD::FP_TO_SINT, MVT::v4i1, MVT::v4i32);
1320 setOperationPromotedToType(ISD::FP_TO_UINT, MVT::v4i1, MVT::v4i32);
1321 setOperationAction(ISD::FP_TO_SINT, MVT::v2i1, Custom);
1322 setOperationAction(ISD::FP_TO_UINT, MVT::v2i1, Custom);
1323
1324 // There is no byte sized k-register load or store without AVX512DQ.
1325 if (!Subtarget.hasDQI()) {
1326 setOperationAction(ISD::LOAD, MVT::v1i1, Custom);
1327 setOperationAction(ISD::LOAD, MVT::v2i1, Custom);
1328 setOperationAction(ISD::LOAD, MVT::v4i1, Custom);
1329 setOperationAction(ISD::LOAD, MVT::v8i1, Custom);
1330
1331 setOperationAction(ISD::STORE, MVT::v1i1, Custom);
1332 setOperationAction(ISD::STORE, MVT::v2i1, Custom);
1333 setOperationAction(ISD::STORE, MVT::v4i1, Custom);
1334 setOperationAction(ISD::STORE, MVT::v8i1, Custom);
1335 }
1336
1337 // Extends of v16i1/v8i1/v4i1/v2i1 to 128-bit vectors.
1338 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1339 setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
1340 setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
1341 setOperationAction(ISD::ANY_EXTEND, VT, Custom);
1342 }
1343
1344 for (auto VT : { MVT::v2i1, MVT::v4i1, MVT::v8i1, MVT::v16i1 }) {
1345 setOperationAction(ISD::ADD, VT, Custom);
1346 setOperationAction(ISD::SUB, VT, Custom);
1347 setOperationAction(ISD::MUL, VT, Custom);
1348 setOperationAction(ISD::SETCC, VT, Custom);
1349 setOperationAction(ISD::SELECT, VT, Custom);
1350 setOperationAction(ISD::TRUNCATE, VT, Custom);
1351 setOperationAction(ISD::UADDSAT, VT, Custom);
1352 setOperationAction(ISD::SADDSAT, VT, Custom);
1353 setOperationAction(ISD::USUBSAT, VT, Custom);
1354 setOperationAction(ISD::SSUBSAT, VT, Custom);
1355
1356 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1357 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1358 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1359 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1360 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1361 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1362 setOperationAction(ISD::VSELECT, VT, Expand);
1363 }
1364
1365 for (auto VT : { MVT::v1i1, MVT::v2i1, MVT::v4i1, MVT::v8i1 })
1366 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1367 }
1368
1369 // This block controls legalization for 512-bit operations with 32/64 bit
1370 // elements. 512-bits can be disabled based on prefer-vector-width and
1371 // required-vector-width function attributes.
1372 if (!Subtarget.useSoftFloat() && Subtarget.useAVX512Regs()) {
1373 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1374 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1375 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1376 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1377
1378 for (auto ExtType : {ISD::ZEXTLOAD, ISD::SEXTLOAD}) {
1379 setLoadExtAction(ExtType, MVT::v16i32, MVT::v16i8, Legal);
1380 setLoadExtAction(ExtType, MVT::v16i32, MVT::v16i16, Legal);
1381 setLoadExtAction(ExtType, MVT::v8i64, MVT::v8i8, Legal);
1382 setLoadExtAction(ExtType, MVT::v8i64, MVT::v8i16, Legal);
1383 setLoadExtAction(ExtType, MVT::v8i64, MVT::v8i32, Legal);
1384 }
1385
1386 for (MVT VT : { MVT::v16f32, MVT::v8f64 }) {
1387 setOperationAction(ISD::FNEG, VT, Custom);
1388 setOperationAction(ISD::FABS, VT, Custom);
1389 setOperationAction(ISD::FMA, VT, Legal);
1390 setOperationAction(ISD::FCOPYSIGN, VT, Custom);
1391 }
1392
1393 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1394 setOperationPromotedToType(ISD::FP_TO_SINT, MVT::v16i16, MVT::v16i32);
1395 setOperationPromotedToType(ISD::FP_TO_SINT, MVT::v16i8, MVT::v16i32);
1396 setOperationPromotedToType(ISD::FP_TO_SINT, MVT::v16i1, MVT::v16i32);
1397 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1398 setOperationPromotedToType(ISD::FP_TO_UINT, MVT::v16i1, MVT::v16i32);
1399 setOperationPromotedToType(ISD::FP_TO_UINT, MVT::v16i8, MVT::v16i32);
1400 setOperationPromotedToType(ISD::FP_TO_UINT, MVT::v16i16, MVT::v16i32);
1401 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1402 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1403
1404 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Legal);
1405 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Legal);
1406 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Legal);
1407 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Legal);
1408 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Legal);
1409
1410 if (!Subtarget.hasVLX()) {
1411 // With 512-bit vectors and no VLX, we prefer to widen MLOAD/MSTORE
1412 // to 512-bit rather than use the AVX2 instructions so that we can use
1413 // k-masks.
1414 for (auto VT : {MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1415 MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64}) {
1416 setOperationAction(ISD::MLOAD, VT, Custom);
1417 setOperationAction(ISD::MSTORE, VT, Custom);
1418 }
1419 }
1420
1421 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1422 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1423 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1424 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1425 setOperationAction(ISD::ANY_EXTEND, MVT::v16i32, Custom);
1426 setOperationAction(ISD::ANY_EXTEND, MVT::v8i64, Custom);
1427 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1428 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1429
1430 if (ExperimentalVectorWideningLegalization) {
1431 // Need to custom widen this if we don't have AVX512BW.
1432 setOperationAction(ISD::ANY_EXTEND, MVT::v8i8, Custom);
1433 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i8, Custom);
1434 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i8, Custom);
1435 }
1436
1437 for (auto VT : { MVT::v16f32, MVT::v8f64 }) {
1438 setOperationAction(ISD::FFLOOR, VT, Legal);
1439 setOperationAction(ISD::FCEIL, VT, Legal);
1440 setOperationAction(ISD::FTRUNC, VT, Legal);
1441 setOperationAction(ISD::FRINT, VT, Legal);
1442 setOperationAction(ISD::FNEARBYINT, VT, Legal);
1443 }
1444
1445 // Without BWI we need to use custom lowering to handle MVT::v64i8 input.
1446 for (auto VT : {MVT::v16i32, MVT::v8i64, MVT::v64i8}) {
1447 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, VT, Custom);
1448 setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Custom);
1449 }
1450
1451 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1452 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1453 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1454 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1455
1456 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1457 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1458
1459 setOperationAction(ISD::MULHU, MVT::v16i32, Custom);
1460 setOperationAction(ISD::MULHS, MVT::v16i32, Custom);
1461
1462 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1463 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1464 setOperationAction(ISD::SELECT, MVT::v16i32, Custom);
1465 setOperationAction(ISD::SELECT, MVT::v32i16, Custom);
1466 setOperationAction(ISD::SELECT, MVT::v64i8, Custom);
1467 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1468
1469 for (auto VT : { MVT::v16i32, MVT::v8i64 }) {
1470 setOperationAction(ISD::SMAX, VT, Legal);
1471 setOperationAction(ISD::UMAX, VT, Legal);
1472 setOperationAction(ISD::SMIN, VT, Legal);
1473 setOperationAction(ISD::UMIN, VT, Legal);
1474 setOperationAction(ISD::ABS, VT, Legal);
1475 setOperationAction(ISD::SRL, VT, Custom);
1476 setOperationAction(ISD::SHL, VT, Custom);
1477 setOperationAction(ISD::SRA, VT, Custom);
1478 setOperationAction(ISD::CTPOP, VT, Custom);
1479 setOperationAction(ISD::ROTL, VT, Custom);
1480 setOperationAction(ISD::ROTR, VT, Custom);
1481 setOperationAction(ISD::SETCC, VT, Custom);
1482
1483 // The condition codes aren't legal in SSE/AVX and under AVX512 we use
1484 // setcc all the way to isel and prefer SETGT in some isel patterns.
1485 setCondCodeAction(ISD::SETLT, VT, Custom);
1486 setCondCodeAction(ISD::SETLE, VT, Custom);
1487 }
1488
1489 if (Subtarget.hasDQI()) {
1490 setOperationAction(ISD::SINT_TO_FP, MVT::v8i64, Legal);
1491 setOperationAction(ISD::UINT_TO_FP, MVT::v8i64, Legal);
1492 setOperationAction(ISD::FP_TO_SINT, MVT::v8i64, Legal);
1493 setOperationAction(ISD::FP_TO_UINT, MVT::v8i64, Legal);
1494
1495 setOperationAction(ISD::MUL, MVT::v8i64, Legal);
1496 }
1497
1498 if (Subtarget.hasCDI()) {
1499 // NonVLX sub-targets extend 128/256 vectors to use the 512 version.
1500 for (auto VT : { MVT::v16i32, MVT::v8i64} ) {
1501 setOperationAction(ISD::CTLZ, VT, Legal);
1502 }
1503 } // Subtarget.hasCDI()
1504
1505 if (Subtarget.hasVPOPCNTDQ()) {
1506 for (auto VT : { MVT::v16i32, MVT::v8i64 })
1507 setOperationAction(ISD::CTPOP, VT, Legal);
1508 }
1509
1510 // Extract subvector is special because the value type
1511 // (result) is 256-bit but the source is 512-bit wide.
1512 // 128-bit was made Legal under AVX1.
1513 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64,
1514 MVT::v8f32, MVT::v4f64 })
1515 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1516
1517 for (auto VT : { MVT::v16i32, MVT::v8i64, MVT::v16f32, MVT::v8f64 }) {
1518 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1519 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1520 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1521 setOperationAction(ISD::VSELECT, VT, Custom);
1522 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1523 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1524 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Legal);
1525 setOperationAction(ISD::MLOAD, VT, Legal);
1526 setOperationAction(ISD::MSTORE, VT, Legal);
1527 setOperationAction(ISD::MGATHER, VT, Custom);
1528 setOperationAction(ISD::MSCATTER, VT, Custom);
1529 }
1530 // Need to custom split v32i16/v64i8 bitcasts.
1531 if (!Subtarget.hasBWI()) {
1532 setOperationAction(ISD::BITCAST, MVT::v32i16, Custom);
1533 setOperationAction(ISD::BITCAST, MVT::v64i8, Custom);
1534 }
1535
1536 if (Subtarget.hasVBMI2()) {
1537 for (auto VT : { MVT::v16i32, MVT::v8i64 }) {
1538 setOperationAction(ISD::FSHL, VT, Custom);
1539 setOperationAction(ISD::FSHR, VT, Custom);
1540 }
1541 }
1542 }// has AVX-512
1543
1544 // This block controls legalization for operations that don't have
1545 // pre-AVX512 equivalents. Without VLX we use 512-bit operations for
1546 // narrower widths.
1547 if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512()) {
1548 // These operations are handled on non-VLX by artificially widening in
1549 // isel patterns.
1550 // TODO: Custom widen in lowering on non-VLX and drop the isel patterns?
1551
1552 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1553 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1554 setOperationAction(ISD::FP_TO_UINT, MVT::v2i32, Custom);
1555 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1556 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1557
1558 for (auto VT : { MVT::v2i64, MVT::v4i64 }) {
1559 setOperationAction(ISD::SMAX, VT, Legal);
1560 setOperationAction(ISD::UMAX, VT, Legal);
1561 setOperationAction(ISD::SMIN, VT, Legal);
1562 setOperationAction(ISD::UMIN, VT, Legal);
1563 setOperationAction(ISD::ABS, VT, Legal);
1564 }
1565
1566 for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 }) {
1567 setOperationAction(ISD::ROTL, VT, Custom);
1568 setOperationAction(ISD::ROTR, VT, Custom);
1569 }
1570
1571 // Custom legalize 2x32 to get a little better code.
1572 setOperationAction(ISD::MSCATTER, MVT::v2f32, Custom);
1573 setOperationAction(ISD::MSCATTER, MVT::v2i32, Custom);
1574
1575 for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1576 MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64 })
1577 setOperationAction(ISD::MSCATTER, VT, Custom);
1578
1579 if (Subtarget.hasDQI()) {
1580 for (auto VT : { MVT::v2i64, MVT::v4i64 }) {
1581 setOperationAction(ISD::SINT_TO_FP, VT, Legal);
1582 setOperationAction(ISD::UINT_TO_FP, VT, Legal);
1583 setOperationAction(ISD::FP_TO_SINT, VT, Legal);
1584 setOperationAction(ISD::FP_TO_UINT, VT, Legal);
1585
1586 setOperationAction(ISD::MUL, VT, Legal);
1587 }
1588 }
1589
1590 if (Subtarget.hasCDI()) {
1591 for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 }) {
1592 setOperationAction(ISD::CTLZ, VT, Legal);
1593 }
1594 } // Subtarget.hasCDI()
1595
1596 if (Subtarget.hasVPOPCNTDQ()) {
1597 for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 })
1598 setOperationAction(ISD::CTPOP, VT, Legal);
1599 }
1600 }
1601
1602 // This block control legalization of v32i1/v64i1 which are available with
1603 // AVX512BW. 512-bit v32i16 and v64i8 vector legalization is controlled with
1604 // useBWIRegs.
1605 if (!Subtarget.useSoftFloat() && Subtarget.hasBWI()) {
1606 addRegisterClass(MVT::v32i1, &X86::VK32RegClass);
1607 addRegisterClass(MVT::v64i1, &X86::VK64RegClass);
1608
1609 for (auto VT : { MVT::v32i1, MVT::v64i1 }) {
1610 setOperationAction(ISD::ADD, VT, Custom);
1611 setOperationAction(ISD::SUB, VT, Custom);
1612 setOperationAction(ISD::MUL, VT, Custom);
1613 setOperationAction(ISD::VSELECT, VT, Expand);
1614 setOperationAction(ISD::UADDSAT, VT, Custom);
1615 setOperationAction(ISD::SADDSAT, VT, Custom);
1616 setOperationAction(ISD::USUBSAT, VT, Custom);
1617 setOperationAction(ISD::SSUBSAT, VT, Custom);
1618
1619 setOperationAction(ISD::TRUNCATE, VT, Custom);
1620 setOperationAction(ISD::SETCC, VT, Custom);
1621 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1622 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1623 setOperationAction(ISD::SELECT, VT, Custom);
1624 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1625 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1626 }
1627
1628 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i1, Custom);
1629 setOperationAction(ISD::CONCAT_VECTORS, MVT::v64i1, Custom);
1630 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v32i1, Custom);
1631 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v64i1, Custom);
1632 for (auto VT : { MVT::v16i1, MVT::v32i1 })
1633 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1634
1635 // Extends from v32i1 masks to 256-bit vectors.
1636 setOperationAction(ISD::SIGN_EXTEND, MVT::v32i8, Custom);
1637 setOperationAction(ISD::ZERO_EXTEND, MVT::v32i8, Custom);
1638 setOperationAction(ISD::ANY_EXTEND, MVT::v32i8, Custom);
1639 }
1640
1641 // This block controls legalization for v32i16 and v64i8. 512-bits can be
1642 // disabled based on prefer-vector-width and required-vector-width function
1643 // attributes.
1644 if (!Subtarget.useSoftFloat() && Subtarget.useBWIRegs()) {
1645 addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1646 addRegisterClass(MVT::v64i8, &X86::VR512RegClass);
1647
1648 // Extends from v64i1 masks to 512-bit vectors.
1649 setOperationAction(ISD::SIGN_EXTEND, MVT::v64i8, Custom);
1650 setOperationAction(ISD::ZERO_EXTEND, MVT::v64i8, Custom);
1651 setOperationAction(ISD::ANY_EXTEND, MVT::v64i8, Custom);
1652
1653 setOperationAction(ISD::MUL, MVT::v32i16, Legal);
1654 setOperationAction(ISD::MUL, MVT::v64i8, Custom);
1655 setOperationAction(ISD::MULHS, MVT::v32i16, Legal);
1656 setOperationAction(ISD::MULHU, MVT::v32i16, Legal);
1657 setOperationAction(ISD::MULHS, MVT::v64i8, Custom);
1658 setOperationAction(ISD::MULHU, MVT::v64i8, Custom);
1659 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i16, Custom);
1660 setOperationAction(ISD::CONCAT_VECTORS, MVT::v64i8, Custom);
1661 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v32i16, Legal);
1662 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v64i8, Legal);
1663 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v32i16, Custom);
1664 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v64i8, Custom);
1665 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v32i16, Custom);
1666 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v64i8, Custom);
1667 setOperationAction(ISD::SIGN_EXTEND, MVT::v32i16, Custom);
1668 setOperationAction(ISD::ZERO_EXTEND, MVT::v32i16, Custom);
1669 setOperationAction(ISD::ANY_EXTEND, MVT::v32i16, Custom);
1670 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v32i16, Custom);
1671 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v64i8, Custom);
1672 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v32i16, Custom);
1673 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v64i8, Custom);
1674 setOperationAction(ISD::TRUNCATE, MVT::v32i8, Custom);
1675 setOperationAction(ISD::BITREVERSE, MVT::v64i8, Custom);
1676
1677 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v32i16, Custom);
1678 setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, MVT::v32i16, Custom);
1679
1680 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Legal);
1681
1682 for (auto VT : { MVT::v64i8, MVT::v32i16 }) {
1683 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1684 setOperationAction(ISD::VSELECT, VT, Custom);
1685 setOperationAction(ISD::ABS, VT, Legal);
1686 setOperationAction(ISD::SRL, VT, Custom);
1687 setOperationAction(ISD::SHL, VT, Custom);
1688 setOperationAction(ISD::SRA, VT, Custom);
1689 setOperationAction(ISD::MLOAD, VT, Legal);
1690 setOperationAction(ISD::MSTORE, VT, Legal);
1691 setOperationAction(ISD::CTPOP, VT, Custom);
1692 setOperationAction(ISD::CTLZ, VT, Custom);
1693 setOperationAction(ISD::SMAX, VT, Legal);
1694 setOperationAction(ISD::UMAX, VT, Legal);
1695 setOperationAction(ISD::SMIN, VT, Legal);
1696 setOperationAction(ISD::UMIN, VT, Legal);
1697 setOperationAction(ISD::SETCC, VT, Custom);
1698 setOperationAction(ISD::UADDSAT, VT, Legal);
1699 setOperationAction(ISD::SADDSAT, VT, Legal);
1700 setOperationAction(ISD::USUBSAT, VT, Legal);
1701 setOperationAction(ISD::SSUBSAT, VT, Legal);
1702
1703 // The condition codes aren't legal in SSE/AVX and under AVX512 we use
1704 // setcc all the way to isel and prefer SETGT in some isel patterns.
1705 setCondCodeAction(ISD::SETLT, VT, Custom);
1706 setCondCodeAction(ISD::SETLE, VT, Custom);
1707 }
1708
1709 for (auto ExtType : {ISD::ZEXTLOAD, ISD::SEXTLOAD}) {
1710 setLoadExtAction(ExtType, MVT::v32i16, MVT::v32i8, Legal);
1711 }
1712
1713 if (Subtarget.hasBITALG()) {
1714 for (auto VT : { MVT::v64i8, MVT::v32i16 })
1715 setOperationAction(ISD::CTPOP, VT, Legal);
1716 }
1717
1718 if (Subtarget.hasVBMI2()) {
1719 setOperationAction(ISD::FSHL, MVT::v32i16, Custom);
1720 setOperationAction(ISD::FSHR, MVT::v32i16, Custom);
1721 }
1722 }
1723
1724 if (!Subtarget.useSoftFloat() && Subtarget.hasBWI()) {
1725 for (auto VT : { MVT::v32i8, MVT::v16i8, MVT::v16i16, MVT::v8i16 }) {
1726 setOperationAction(ISD::MLOAD, VT, Subtarget.hasVLX() ? Legal : Custom);
1727 setOperationAction(ISD::MSTORE, VT, Subtarget.hasVLX() ? Legal : Custom);
1728 }
1729
1730 // These operations are handled on non-VLX by artificially widening in
1731 // isel patterns.
1732 // TODO: Custom widen in lowering on non-VLX and drop the isel patterns?
1733
1734 if (Subtarget.hasBITALG()) {
1735 for (auto VT : { MVT::v16i8, MVT::v32i8, MVT::v8i16, MVT::v16i16 })
1736 setOperationAction(ISD::CTPOP, VT, Legal);
1737 }
1738 }
1739
1740 if (!Subtarget.useSoftFloat() && Subtarget.hasVLX()) {
1741 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Legal);
1742 setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1743 setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1744 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Legal);
1745 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1746
1747 setTruncStoreAction(MVT::v2i64, MVT::v2i8, Legal);
1748 setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1749 setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1750 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Legal);
1751 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1752
1753 if (Subtarget.hasDQI()) {
1754 // Fast v2f32 SINT_TO_FP( v2i64 ) custom conversion.
1755 // v2f32 UINT_TO_FP is already custom under SSE2.
1756 setOperationAction(ISD::SINT_TO_FP, MVT::v2f32, Custom);
1757 assert(isOperationCustom(ISD::UINT_TO_FP, MVT::v2f32) &&((isOperationCustom(ISD::UINT_TO_FP, MVT::v2f32) && "Unexpected operation action!"
) ? static_cast<void> (0) : __assert_fail ("isOperationCustom(ISD::UINT_TO_FP, MVT::v2f32) && \"Unexpected operation action!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 1758, __PRETTY_FUNCTION__))
1758 "Unexpected operation action!")((isOperationCustom(ISD::UINT_TO_FP, MVT::v2f32) && "Unexpected operation action!"
) ? static_cast<void> (0) : __assert_fail ("isOperationCustom(ISD::UINT_TO_FP, MVT::v2f32) && \"Unexpected operation action!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 1758, __PRETTY_FUNCTION__))
;
1759 // v2i64 FP_TO_S/UINT(v2f32) custom conversion.
1760 setOperationAction(ISD::FP_TO_SINT, MVT::v2f32, Custom);
1761 setOperationAction(ISD::FP_TO_UINT, MVT::v2f32, Custom);
1762 }
1763
1764 if (Subtarget.hasBWI()) {
1765 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Legal);
1766 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Legal);
1767 }
1768
1769 if (Subtarget.hasVBMI2()) {
1770 // TODO: Make these legal even without VLX?
1771 for (auto VT : { MVT::v8i16, MVT::v4i32, MVT::v2i64,
1772 MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1773 setOperationAction(ISD::FSHL, VT, Custom);
1774 setOperationAction(ISD::FSHR, VT, Custom);
1775 }
1776 }
1777 }
1778
1779 // We want to custom lower some of our intrinsics.
1780 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1781 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1782 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1783 if (!Subtarget.is64Bit()) {
1784 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1785 }
1786
1787 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1788 // handle type legalization for these operations here.
1789 //
1790 // FIXME: We really should do custom legalization for addition and
1791 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1792 // than generic legalization for 64-bit multiplication-with-overflow, though.
1793 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
1794 if (VT == MVT::i64 && !Subtarget.is64Bit())
1795 continue;
1796 // Add/Sub/Mul with overflow operations are custom lowered.
1797 setOperationAction(ISD::SADDO, VT, Custom);
1798 setOperationAction(ISD::UADDO, VT, Custom);
1799 setOperationAction(ISD::SSUBO, VT, Custom);
1800 setOperationAction(ISD::USUBO, VT, Custom);
1801 setOperationAction(ISD::SMULO, VT, Custom);
1802 setOperationAction(ISD::UMULO, VT, Custom);
1803
1804 // Support carry in as value rather than glue.
1805 setOperationAction(ISD::ADDCARRY, VT, Custom);
1806 setOperationAction(ISD::SUBCARRY, VT, Custom);
1807 setOperationAction(ISD::SETCCCARRY, VT, Custom);
1808 }
1809
1810 if (!Subtarget.is64Bit()) {
1811 // These libcalls are not available in 32-bit.
1812 setLibcallName(RTLIB::SHL_I128, nullptr);
1813 setLibcallName(RTLIB::SRL_I128, nullptr);
1814 setLibcallName(RTLIB::SRA_I128, nullptr);
1815 setLibcallName(RTLIB::MUL_I128, nullptr);
1816 }
1817
1818 // Combine sin / cos into _sincos_stret if it is available.
1819 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
1820 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
1821 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1822 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1823 }
1824
1825 if (Subtarget.isTargetWin64()) {
1826 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1827 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1828 setOperationAction(ISD::SREM, MVT::i128, Custom);
1829 setOperationAction(ISD::UREM, MVT::i128, Custom);
1830 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1831 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1832 }
1833
1834 // On 32 bit MSVC, `fmodf(f32)` is not defined - only `fmod(f64)`
1835 // is. We should promote the value to 64-bits to solve this.
1836 // This is what the CRT headers do - `fmodf` is an inline header
1837 // function casting to f64 and calling `fmod`.
1838 if (Subtarget.is32Bit() && (Subtarget.isTargetKnownWindowsMSVC() ||
1839 Subtarget.isTargetWindowsItanium()))
1840 for (ISD::NodeType Op :
1841 {ISD::FCEIL, ISD::FCOS, ISD::FEXP, ISD::FFLOOR, ISD::FREM, ISD::FLOG,
1842 ISD::FLOG10, ISD::FPOW, ISD::FSIN})
1843 if (isOperationExpand(Op, MVT::f32))
1844 setOperationAction(Op, MVT::f32, Promote);
1845
1846 // We have target-specific dag combine patterns for the following nodes:
1847 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1848 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
1849 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1850 setTargetDAGCombine(ISD::CONCAT_VECTORS);
1851 setTargetDAGCombine(ISD::INSERT_SUBVECTOR);
1852 setTargetDAGCombine(ISD::EXTRACT_SUBVECTOR);
1853 setTargetDAGCombine(ISD::BITCAST);
1854 setTargetDAGCombine(ISD::VSELECT);
1855 setTargetDAGCombine(ISD::SELECT);
1856 setTargetDAGCombine(ISD::SHL);
1857 setTargetDAGCombine(ISD::SRA);
1858 setTargetDAGCombine(ISD::SRL);
1859 setTargetDAGCombine(ISD::OR);
1860 setTargetDAGCombine(ISD::AND);
1861 setTargetDAGCombine(ISD::ADD);
1862 setTargetDAGCombine(ISD::FADD);
1863 setTargetDAGCombine(ISD::FSUB);
1864 setTargetDAGCombine(ISD::FNEG);
1865 setTargetDAGCombine(ISD::FMA);
1866 setTargetDAGCombine(ISD::FMINNUM);
1867 setTargetDAGCombine(ISD::FMAXNUM);
1868 setTargetDAGCombine(ISD::SUB);
1869 setTargetDAGCombine(ISD::LOAD);
1870 setTargetDAGCombine(ISD::MLOAD);
1871 setTargetDAGCombine(ISD::STORE);
1872 setTargetDAGCombine(ISD::MSTORE);
1873 setTargetDAGCombine(ISD::TRUNCATE);
1874 setTargetDAGCombine(ISD::ZERO_EXTEND);
1875 setTargetDAGCombine(ISD::ANY_EXTEND);
1876 setTargetDAGCombine(ISD::SIGN_EXTEND);
1877 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1878 setTargetDAGCombine(ISD::ANY_EXTEND_VECTOR_INREG);
1879 setTargetDAGCombine(ISD::ZERO_EXTEND_VECTOR_INREG);
1880 setTargetDAGCombine(ISD::SINT_TO_FP);
1881 setTargetDAGCombine(ISD::UINT_TO_FP);
1882 setTargetDAGCombine(ISD::SETCC);
1883 setTargetDAGCombine(ISD::MUL);
1884 setTargetDAGCombine(ISD::XOR);
1885 setTargetDAGCombine(ISD::MSCATTER);
1886 setTargetDAGCombine(ISD::MGATHER);
1887
1888 computeRegisterProperties(Subtarget.getRegisterInfo());
1889
1890 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1891 MaxStoresPerMemsetOptSize = 8;
1892 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1893 MaxStoresPerMemcpyOptSize = 4;
1894 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1895 MaxStoresPerMemmoveOptSize = 4;
1896
1897 // TODO: These control memcmp expansion in CGP and could be raised higher, but
1898 // that needs to benchmarked and balanced with the potential use of vector
1899 // load/store types (PR33329, PR33914).
1900 MaxLoadsPerMemcmp = 2;
1901 MaxLoadsPerMemcmpOptSize = 2;
1902
1903 // Set loop alignment to 2^ExperimentalPrefLoopAlignment bytes (default: 2^4).
1904 setPrefLoopAlignment(ExperimentalPrefLoopAlignment);
1905
1906 // An out-of-order CPU can speculatively execute past a predictable branch,
1907 // but a conditional move could be stalled by an expensive earlier operation.
1908 PredictableSelectIsExpensive = Subtarget.getSchedModel().isOutOfOrder();
1909 EnableExtLdPromotion = true;
1910 setPrefFunctionAlignment(4); // 2^4 bytes.
1911
1912 verifyIntrinsicTables();
1913}
1914
1915// This has so far only been implemented for 64-bit MachO.
1916bool X86TargetLowering::useLoadStackGuardNode() const {
1917 return Subtarget.isTargetMachO() && Subtarget.is64Bit();
1918}
1919
1920bool X86TargetLowering::useStackGuardXorFP() const {
1921 // Currently only MSVC CRTs XOR the frame pointer into the stack guard value.
1922 return Subtarget.getTargetTriple().isOSMSVCRT();
1923}
1924
1925SDValue X86TargetLowering::emitStackGuardXorFP(SelectionDAG &DAG, SDValue Val,
1926 const SDLoc &DL) const {
1927 EVT PtrTy = getPointerTy(DAG.getDataLayout());
1928 unsigned XorOp = Subtarget.is64Bit() ? X86::XOR64_FP : X86::XOR32_FP;
1929 MachineSDNode *Node = DAG.getMachineNode(XorOp, DL, PtrTy, Val);
1930 return SDValue(Node, 0);
1931}
1932
1933TargetLoweringBase::LegalizeTypeAction
1934X86TargetLowering::getPreferredVectorAction(MVT VT) const {
1935 if (VT == MVT::v32i1 && Subtarget.hasAVX512() && !Subtarget.hasBWI())
1936 return TypeSplitVector;
1937
1938 if (ExperimentalVectorWideningLegalization &&
1939 VT.getVectorNumElements() != 1 &&
1940 VT.getVectorElementType() != MVT::i1)
1941 return TypeWidenVector;
1942
1943 return TargetLoweringBase::getPreferredVectorAction(VT);
1944}
1945
1946MVT X86TargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
1947 CallingConv::ID CC,
1948 EVT VT) const {
1949 if (VT == MVT::v32i1 && Subtarget.hasAVX512() && !Subtarget.hasBWI())
1950 return MVT::v32i8;
1951 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
1952}
1953
1954unsigned X86TargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
1955 CallingConv::ID CC,
1956 EVT VT) const {
1957 if (VT == MVT::v32i1 && Subtarget.hasAVX512() && !Subtarget.hasBWI())
1958 return 1;
1959 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1960}
1961
1962EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL,
1963 LLVMContext& Context,
1964 EVT VT) const {
1965 if (!VT.isVector())
1966 return MVT::i8;
1967
1968 if (Subtarget.hasAVX512()) {
1969 const unsigned NumElts = VT.getVectorNumElements();
1970
1971 // Figure out what this type will be legalized to.
1972 EVT LegalVT = VT;
1973 while (getTypeAction(Context, LegalVT) != TypeLegal)
1974 LegalVT = getTypeToTransformTo(Context, LegalVT);
1975
1976 // If we got a 512-bit vector then we'll definitely have a vXi1 compare.
1977 if (LegalVT.getSimpleVT().is512BitVector())
1978 return EVT::getVectorVT(Context, MVT::i1, NumElts);
1979
1980 if (LegalVT.getSimpleVT().isVector() && Subtarget.hasVLX()) {
1981 // If we legalized to less than a 512-bit vector, then we will use a vXi1
1982 // compare for vXi32/vXi64 for sure. If we have BWI we will also support
1983 // vXi16/vXi8.
1984 MVT EltVT = LegalVT.getSimpleVT().getVectorElementType();
1985 if (Subtarget.hasBWI() || EltVT.getSizeInBits() >= 32)
1986 return EVT::getVectorVT(Context, MVT::i1, NumElts);
1987 }
1988 }
1989
1990 return VT.changeVectorElementTypeToInteger();
1991}
1992
1993/// Helper for getByValTypeAlignment to determine
1994/// the desired ByVal argument alignment.
1995static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1996 if (MaxAlign == 16)
1997 return;
1998 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1999 if (VTy->getBitWidth() == 128)
2000 MaxAlign = 16;
2001 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2002 unsigned EltAlign = 0;
2003 getMaxByValAlign(ATy->getElementType(), EltAlign);
2004 if (EltAlign > MaxAlign)
2005 MaxAlign = EltAlign;
2006 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
2007 for (auto *EltTy : STy->elements()) {
2008 unsigned EltAlign = 0;
2009 getMaxByValAlign(EltTy, EltAlign);
2010 if (EltAlign > MaxAlign)
2011 MaxAlign = EltAlign;
2012 if (MaxAlign == 16)
2013 break;
2014 }
2015 }
2016}
2017
2018/// Return the desired alignment for ByVal aggregate
2019/// function arguments in the caller parameter area. For X86, aggregates
2020/// that contain SSE vectors are placed at 16-byte boundaries while the rest
2021/// are at 4-byte boundaries.
2022unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
2023 const DataLayout &DL) const {
2024 if (Subtarget.is64Bit()) {
2025 // Max of 8 and alignment of type.
2026 unsigned TyAlign = DL.getABITypeAlignment(Ty);
2027 if (TyAlign > 8)
2028 return TyAlign;
2029 return 8;
2030 }
2031
2032 unsigned Align = 4;
2033 if (Subtarget.hasSSE1())
2034 getMaxByValAlign(Ty, Align);
2035 return Align;
2036}
2037
2038/// Returns the target specific optimal type for load
2039/// and store operations as a result of memset, memcpy, and memmove
2040/// lowering. If DstAlign is zero that means it's safe to destination
2041/// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
2042/// means there isn't a need to check it against alignment requirement,
2043/// probably because the source does not need to be loaded. If 'IsMemset' is
2044/// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
2045/// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
2046/// source is constant so it does not need to be loaded.
2047/// It returns EVT::Other if the type should be determined using generic
2048/// target-independent logic.
2049/// For vector ops we check that the overall size isn't larger than our
2050/// preferred vector width.
2051EVT X86TargetLowering::getOptimalMemOpType(
2052 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
2053 bool ZeroMemset, bool MemcpyStrSrc,
2054 const AttributeList &FuncAttributes) const {
2055 if (!FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) {
2056 if (Size >= 16 && (!Subtarget.isUnalignedMem16Slow() ||
2057 ((DstAlign == 0 || DstAlign >= 16) &&
2058 (SrcAlign == 0 || SrcAlign >= 16)))) {
2059 // FIXME: Check if unaligned 32-byte accesses are slow.
2060 if (Size >= 32 && Subtarget.hasAVX() &&
2061 (Subtarget.getPreferVectorWidth() >= 256)) {
2062 // Although this isn't a well-supported type for AVX1, we'll let
2063 // legalization and shuffle lowering produce the optimal codegen. If we
2064 // choose an optimal type with a vector element larger than a byte,
2065 // getMemsetStores() may create an intermediate splat (using an integer
2066 // multiply) before we splat as a vector.
2067 return MVT::v32i8;
2068 }
2069 if (Subtarget.hasSSE2() && (Subtarget.getPreferVectorWidth() >= 128))
2070 return MVT::v16i8;
2071 // TODO: Can SSE1 handle a byte vector?
2072 // If we have SSE1 registers we should be able to use them.
2073 if (Subtarget.hasSSE1() && (Subtarget.is64Bit() || Subtarget.hasX87()) &&
2074 (Subtarget.getPreferVectorWidth() >= 128))
2075 return MVT::v4f32;
2076 } else if ((!IsMemset || ZeroMemset) && !MemcpyStrSrc && Size >= 8 &&
2077 !Subtarget.is64Bit() && Subtarget.hasSSE2()) {
2078 // Do not use f64 to lower memcpy if source is string constant. It's
2079 // better to use i32 to avoid the loads.
2080 // Also, do not use f64 to lower memset unless this is a memset of zeros.
2081 // The gymnastics of splatting a byte value into an XMM register and then
2082 // only using 8-byte stores (because this is a CPU with slow unaligned
2083 // 16-byte accesses) makes that a loser.
2084 return MVT::f64;
2085 }
2086 }
2087 // This is a compromise. If we reach here, unaligned accesses may be slow on
2088 // this target. However, creating smaller, aligned accesses could be even
2089 // slower and would certainly be a lot more code.
2090 if (Subtarget.is64Bit() && Size >= 8)
2091 return MVT::i64;
2092 return MVT::i32;
2093}
2094
2095bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
2096 if (VT == MVT::f32)
2097 return X86ScalarSSEf32;
2098 else if (VT == MVT::f64)
2099 return X86ScalarSSEf64;
2100 return true;
2101}
2102
2103bool
2104X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
2105 unsigned,
2106 unsigned,
2107 bool *Fast) const {
2108 if (Fast) {
2109 switch (VT.getSizeInBits()) {
2110 default:
2111 // 8-byte and under are always assumed to be fast.
2112 *Fast = true;
2113 break;
2114 case 128:
2115 *Fast = !Subtarget.isUnalignedMem16Slow();
2116 break;
2117 case 256:
2118 *Fast = !Subtarget.isUnalignedMem32Slow();
2119 break;
2120 // TODO: What about AVX-512 (512-bit) accesses?
2121 }
2122 }
2123 // Misaligned accesses of any size are always allowed.
2124 return true;
2125}
2126
2127/// Return the entry encoding for a jump table in the
2128/// current function. The returned value is a member of the
2129/// MachineJumpTableInfo::JTEntryKind enum.
2130unsigned X86TargetLowering::getJumpTableEncoding() const {
2131 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
2132 // symbol.
2133 if (isPositionIndependent() && Subtarget.isPICStyleGOT())
2134 return MachineJumpTableInfo::EK_Custom32;
2135
2136 // Otherwise, use the normal jump table encoding heuristics.
2137 return TargetLowering::getJumpTableEncoding();
2138}
2139
2140bool X86TargetLowering::useSoftFloat() const {
2141 return Subtarget.useSoftFloat();
2142}
2143
2144void X86TargetLowering::markLibCallAttributes(MachineFunction *MF, unsigned CC,
2145 ArgListTy &Args) const {
2146
2147 // Only relabel X86-32 for C / Stdcall CCs.
2148 if (Subtarget.is64Bit())
2149 return;
2150 if (CC != CallingConv::C && CC != CallingConv::X86_StdCall)
2151 return;
2152 unsigned ParamRegs = 0;
2153 if (auto *M = MF->getFunction().getParent())
2154 ParamRegs = M->getNumberRegisterParameters();
2155
2156 // Mark the first N int arguments as having reg
2157 for (unsigned Idx = 0; Idx < Args.size(); Idx++) {
2158 Type *T = Args[Idx].Ty;
2159 if (T->isIntOrPtrTy())
2160 if (MF->getDataLayout().getTypeAllocSize(T) <= 8) {
2161 unsigned numRegs = 1;
2162 if (MF->getDataLayout().getTypeAllocSize(T) > 4)
2163 numRegs = 2;
2164 if (ParamRegs < numRegs)
2165 return;
2166 ParamRegs -= numRegs;
2167 Args[Idx].IsInReg = true;
2168 }
2169 }
2170}
2171
2172const MCExpr *
2173X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
2174 const MachineBasicBlock *MBB,
2175 unsigned uid,MCContext &Ctx) const{
2176 assert(isPositionIndependent() && Subtarget.isPICStyleGOT())((isPositionIndependent() && Subtarget.isPICStyleGOT(
)) ? static_cast<void> (0) : __assert_fail ("isPositionIndependent() && Subtarget.isPICStyleGOT()"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 2176, __PRETTY_FUNCTION__))
;
2177 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
2178 // entries.
2179 return MCSymbolRefExpr::create(MBB->getSymbol(),
2180 MCSymbolRefExpr::VK_GOTOFF, Ctx);
2181}
2182
2183/// Returns relocation base for the given PIC jumptable.
2184SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
2185 SelectionDAG &DAG) const {
2186 if (!Subtarget.is64Bit())
2187 // This doesn't have SDLoc associated with it, but is not really the
2188 // same as a Register.
2189 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
2190 getPointerTy(DAG.getDataLayout()));
2191 return Table;
2192}
2193
2194/// This returns the relocation base for the given PIC jumptable,
2195/// the same as getPICJumpTableRelocBase, but as an MCExpr.
2196const MCExpr *X86TargetLowering::
2197getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
2198 MCContext &Ctx) const {
2199 // X86-64 uses RIP relative addressing based on the jump table label.
2200 if (Subtarget.isPICStyleRIPRel())
2201 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2202
2203 // Otherwise, the reference is relative to the PIC base.
2204 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2205}
2206
2207std::pair<const TargetRegisterClass *, uint8_t>
2208X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
2209 MVT VT) const {
2210 const TargetRegisterClass *RRC = nullptr;
2211 uint8_t Cost = 1;
2212 switch (VT.SimpleTy) {
2213 default:
2214 return TargetLowering::findRepresentativeClass(TRI, VT);
2215 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
2216 RRC = Subtarget.is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
2217 break;
2218 case MVT::x86mmx:
2219 RRC = &X86::VR64RegClass;
2220 break;
2221 case MVT::f32: case MVT::f64:
2222 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
2223 case MVT::v4f32: case MVT::v2f64:
2224 case MVT::v32i8: case MVT::v16i16: case MVT::v8i32: case MVT::v4i64:
2225 case MVT::v8f32: case MVT::v4f64:
2226 case MVT::v64i8: case MVT::v32i16: case MVT::v16i32: case MVT::v8i64:
2227 case MVT::v16f32: case MVT::v8f64:
2228 RRC = &X86::VR128XRegClass;
2229 break;
2230 }
2231 return std::make_pair(RRC, Cost);
2232}
2233
2234unsigned X86TargetLowering::getAddressSpace() const {
2235 if (Subtarget.is64Bit())
2236 return (getTargetMachine().getCodeModel() == CodeModel::Kernel) ? 256 : 257;
2237 return 256;
2238}
2239
2240static bool hasStackGuardSlotTLS(const Triple &TargetTriple) {
2241 return TargetTriple.isOSGlibc() || TargetTriple.isOSFuchsia() ||
2242 (TargetTriple.isAndroid() && !TargetTriple.isAndroidVersionLT(17));
2243}
2244
2245static Constant* SegmentOffset(IRBuilder<> &IRB,
2246 unsigned Offset, unsigned AddressSpace) {
2247 return ConstantExpr::getIntToPtr(
2248 ConstantInt::get(Type::getInt32Ty(IRB.getContext()), Offset),
2249 Type::getInt8PtrTy(IRB.getContext())->getPointerTo(AddressSpace));
2250}
2251
2252Value *X86TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
2253 // glibc, bionic, and Fuchsia have a special slot for the stack guard in
2254 // tcbhead_t; use it instead of the usual global variable (see
2255 // sysdeps/{i386,x86_64}/nptl/tls.h)
2256 if (hasStackGuardSlotTLS(Subtarget.getTargetTriple())) {
2257 if (Subtarget.isTargetFuchsia()) {
2258 // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
2259 return SegmentOffset(IRB, 0x10, getAddressSpace());
2260 } else {
2261 // %fs:0x28, unless we're using a Kernel code model, in which case
2262 // it's %gs:0x28. gs:0x14 on i386.
2263 unsigned Offset = (Subtarget.is64Bit()) ? 0x28 : 0x14;
2264 return SegmentOffset(IRB, Offset, getAddressSpace());
2265 }
2266 }
2267
2268 return TargetLowering::getIRStackGuard(IRB);
2269}
2270
2271void X86TargetLowering::insertSSPDeclarations(Module &M) const {
2272 // MSVC CRT provides functionalities for stack protection.
2273 if (Subtarget.getTargetTriple().isWindowsMSVCEnvironment() ||
2274 Subtarget.getTargetTriple().isWindowsItaniumEnvironment()) {
2275 // MSVC CRT has a global variable holding security cookie.
2276 M.getOrInsertGlobal("__security_cookie",
2277 Type::getInt8PtrTy(M.getContext()));
2278
2279 // MSVC CRT has a function to validate security cookie.
2280 FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
2281 "__security_check_cookie", Type::getVoidTy(M.getContext()),
2282 Type::getInt8PtrTy(M.getContext()));
2283 if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) {
2284 F->setCallingConv(CallingConv::X86_FastCall);
2285 F->addAttribute(1, Attribute::AttrKind::InReg);
2286 }
2287 return;
2288 }
2289 // glibc, bionic, and Fuchsia have a special slot for the stack guard.
2290 if (hasStackGuardSlotTLS(Subtarget.getTargetTriple()))
2291 return;
2292 TargetLowering::insertSSPDeclarations(M);
2293}
2294
2295Value *X86TargetLowering::getSDagStackGuard(const Module &M) const {
2296 // MSVC CRT has a global variable holding security cookie.
2297 if (Subtarget.getTargetTriple().isWindowsMSVCEnvironment() ||
2298 Subtarget.getTargetTriple().isWindowsItaniumEnvironment()) {
2299 return M.getGlobalVariable("__security_cookie");
2300 }
2301 return TargetLowering::getSDagStackGuard(M);
2302}
2303
2304Function *X86TargetLowering::getSSPStackGuardCheck(const Module &M) const {
2305 // MSVC CRT has a function to validate security cookie.
2306 if (Subtarget.getTargetTriple().isWindowsMSVCEnvironment() ||
2307 Subtarget.getTargetTriple().isWindowsItaniumEnvironment()) {
2308 return M.getFunction("__security_check_cookie");
2309 }
2310 return TargetLowering::getSSPStackGuardCheck(M);
2311}
2312
2313Value *X86TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
2314 if (Subtarget.getTargetTriple().isOSContiki())
2315 return getDefaultSafeStackPointerLocation(IRB, false);
2316
2317 // Android provides a fixed TLS slot for the SafeStack pointer. See the
2318 // definition of TLS_SLOT_SAFESTACK in
2319 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
2320 if (Subtarget.isTargetAndroid()) {
2321 // %fs:0x48, unless we're using a Kernel code model, in which case it's %gs:
2322 // %gs:0x24 on i386
2323 unsigned Offset = (Subtarget.is64Bit()) ? 0x48 : 0x24;
2324 return SegmentOffset(IRB, Offset, getAddressSpace());
2325 }
2326
2327 // Fuchsia is similar.
2328 if (Subtarget.isTargetFuchsia()) {
2329 // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
2330 return SegmentOffset(IRB, 0x18, getAddressSpace());
2331 }
2332
2333 return TargetLowering::getSafeStackPointerLocation(IRB);
2334}
2335
2336bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2337 unsigned DestAS) const {
2338 assert(SrcAS != DestAS && "Expected different address spaces!")((SrcAS != DestAS && "Expected different address spaces!"
) ? static_cast<void> (0) : __assert_fail ("SrcAS != DestAS && \"Expected different address spaces!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 2338, __PRETTY_FUNCTION__))
;
2339
2340 return SrcAS < 256 && DestAS < 256;
2341}
2342
2343//===----------------------------------------------------------------------===//
2344// Return Value Calling Convention Implementation
2345//===----------------------------------------------------------------------===//
2346
2347bool X86TargetLowering::CanLowerReturn(
2348 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2349 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2350 SmallVector<CCValAssign, 16> RVLocs;
2351 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2352 return CCInfo.CheckReturn(Outs, RetCC_X86);
2353}
2354
2355const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2356 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2357 return ScratchRegs;
2358}
2359
2360/// Lowers masks values (v*i1) to the local register values
2361/// \returns DAG node after lowering to register type
2362static SDValue lowerMasksToReg(const SDValue &ValArg, const EVT &ValLoc,
2363 const SDLoc &Dl, SelectionDAG &DAG) {
2364 EVT ValVT = ValArg.getValueType();
2365
2366 if (ValVT == MVT::v1i1)
2367 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, Dl, ValLoc, ValArg,
2368 DAG.getIntPtrConstant(0, Dl));
2369
2370 if ((ValVT == MVT::v8i1 && (ValLoc == MVT::i8 || ValLoc == MVT::i32)) ||
2371 (ValVT == MVT::v16i1 && (ValLoc == MVT::i16 || ValLoc == MVT::i32))) {
2372 // Two stage lowering might be required
2373 // bitcast: v8i1 -> i8 / v16i1 -> i16
2374 // anyextend: i8 -> i32 / i16 -> i32
2375 EVT TempValLoc = ValVT == MVT::v8i1 ? MVT::i8 : MVT::i16;
2376 SDValue ValToCopy = DAG.getBitcast(TempValLoc, ValArg);
2377 if (ValLoc == MVT::i32)
2378 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, Dl, ValLoc, ValToCopy);
2379 return ValToCopy;
2380 }
2381
2382 if ((ValVT == MVT::v32i1 && ValLoc == MVT::i32) ||
2383 (ValVT == MVT::v64i1 && ValLoc == MVT::i64)) {
2384 // One stage lowering is required
2385 // bitcast: v32i1 -> i32 / v64i1 -> i64
2386 return DAG.getBitcast(ValLoc, ValArg);
2387 }
2388
2389 return DAG.getNode(ISD::ANY_EXTEND, Dl, ValLoc, ValArg);
2390}
2391
2392/// Breaks v64i1 value into two registers and adds the new node to the DAG
2393static void Passv64i1ArgInRegs(
2394 const SDLoc &Dl, SelectionDAG &DAG, SDValue Chain, SDValue &Arg,
2395 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, CCValAssign &VA,
2396 CCValAssign &NextVA, const X86Subtarget &Subtarget) {
2397 assert(Subtarget.hasBWI() && "Expected AVX512BW target!")((Subtarget.hasBWI() && "Expected AVX512BW target!") ?
static_cast<void> (0) : __assert_fail ("Subtarget.hasBWI() && \"Expected AVX512BW target!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 2397, __PRETTY_FUNCTION__))
;
2398 assert(Subtarget.is32Bit() && "Expecting 32 bit target")((Subtarget.is32Bit() && "Expecting 32 bit target") ?
static_cast<void> (0) : __assert_fail ("Subtarget.is32Bit() && \"Expecting 32 bit target\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 2398, __PRETTY_FUNCTION__))
;
2399 assert(Arg.getValueType() == MVT::i64 && "Expecting 64 bit value")((Arg.getValueType() == MVT::i64 && "Expecting 64 bit value"
) ? static_cast<void> (0) : __assert_fail ("Arg.getValueType() == MVT::i64 && \"Expecting 64 bit value\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 2399, __PRETTY_FUNCTION__))
;
2400 assert(VA.isRegLoc() && NextVA.isRegLoc() &&((VA.isRegLoc() && NextVA.isRegLoc() && "The value should reside in two registers"
) ? static_cast<void> (0) : __assert_fail ("VA.isRegLoc() && NextVA.isRegLoc() && \"The value should reside in two registers\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 2401, __PRETTY_FUNCTION__))
2401 "The value should reside in two registers")((VA.isRegLoc() && NextVA.isRegLoc() && "The value should reside in two registers"
) ? static_cast<void> (0) : __assert_fail ("VA.isRegLoc() && NextVA.isRegLoc() && \"The value should reside in two registers\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 2401, __PRETTY_FUNCTION__))
;
2402
2403 // Before splitting the value we cast it to i64
2404 Arg = DAG.getBitcast(MVT::i64, Arg);
2405
2406 // Splitting the value into two i32 types
2407 SDValue Lo, Hi;
2408 Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i32, Arg,
2409 DAG.getConstant(0, Dl, MVT::i32));
2410 Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i32, Arg,
2411 DAG.getConstant(1, Dl, MVT::i32));
2412
2413 // Attach the two i32 types into corresponding registers
2414 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Lo));
2415 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), Hi));
2416}
2417
2418SDValue
2419X86TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2420 bool isVarArg,
2421 const SmallVectorImpl<ISD::OutputArg> &Outs,
2422 const SmallVectorImpl<SDValue> &OutVals,
2423 const SDLoc &dl, SelectionDAG &DAG) const {
2424 MachineFunction &MF = DAG.getMachineFunction();
2425 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2426
2427 // In some cases we need to disable registers from the default CSR list.
2428 // For example, when they are used for argument passing.
2429 bool ShouldDisableCalleeSavedRegister =
2430 CallConv == CallingConv::X86_RegCall ||
2431 MF.getFunction().hasFnAttribute("no_caller_saved_registers");
2432
2433 if (CallConv == CallingConv::X86_INTR && !Outs.empty())
2434 report_fatal_error("X86 interrupts may not return any value");
2435
2436 SmallVector<CCValAssign, 16> RVLocs;
2437 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2438 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2439
2440 SDValue Flag;
2441 SmallVector<SDValue, 6> RetOps;
2442 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2443 // Operand #1 = Bytes To Pop
2444 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2445 MVT::i32));
2446
2447 // Copy the result values into the output registers.
2448 for (unsigned I = 0, OutsIndex = 0, E = RVLocs.size(); I != E;
2449 ++I, ++OutsIndex) {
2450 CCValAssign &VA = RVLocs[I];
2451 assert(VA.isRegLoc() && "Can only return in registers!")((VA.isRegLoc() && "Can only return in registers!") ?
static_cast<void> (0) : __assert_fail ("VA.isRegLoc() && \"Can only return in registers!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 2451, __PRETTY_FUNCTION__))
;
2452
2453 // Add the register to the CalleeSaveDisableRegs list.
2454 if (ShouldDisableCalleeSavedRegister)
2455 MF.getRegInfo().disableCalleeSavedRegister(VA.getLocReg());
2456
2457 SDValue ValToCopy = OutVals[OutsIndex];
2458 EVT ValVT = ValToCopy.getValueType();
2459
2460 // Promote values to the appropriate types.
2461 if (VA.getLocInfo() == CCValAssign::SExt)
2462 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2463 else if (VA.getLocInfo() == CCValAssign::ZExt)
2464 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2465 else if (VA.getLocInfo() == CCValAssign::AExt) {
2466 if (ValVT.isVector() && ValVT.getVectorElementType() == MVT::i1)
2467 ValToCopy = lowerMasksToReg(ValToCopy, VA.getLocVT(), dl, DAG);
2468 else
2469 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2470 }
2471 else if (VA.getLocInfo() == CCValAssign::BCvt)
2472 ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2473
2474 assert(VA.getLocInfo() != CCValAssign::FPExt &&((VA.getLocInfo() != CCValAssign::FPExt && "Unexpected FP-extend for return value."
) ? static_cast<void> (0) : __assert_fail ("VA.getLocInfo() != CCValAssign::FPExt && \"Unexpected FP-extend for return value.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 2475, __PRETTY_FUNCTION__))
2475 "Unexpected FP-extend for return value.")((VA.getLocInfo() != CCValAssign::FPExt && "Unexpected FP-extend for return value."
) ? static_cast<void> (0) : __assert_fail ("VA.getLocInfo() != CCValAssign::FPExt && \"Unexpected FP-extend for return value.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 2475, __PRETTY_FUNCTION__))
;
2476
2477 // If this is x86-64, and we disabled SSE, we can't return FP values,
2478 // or SSE or MMX vectors.
2479 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2480 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2481 (Subtarget.is64Bit() && !Subtarget.hasSSE1())) {
2482 errorUnsupported(DAG, dl, "SSE register return with SSE disabled");
2483 VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
2484 } else if (ValVT == MVT::f64 &&
2485 (Subtarget.is64Bit() && !Subtarget.hasSSE2())) {
2486 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
2487 // llvm-gcc has never done it right and no one has noticed, so this
2488 // should be OK for now.
2489 errorUnsupported(DAG, dl, "SSE2 register return with SSE2 disabled");
2490 VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
2491 }
2492
2493 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2494 // the RET instruction and handled by the FP Stackifier.
2495 if (VA.getLocReg() == X86::FP0 ||
2496 VA.getLocReg() == X86::FP1) {
2497 // If this is a copy from an xmm register to ST(0), use an FPExtend to
2498 // change the value to the FP stack register class.
2499 if (isScalarFPTypeInSSEReg(VA.getValVT()))
2500 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2501 RetOps.push_back(ValToCopy);
2502 // Don't emit a copytoreg.
2503 continue;
2504 }
2505
2506 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2507 // which is returned in RAX / RDX.
2508 if (Subtarget.is64Bit()) {
2509 if (ValVT == MVT::x86mmx) {
2510 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2511 ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2512 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2513 ValToCopy);
2514 // If we don't have SSE2 available, convert to v4f32 so the generated
2515 // register is legal.
2516 if (!Subtarget.hasSSE2())
2517 ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2518 }
2519 }
2520 }
2521
2522 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2523
2524 if (VA.needsCustom()) {
2525 assert(VA.getValVT() == MVT::v64i1 &&((VA.getValVT() == MVT::v64i1 && "Currently the only custom case is when we split v64i1 to 2 regs"
) ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 2526, __PRETTY_FUNCTION__))
2526 "Currently the only custom case is when we split v64i1 to 2 regs")((VA.getValVT() == MVT::v64i1 && "Currently the only custom case is when we split v64i1 to 2 regs"
) ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 2526, __PRETTY_FUNCTION__))
;
2527
2528 Passv64i1ArgInRegs(dl, DAG, Chain, ValToCopy, RegsToPass, VA, RVLocs[++I],
2529 Subtarget);
2530
2531 assert(2 == RegsToPass.size() &&((2 == RegsToPass.size() && "Expecting two registers after Pass64BitArgInRegs"
) ? static_cast<void> (0) : __assert_fail ("2 == RegsToPass.size() && \"Expecting two registers after Pass64BitArgInRegs\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 2532, __PRETTY_FUNCTION__))
2532 "Expecting two registers after Pass64BitArgInRegs")((2 == RegsToPass.size() && "Expecting two registers after Pass64BitArgInRegs"
) ? static_cast<void> (0) : __assert_fail ("2 == RegsToPass.size() && \"Expecting two registers after Pass64BitArgInRegs\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 2532, __PRETTY_FUNCTION__))
;
2533
2534 // Add the second register to the CalleeSaveDisableRegs list.
2535 if (ShouldDisableCalleeSavedRegister)
2536 MF.getRegInfo().disableCalleeSavedRegister(RVLocs[I].getLocReg());
2537 } else {
2538 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ValToCopy));
2539 }
2540
2541 // Add nodes to the DAG and add the values into the RetOps list
2542 for (auto &Reg : RegsToPass) {
2543 Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, Flag);
2544 Flag = Chain.getValue(1);
2545 RetOps.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
2546 }
2547 }
2548
2549 // Swift calling convention does not require we copy the sret argument
2550 // into %rax/%eax for the return, and SRetReturnReg is not set for Swift.
2551
2552 // All x86 ABIs require that for returning structs by value we copy
2553 // the sret argument into %rax/%eax (depending on ABI) for the return.
2554 // We saved the argument into a virtual register in the entry block,
2555 // so now we copy the value out and into %rax/%eax.
2556 //
2557 // Checking Function.hasStructRetAttr() here is insufficient because the IR
2558 // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2559 // false, then an sret argument may be implicitly inserted in the SelDAG. In
2560 // either case FuncInfo->setSRetReturnReg() will have been called.
2561 if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2562 // When we have both sret and another return value, we should use the
2563 // original Chain stored in RetOps[0], instead of the current Chain updated
2564 // in the above loop. If we only have sret, RetOps[0] equals to Chain.
2565
2566 // For the case of sret and another return value, we have
2567 // Chain_0 at the function entry
2568 // Chain_1 = getCopyToReg(Chain_0) in the above loop
2569 // If we use Chain_1 in getCopyFromReg, we will have
2570 // Val = getCopyFromReg(Chain_1)
2571 // Chain_2 = getCopyToReg(Chain_1, Val) from below
2572
2573 // getCopyToReg(Chain_0) will be glued together with
2574 // getCopyToReg(Chain_1, Val) into Unit A, getCopyFromReg(Chain_1) will be
2575 // in Unit B, and we will have cyclic dependency between Unit A and Unit B:
2576 // Data dependency from Unit B to Unit A due to usage of Val in
2577 // getCopyToReg(Chain_1, Val)
2578 // Chain dependency from Unit A to Unit B
2579
2580 // So here, we use RetOps[0] (i.e Chain_0) for getCopyFromReg.
2581 SDValue Val = DAG.getCopyFromReg(RetOps[0], dl, SRetReg,
2582 getPointerTy(MF.getDataLayout()));
2583
2584 unsigned RetValReg
2585 = (Subtarget.is64Bit() && !Subtarget.isTarget64BitILP32()) ?
2586 X86::RAX : X86::EAX;
2587 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2588 Flag = Chain.getValue(1);
2589
2590 // RAX/EAX now acts like a return value.
2591 RetOps.push_back(
2592 DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2593
2594 // Add the returned register to the CalleeSaveDisableRegs list.
2595 if (ShouldDisableCalleeSavedRegister)
2596 MF.getRegInfo().disableCalleeSavedRegister(RetValReg);
2597 }
2598
2599 const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
2600 const MCPhysReg *I =
2601 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2602 if (I) {
2603 for (; *I; ++I) {
2604 if (X86::GR64RegClass.contains(*I))
2605 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2606 else
2607 llvm_unreachable("Unexpected register class in CSRsViaCopy!")::llvm::llvm_unreachable_internal("Unexpected register class in CSRsViaCopy!"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 2607)
;
2608 }
2609 }
2610
2611 RetOps[0] = Chain; // Update chain.
2612
2613 // Add the flag if we have it.
2614 if (Flag.getNode())
2615 RetOps.push_back(Flag);
2616
2617 X86ISD::NodeType opcode = X86ISD::RET_FLAG;
2618 if (CallConv == CallingConv::X86_INTR)
2619 opcode = X86ISD::IRET;
2620 return DAG.getNode(opcode, dl, MVT::Other, RetOps);
2621}
2622
2623bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2624 if (N->getNumValues() != 1 || !N->hasNUsesOfValue(1, 0))
2625 return false;
2626
2627 SDValue TCChain = Chain;
2628 SDNode *Copy = *N->use_begin();
2629 if (Copy->getOpcode() == ISD::CopyToReg) {
2630 // If the copy has a glue operand, we conservatively assume it isn't safe to
2631 // perform a tail call.
2632 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2633 return false;
2634 TCChain = Copy->getOperand(0);
2635 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2636 return false;
2637
2638 bool HasRet = false;
2639 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2640 UI != UE; ++UI) {
2641 if (UI->getOpcode() != X86ISD::RET_FLAG)
2642 return false;
2643 // If we are returning more than one value, we can definitely
2644 // not make a tail call see PR19530
2645 if (UI->getNumOperands() > 4)
2646 return false;
2647 if (UI->getNumOperands() == 4 &&
2648 UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2649 return false;
2650 HasRet = true;
2651 }
2652
2653 if (!HasRet)
2654 return false;
2655
2656 Chain = TCChain;
2657 return true;
2658}
2659
2660EVT X86TargetLowering::getTypeForExtReturn(LLVMContext &Context, EVT VT,
2661 ISD::NodeType ExtendKind) const {
2662 MVT ReturnMVT = MVT::i32;
2663
2664 bool Darwin = Subtarget.getTargetTriple().isOSDarwin();
2665 if (VT == MVT::i1 || (!Darwin && (VT == MVT::i8 || VT == MVT::i16))) {
2666 // The ABI does not require i1, i8 or i16 to be extended.
2667 //
2668 // On Darwin, there is code in the wild relying on Clang's old behaviour of
2669 // always extending i8/i16 return values, so keep doing that for now.
2670 // (PR26665).
2671 ReturnMVT = MVT::i8;
2672 }
2673
2674 EVT MinVT = getRegisterType(Context, ReturnMVT);
2675 return VT.bitsLT(MinVT) ? MinVT : VT;
2676}
2677
2678/// Reads two 32 bit registers and creates a 64 bit mask value.
2679/// \param VA The current 32 bit value that need to be assigned.
2680/// \param NextVA The next 32 bit value that need to be assigned.
2681/// \param Root The parent DAG node.
2682/// \param [in,out] InFlag Represents SDvalue in the parent DAG node for
2683/// glue purposes. In the case the DAG is already using
2684/// physical register instead of virtual, we should glue
2685/// our new SDValue to InFlag SDvalue.
2686/// \return a new SDvalue of size 64bit.
2687static SDValue getv64i1Argument(CCValAssign &VA, CCValAssign &NextVA,
2688 SDValue &Root, SelectionDAG &DAG,
2689 const SDLoc &Dl, const X86Subtarget &Subtarget,
2690 SDValue *InFlag = nullptr) {
2691 assert((Subtarget.hasBWI()) && "Expected AVX512BW target!")(((Subtarget.hasBWI()) && "Expected AVX512BW target!"
) ? static_cast<void> (0) : __assert_fail ("(Subtarget.hasBWI()) && \"Expected AVX512BW target!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 2691, __PRETTY_FUNCTION__))
;
2692 assert(Subtarget.is32Bit() && "Expecting 32 bit target")((Subtarget.is32Bit() && "Expecting 32 bit target") ?
static_cast<void> (0) : __assert_fail ("Subtarget.is32Bit() && \"Expecting 32 bit target\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 2692, __PRETTY_FUNCTION__))
;
2693 assert(VA.getValVT() == MVT::v64i1 &&((VA.getValVT() == MVT::v64i1 && "Expecting first location of 64 bit width type"
) ? static_cast<void> (0) : __assert_fail ("VA.getValVT() == MVT::v64i1 && \"Expecting first location of 64 bit width type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 2694, __PRETTY_FUNCTION__))
2694 "Expecting first location of 64 bit width type")((VA.getValVT() == MVT::v64i1 && "Expecting first location of 64 bit width type"
) ? static_cast<void> (0) : __assert_fail ("VA.getValVT() == MVT::v64i1 && \"Expecting first location of 64 bit width type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 2694, __PRETTY_FUNCTION__))
;
2695 assert(NextVA.getValVT() == VA.getValVT() &&((NextVA.getValVT() == VA.getValVT() && "The locations should have the same type"
) ? static_cast<void> (0) : __assert_fail ("NextVA.getValVT() == VA.getValVT() && \"The locations should have the same type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 2696, __PRETTY_FUNCTION__))
2696 "The locations should have the same type")((NextVA.getValVT() == VA.getValVT() && "The locations should have the same type"
) ? static_cast<void> (0) : __assert_fail ("NextVA.getValVT() == VA.getValVT() && \"The locations should have the same type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 2696, __PRETTY_FUNCTION__))
;
2697 assert(VA.isRegLoc() && NextVA.isRegLoc() &&((VA.isRegLoc() && NextVA.isRegLoc() && "The values should reside in two registers"
) ? static_cast<void> (0) : __assert_fail ("VA.isRegLoc() && NextVA.isRegLoc() && \"The values should reside in two registers\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 2698, __PRETTY_FUNCTION__))
2698 "The values should reside in two registers")((VA.isRegLoc() && NextVA.isRegLoc() && "The values should reside in two registers"
) ? static_cast<void> (0) : __assert_fail ("VA.isRegLoc() && NextVA.isRegLoc() && \"The values should reside in two registers\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 2698, __PRETTY_FUNCTION__))
;
2699
2700 SDValue Lo, Hi;
2701 SDValue ArgValueLo, ArgValueHi;
2702
2703 MachineFunction &MF = DAG.getMachineFunction();
2704 const TargetRegisterClass *RC = &X86::GR32RegClass;
2705
2706 // Read a 32 bit value from the registers.
2707 if (nullptr == InFlag) {
2708 // When no physical register is present,
2709 // create an intermediate virtual register.
2710 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2711 ArgValueLo = DAG.getCopyFromReg(Root, Dl, Reg, MVT::i32);
2712 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2713 ArgValueHi = DAG.getCopyFromReg(Root, Dl, Reg, MVT::i32);
2714 } else {
2715 // When a physical register is available read the value from it and glue
2716 // the reads together.
2717 ArgValueLo =
2718 DAG.getCopyFromReg(Root, Dl, VA.getLocReg(), MVT::i32, *InFlag);
2719 *InFlag = ArgValueLo.getValue(2);
2720 ArgValueHi =
2721 DAG.getCopyFromReg(Root, Dl, NextVA.getLocReg(), MVT::i32, *InFlag);
2722 *InFlag = ArgValueHi.getValue(2);
2723 }
2724
2725 // Convert the i32 type into v32i1 type.
2726 Lo = DAG.getBitcast(MVT::v32i1, ArgValueLo);
2727
2728 // Convert the i32 type into v32i1 type.
2729 Hi = DAG.getBitcast(MVT::v32i1, ArgValueHi);
2730
2731 // Concatenate the two values together.
2732 return DAG.getNode(ISD::CONCAT_VECTORS, Dl, MVT::v64i1, Lo, Hi);
2733}
2734
2735/// The function will lower a register of various sizes (8/16/32/64)
2736/// to a mask value of the expected size (v8i1/v16i1/v32i1/v64i1)
2737/// \returns a DAG node contains the operand after lowering to mask type.
2738static SDValue lowerRegToMasks(const SDValue &ValArg, const EVT &ValVT,
2739 const EVT &ValLoc, const SDLoc &Dl,
2740 SelectionDAG &DAG) {
2741 SDValue ValReturned = ValArg;
2742
2743 if (ValVT == MVT::v1i1)
2744 return DAG.getNode(ISD::SCALAR_TO_VECTOR, Dl, MVT::v1i1, ValReturned);
2745
2746 if (ValVT == MVT::v64i1) {
2747 // In 32 bit machine, this case is handled by getv64i1Argument
2748 assert(ValLoc == MVT::i64 && "Expecting only i64 locations")((ValLoc == MVT::i64 && "Expecting only i64 locations"
) ? static_cast<void> (0) : __assert_fail ("ValLoc == MVT::i64 && \"Expecting only i64 locations\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 2748, __PRETTY_FUNCTION__))
;
2749 // In 64 bit machine, There is no need to truncate the value only bitcast
2750 } else {
2751 MVT maskLen;
2752 switch (ValVT.getSimpleVT().SimpleTy) {
2753 case MVT::v8i1:
2754 maskLen = MVT::i8;
2755 break;
2756 case MVT::v16i1:
2757 maskLen = MVT::i16;
2758 break;
2759 case MVT::v32i1:
2760 maskLen = MVT::i32;
2761 break;
2762 default:
2763 llvm_unreachable("Expecting a vector of i1 types")::llvm::llvm_unreachable_internal("Expecting a vector of i1 types"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 2763)
;
2764 }
2765
2766 ValReturned = DAG.getNode(ISD::TRUNCATE, Dl, maskLen, ValReturned);
2767 }
2768 return DAG.getBitcast(ValVT, ValReturned);
2769}
2770
2771/// Lower the result values of a call into the
2772/// appropriate copies out of appropriate physical registers.
2773///
2774SDValue X86TargetLowering::LowerCallResult(
2775 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2776 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
2777 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
2778 uint32_t *RegMask) const {
2779
2780 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
2781 // Assign locations to each value returned by this call.
2782 SmallVector<CCValAssign, 16> RVLocs;
2783 bool Is64Bit = Subtarget.is64Bit();
2784 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2785 *DAG.getContext());
2786 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2787
2788 // Copy all of the result registers out of their specified physreg.
2789 for (unsigned I = 0, InsIndex = 0, E = RVLocs.size(); I != E;
2790 ++I, ++InsIndex) {
2791 CCValAssign &VA = RVLocs[I];
2792 EVT CopyVT = VA.getLocVT();
2793
2794 // In some calling conventions we need to remove the used registers
2795 // from the register mask.
2796 if (RegMask) {
2797 for (MCSubRegIterator SubRegs(VA.getLocReg(), TRI, /*IncludeSelf=*/true);
2798 SubRegs.isValid(); ++SubRegs)
2799 RegMask[*SubRegs / 32] &= ~(1u << (*SubRegs % 32));
2800 }
2801
2802 // If this is x86-64, and we disabled SSE, we can't return FP values
2803 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64 || CopyVT == MVT::f128) &&
2804 ((Is64Bit || Ins[InsIndex].Flags.isInReg()) && !Subtarget.hasSSE1())) {
2805 errorUnsupported(DAG, dl, "SSE register return with SSE disabled");
2806 VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
2807 }
2808
2809 // If we prefer to use the value in xmm registers, copy it out as f80 and
2810 // use a truncate to move it from fp stack reg to xmm reg.
2811 bool RoundAfterCopy = false;
2812 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2813 isScalarFPTypeInSSEReg(VA.getValVT())) {
2814 if (!Subtarget.hasX87())
2815 report_fatal_error("X87 register return with X87 disabled");
2816 CopyVT = MVT::f80;
2817 RoundAfterCopy = (CopyVT != VA.getLocVT());
2818 }
2819
2820 SDValue Val;
2821 if (VA.needsCustom()) {
2822 assert(VA.getValVT() == MVT::v64i1 &&((VA.getValVT() == MVT::v64i1 && "Currently the only custom case is when we split v64i1 to 2 regs"
) ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 2823, __PRETTY_FUNCTION__))
2823 "Currently the only custom case is when we split v64i1 to 2 regs")((VA.getValVT() == MVT::v64i1 && "Currently the only custom case is when we split v64i1 to 2 regs"
) ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 2823, __PRETTY_FUNCTION__))
;
2824 Val =
2825 getv64i1Argument(VA, RVLocs[++I], Chain, DAG, dl, Subtarget, &InFlag);
2826 } else {
2827 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), CopyVT, InFlag)
2828 .getValue(1);
2829 Val = Chain.getValue(0);
2830 InFlag = Chain.getValue(2);
2831 }
2832
2833 if (RoundAfterCopy)
2834 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2835 // This truncation won't change the value.
2836 DAG.getIntPtrConstant(1, dl));
2837
2838 if (VA.isExtInLoc() && (VA.getValVT().getScalarType() == MVT::i1)) {
2839 if (VA.getValVT().isVector() &&
2840 ((VA.getLocVT() == MVT::i64) || (VA.getLocVT() == MVT::i32) ||
2841 (VA.getLocVT() == MVT::i16) || (VA.getLocVT() == MVT::i8))) {
2842 // promoting a mask type (v*i1) into a register of type i64/i32/i16/i8
2843 Val = lowerRegToMasks(Val, VA.getValVT(), VA.getLocVT(), dl, DAG);
2844 } else
2845 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2846 }
2847
2848 InVals.push_back(Val);
2849 }
2850
2851 return Chain;
2852}
2853
2854//===----------------------------------------------------------------------===//
2855// C & StdCall & Fast Calling Convention implementation
2856//===----------------------------------------------------------------------===//
2857// StdCall calling convention seems to be standard for many Windows' API
2858// routines and around. It differs from C calling convention just a little:
2859// callee should clean up the stack, not caller. Symbols should be also
2860// decorated in some fancy way :) It doesn't support any vector arguments.
2861// For info on fast calling convention see Fast Calling Convention (tail call)
2862// implementation LowerX86_32FastCCCallTo.
2863
2864/// CallIsStructReturn - Determines whether a call uses struct return
2865/// semantics.
2866enum StructReturnType {
2867 NotStructReturn,
2868 RegStructReturn,
2869 StackStructReturn
2870};
2871static StructReturnType
2872callIsStructReturn(ArrayRef<ISD::OutputArg> Outs, bool IsMCU) {
2873 if (Outs.empty())
2874 return NotStructReturn;
2875
2876 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2877 if (!Flags.isSRet())
2878 return NotStructReturn;
2879 if (Flags.isInReg() || IsMCU)
2880 return RegStructReturn;
2881 return StackStructReturn;
2882}
2883
2884/// Determines whether a function uses struct return semantics.
2885static StructReturnType
2886argsAreStructReturn(ArrayRef<ISD::InputArg> Ins, bool IsMCU) {
2887 if (Ins.empty())
2888 return NotStructReturn;
2889
2890 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2891 if (!Flags.isSRet())
2892 return NotStructReturn;
2893 if (Flags.isInReg() || IsMCU)
2894 return RegStructReturn;
2895 return StackStructReturn;
2896}
2897
2898/// Make a copy of an aggregate at address specified by "Src" to address
2899/// "Dst" with size and alignment information specified by the specific
2900/// parameter attribute. The copy will be passed as a byval function parameter.
2901static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
2902 SDValue Chain, ISD::ArgFlagsTy Flags,
2903 SelectionDAG &DAG, const SDLoc &dl) {
2904 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2905
2906 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2907 /*isVolatile*/false, /*AlwaysInline=*/true,
2908 /*isTailCall*/false,
2909 MachinePointerInfo(), MachinePointerInfo());
2910}
2911
2912/// Return true if the calling convention is one that we can guarantee TCO for.
2913static bool canGuaranteeTCO(CallingConv::ID CC) {
2914 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2915 CC == CallingConv::X86_RegCall || CC == CallingConv::HiPE ||
2916 CC == CallingConv::HHVM);
2917}
2918
2919/// Return true if we might ever do TCO for calls with this calling convention.
2920static bool mayTailCallThisCC(CallingConv::ID CC) {
2921 switch (CC) {
2922 // C calling conventions:
2923 case CallingConv::C:
2924 case CallingConv::Win64:
2925 case CallingConv::X86_64_SysV:
2926 // Callee pop conventions:
2927 case CallingConv::X86_ThisCall:
2928 case CallingConv::X86_StdCall:
2929 case CallingConv::X86_VectorCall:
2930 case CallingConv::X86_FastCall:
2931 // Swift:
2932 case CallingConv::Swift:
2933 return true;
2934 default:
2935 return canGuaranteeTCO(CC);
2936 }
2937}
2938
2939/// Return true if the function is being made into a tailcall target by
2940/// changing its ABI.
2941static bool shouldGuaranteeTCO(CallingConv::ID CC, bool GuaranteedTailCallOpt) {
2942 return GuaranteedTailCallOpt && canGuaranteeTCO(CC);
2943}
2944
2945bool X86TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2946 auto Attr =
2947 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2948 if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2949 return false;
2950
2951 ImmutableCallSite CS(CI);
2952 CallingConv::ID CalleeCC = CS.getCallingConv();
2953 if (!mayTailCallThisCC(CalleeCC))
2954 return false;
2955
2956 return true;
2957}
2958
2959SDValue
2960X86TargetLowering::LowerMemArgument(SDValue Chain, CallingConv::ID CallConv,
2961 const SmallVectorImpl<ISD::InputArg> &Ins,
2962 const SDLoc &dl, SelectionDAG &DAG,
2963 const CCValAssign &VA,
2964 MachineFrameInfo &MFI, unsigned i) const {
2965 // Create the nodes corresponding to a load from this parameter slot.
2966 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2967 bool AlwaysUseMutable = shouldGuaranteeTCO(
2968 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2969 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2970 EVT ValVT;
2971 MVT PtrVT = getPointerTy(DAG.getDataLayout());
2972
2973 // If value is passed by pointer we have address passed instead of the value
2974 // itself. No need to extend if the mask value and location share the same
2975 // absolute size.
2976 bool ExtendedInMem =
2977 VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1 &&
2978 VA.getValVT().getSizeInBits() != VA.getLocVT().getSizeInBits();
2979
2980 if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2981 ValVT = VA.getLocVT();
2982 else
2983 ValVT = VA.getValVT();
2984
2985 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2986 // changed with more analysis.
2987 // In case of tail call optimization mark all arguments mutable. Since they
2988 // could be overwritten by lowering of arguments in case of a tail call.
2989 if (Flags.isByVal()) {
2990 unsigned Bytes = Flags.getByValSize();
2991 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2992
2993 // FIXME: For now, all byval parameter objects are marked as aliasing. This
2994 // can be improved with deeper analysis.
2995 int FI = MFI.CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable,
2996 /*isAliased=*/true);
2997 return DAG.getFrameIndex(FI, PtrVT);
2998 }
2999
3000 // This is an argument in memory. We might be able to perform copy elision.
3001 // If the argument is passed directly in memory without any extension, then we
3002 // can perform copy elision. Large vector types, for example, may be passed
3003 // indirectly by pointer.
3004 if (Flags.isCopyElisionCandidate() &&
3005 VA.getLocInfo() != CCValAssign::Indirect && !ExtendedInMem) {
3006 EVT ArgVT = Ins[i].ArgVT;
3007 SDValue PartAddr;
3008 if (Ins[i].PartOffset == 0) {
3009 // If this is a one-part value or the first part of a multi-part value,
3010 // create a stack object for the entire argument value type and return a
3011 // load from our portion of it. This assumes that if the first part of an
3012 // argument is in memory, the rest will also be in memory.
3013 int FI = MFI.CreateFixedObject(ArgVT.getStoreSize(), VA.getLocMemOffset(),
3014 /*Immutable=*/false);
3015 PartAddr = DAG.getFrameIndex(FI, PtrVT);
3016 return DAG.getLoad(
3017 ValVT, dl, Chain, PartAddr,
3018 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3019 } else {
3020 // This is not the first piece of an argument in memory. See if there is
3021 // already a fixed stack object including this offset. If so, assume it
3022 // was created by the PartOffset == 0 branch above and create a load from
3023 // the appropriate offset into it.
3024 int64_t PartBegin = VA.getLocMemOffset();
3025 int64_t PartEnd = PartBegin + ValVT.getSizeInBits() / 8;
3026 int FI = MFI.getObjectIndexBegin();
3027 for (; MFI.isFixedObjectIndex(FI); ++FI) {
3028 int64_t ObjBegin = MFI.getObjectOffset(FI);
3029 int64_t ObjEnd = ObjBegin + MFI.getObjectSize(FI);
3030 if (ObjBegin <= PartBegin && PartEnd <= ObjEnd)
3031 break;
3032 }
3033 if (MFI.isFixedObjectIndex(FI)) {
3034 SDValue Addr =
3035 DAG.getNode(ISD::ADD, dl, PtrVT, DAG.getFrameIndex(FI, PtrVT),
3036 DAG.getIntPtrConstant(Ins[i].PartOffset, dl));
3037 return DAG.getLoad(
3038 ValVT, dl, Chain, Addr,
3039 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI,
3040 Ins[i].PartOffset));
3041 }
3042 }
3043 }
3044
3045 int FI = MFI.CreateFixedObject(ValVT.getSizeInBits() / 8,
3046 VA.getLocMemOffset(), isImmutable);
3047
3048 // Set SExt or ZExt flag.
3049 if (VA.getLocInfo() == CCValAssign::ZExt) {
3050 MFI.setObjectZExt(FI, true);
3051 } else if (VA.getLocInfo() == CCValAssign::SExt) {
3052 MFI.setObjectSExt(FI, true);
3053 }
3054
3055 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3056 SDValue Val = DAG.getLoad(
3057 ValVT, dl, Chain, FIN,
3058 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3059 return ExtendedInMem
3060 ? (VA.getValVT().isVector()
3061 ? DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VA.getValVT(), Val)
3062 : DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val))
3063 : Val;
3064}
3065
3066// FIXME: Get this from tablegen.
3067static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
3068 const X86Subtarget &Subtarget) {
3069 assert(Subtarget.is64Bit())((Subtarget.is64Bit()) ? static_cast<void> (0) : __assert_fail
("Subtarget.is64Bit()", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 3069, __PRETTY_FUNCTION__))
;
3070
3071 if (Subtarget.isCallingConvWin64(CallConv)) {
3072 static const MCPhysReg GPR64ArgRegsWin64[] = {
3073 X86::RCX, X86::RDX, X86::R8, X86::R9
3074 };
3075 return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
3076 }
3077
3078 static const MCPhysReg GPR64ArgRegs64Bit[] = {
3079 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
3080 };
3081 return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
3082}
3083
3084// FIXME: Get this from tablegen.
3085static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
3086 CallingConv::ID CallConv,
3087 const X86Subtarget &Subtarget) {
3088 assert(Subtarget.is64Bit())((Subtarget.is64Bit()) ? static_cast<void> (0) : __assert_fail
("Subtarget.is64Bit()", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 3088, __PRETTY_FUNCTION__))
;
3089 if (Subtarget.isCallingConvWin64(CallConv)) {
3090 // The XMM registers which might contain var arg parameters are shadowed
3091 // in their paired GPR. So we only need to save the GPR to their home
3092 // slots.
3093 // TODO: __vectorcall will change this.
3094 return None;
3095 }
3096
3097 const Function &F = MF.getFunction();
3098 bool NoImplicitFloatOps = F.hasFnAttribute(Attribute::NoImplicitFloat);
3099 bool isSoftFloat = Subtarget.useSoftFloat();
3100 assert(!(isSoftFloat && NoImplicitFloatOps) &&((!(isSoftFloat && NoImplicitFloatOps) && "SSE register cannot be used when SSE is disabled!"
) ? static_cast<void> (0) : __assert_fail ("!(isSoftFloat && NoImplicitFloatOps) && \"SSE register cannot be used when SSE is disabled!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 3101, __PRETTY_FUNCTION__))
3101 "SSE register cannot be used when SSE is disabled!")((!(isSoftFloat && NoImplicitFloatOps) && "SSE register cannot be used when SSE is disabled!"
) ? static_cast<void> (0) : __assert_fail ("!(isSoftFloat && NoImplicitFloatOps) && \"SSE register cannot be used when SSE is disabled!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 3101, __PRETTY_FUNCTION__))
;
3102 if (isSoftFloat || NoImplicitFloatOps || !Subtarget.hasSSE1())
3103 // Kernel mode asks for SSE to be disabled, so there are no XMM argument
3104 // registers.
3105 return None;
3106
3107 static const MCPhysReg XMMArgRegs64Bit[] = {
3108 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3109 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3110 };
3111 return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
3112}
3113
3114#ifndef NDEBUG
3115static bool isSortedByValueNo(ArrayRef<CCValAssign> ArgLocs) {
3116 return std::is_sorted(ArgLocs.begin(), ArgLocs.end(),
3117 [](const CCValAssign &A, const CCValAssign &B) -> bool {
3118 return A.getValNo() < B.getValNo();
3119 });
3120}
3121#endif
3122
3123SDValue X86TargetLowering::LowerFormalArguments(
3124 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3125 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3126 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3127 MachineFunction &MF = DAG.getMachineFunction();
3128 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3129 const TargetFrameLowering &TFI = *Subtarget.getFrameLowering();
3130
3131 const Function &F = MF.getFunction();
3132 if (F.hasExternalLinkage() && Subtarget.isTargetCygMing() &&
3133 F.getName() == "main")
3134 FuncInfo->setForceFramePointer(true);
3135
3136 MachineFrameInfo &MFI = MF.getFrameInfo();
3137 bool Is64Bit = Subtarget.is64Bit();
3138 bool IsWin64 = Subtarget.isCallingConvWin64(CallConv);
3139
3140 assert(((!(isVarArg && canGuaranteeTCO(CallConv)) &&
"Var args not supported with calling conv' regcall, fastcc, ghc or hipe"
) ? static_cast<void> (0) : __assert_fail ("!(isVarArg && canGuaranteeTCO(CallConv)) && \"Var args not supported with calling conv' regcall, fastcc, ghc or hipe\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 3142, __PRETTY_FUNCTION__))
3141 !(isVarArg && canGuaranteeTCO(CallConv)) &&((!(isVarArg && canGuaranteeTCO(CallConv)) &&
"Var args not supported with calling conv' regcall, fastcc, ghc or hipe"
) ? static_cast<void> (0) : __assert_fail ("!(isVarArg && canGuaranteeTCO(CallConv)) && \"Var args not supported with calling conv' regcall, fastcc, ghc or hipe\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 3142, __PRETTY_FUNCTION__))
3142 "Var args not supported with calling conv' regcall, fastcc, ghc or hipe")((!(isVarArg && canGuaranteeTCO(CallConv)) &&
"Var args not supported with calling conv' regcall, fastcc, ghc or hipe"
) ? static_cast<void> (0) : __assert_fail ("!(isVarArg && canGuaranteeTCO(CallConv)) && \"Var args not supported with calling conv' regcall, fastcc, ghc or hipe\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 3142, __PRETTY_FUNCTION__))
;
3143
3144 // Assign locations to all of the incoming arguments.
3145 SmallVector<CCValAssign, 16> ArgLocs;
3146 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
3147
3148 // Allocate shadow area for Win64.
3149 if (IsWin64)
3150 CCInfo.AllocateStack(32, 8);
3151
3152 CCInfo.AnalyzeArguments(Ins, CC_X86);
3153
3154 // In vectorcall calling convention a second pass is required for the HVA
3155 // types.
3156 if (CallingConv::X86_VectorCall == CallConv) {
3157 CCInfo.AnalyzeArgumentsSecondPass(Ins, CC_X86);
3158 }
3159
3160 // The next loop assumes that the locations are in the same order of the
3161 // input arguments.
3162 assert(isSortedByValueNo(ArgLocs) &&((isSortedByValueNo(ArgLocs) && "Argument Location list must be sorted before lowering"
) ? static_cast<void> (0) : __assert_fail ("isSortedByValueNo(ArgLocs) && \"Argument Location list must be sorted before lowering\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 3163, __PRETTY_FUNCTION__))
3163 "Argument Location list must be sorted before lowering")((isSortedByValueNo(ArgLocs) && "Argument Location list must be sorted before lowering"
) ? static_cast<void> (0) : __assert_fail ("isSortedByValueNo(ArgLocs) && \"Argument Location list must be sorted before lowering\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 3163, __PRETTY_FUNCTION__))
;
3164
3165 SDValue ArgValue;
3166 for (unsigned I = 0, InsIndex = 0, E = ArgLocs.size(); I != E;
3167 ++I, ++InsIndex) {
3168 assert(InsIndex < Ins.size() && "Invalid Ins index")((InsIndex < Ins.size() && "Invalid Ins index") ? static_cast
<void> (0) : __assert_fail ("InsIndex < Ins.size() && \"Invalid Ins index\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 3168, __PRETTY_FUNCTION__))
;
3169 CCValAssign &VA = ArgLocs[I];
3170
3171 if (VA.isRegLoc()) {
3172 EVT RegVT = VA.getLocVT();
3173 if (VA.needsCustom()) {
3174 assert(((VA.getValVT() == MVT::v64i1 && "Currently the only custom case is when we split v64i1 to 2 regs"
) ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 3176, __PRETTY_FUNCTION__))
3175 VA.getValVT() == MVT::v64i1 &&((VA.getValVT() == MVT::v64i1 && "Currently the only custom case is when we split v64i1 to 2 regs"
) ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 3176, __PRETTY_FUNCTION__))
3176 "Currently the only custom case is when we split v64i1 to 2 regs")((VA.getValVT() == MVT::v64i1 && "Currently the only custom case is when we split v64i1 to 2 regs"
) ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 3176, __PRETTY_FUNCTION__))
;
3177
3178 // v64i1 values, in regcall calling convention, that are
3179 // compiled to 32 bit arch, are split up into two registers.
3180 ArgValue =
3181 getv64i1Argument(VA, ArgLocs[++I], Chain, DAG, dl, Subtarget);
3182 } else {
3183 const TargetRegisterClass *RC;
3184 if (RegVT == MVT::i8)
3185 RC = &X86::GR8RegClass;
3186 else if (RegVT == MVT::i16)
3187 RC = &X86::GR16RegClass;
3188 else if (RegVT == MVT::i32)
3189 RC = &X86::GR32RegClass;
3190 else if (Is64Bit && RegVT == MVT::i64)
3191 RC = &X86::GR64RegClass;
3192 else if (RegVT == MVT::f32)
3193 RC = Subtarget.hasAVX512() ? &X86::FR32XRegClass : &X86::FR32RegClass;
3194 else if (RegVT == MVT::f64)
3195 RC = Subtarget.hasAVX512() ? &X86::FR64XRegClass : &X86::FR64RegClass;
3196 else if (RegVT == MVT::f80)
3197 RC = &X86::RFP80RegClass;
3198 else if (RegVT == MVT::f128)
3199 RC = &X86::VR128RegClass;
3200 else if (RegVT.is512BitVector())
3201 RC = &X86::VR512RegClass;
3202 else if (RegVT.is256BitVector())
3203 RC = Subtarget.hasVLX() ? &X86::VR256XRegClass : &X86::VR256RegClass;
3204 else if (RegVT.is128BitVector())
3205 RC = Subtarget.hasVLX() ? &X86::VR128XRegClass : &X86::VR128RegClass;
3206 else if (RegVT == MVT::x86mmx)
3207 RC = &X86::VR64RegClass;
3208 else if (RegVT == MVT::v1i1)
3209 RC = &X86::VK1RegClass;
3210 else if (RegVT == MVT::v8i1)
3211 RC = &X86::VK8RegClass;
3212 else if (RegVT == MVT::v16i1)
3213 RC = &X86::VK16RegClass;
3214 else if (RegVT == MVT::v32i1)
3215 RC = &X86::VK32RegClass;
3216 else if (RegVT == MVT::v64i1)
3217 RC = &X86::VK64RegClass;
3218 else
3219 llvm_unreachable("Unknown argument type!")::llvm::llvm_unreachable_internal("Unknown argument type!", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 3219)
;
3220
3221 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3222 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3223 }
3224
3225 // If this is an 8 or 16-bit value, it is really passed promoted to 32
3226 // bits. Insert an assert[sz]ext to capture this, then truncate to the
3227 // right size.
3228 if (VA.getLocInfo() == CCValAssign::SExt)
3229 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3230 DAG.getValueType(VA.getValVT()));
3231 else if (VA.getLocInfo() == CCValAssign::ZExt)
3232 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3233 DAG.getValueType(VA.getValVT()));
3234 else if (VA.getLocInfo() == CCValAssign::BCvt)
3235 ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
3236
3237 if (VA.isExtInLoc()) {
3238 // Handle MMX values passed in XMM regs.
3239 if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
3240 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
3241 else if (VA.getValVT().isVector() &&
3242 VA.getValVT().getScalarType() == MVT::i1 &&
3243 ((VA.getLocVT() == MVT::i64) || (VA.getLocVT() == MVT::i32) ||
3244 (VA.getLocVT() == MVT::i16) || (VA.getLocVT() == MVT::i8))) {
3245 // Promoting a mask type (v*i1) into a register of type i64/i32/i16/i8
3246 ArgValue = lowerRegToMasks(ArgValue, VA.getValVT(), RegVT, dl, DAG);
3247 } else
3248 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3249 }
3250 } else {
3251 assert(VA.isMemLoc())((VA.isMemLoc()) ? static_cast<void> (0) : __assert_fail
("VA.isMemLoc()", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 3251, __PRETTY_FUNCTION__))
;
3252 ArgValue =
3253 LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, InsIndex);
3254 }
3255
3256 // If value is passed via pointer - do a load.
3257 if (VA.getLocInfo() == CCValAssign::Indirect && !Ins[I].Flags.isByVal())
3258 ArgValue =
3259 DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, MachinePointerInfo());
3260
3261 InVals.push_back(ArgValue);
3262 }
3263
3264 for (unsigned I = 0, E = Ins.size(); I != E; ++I) {
3265 // Swift calling convention does not require we copy the sret argument
3266 // into %rax/%eax for the return. We don't set SRetReturnReg for Swift.
3267 if (CallConv == CallingConv::Swift)
3268 continue;
3269
3270 // All x86 ABIs require that for returning structs by value we copy the
3271 // sret argument into %rax/%eax (depending on ABI) for the return. Save
3272 // the argument into a virtual register so that we can access it from the
3273 // return points.
3274 if (Ins[I].Flags.isSRet()) {
3275 unsigned Reg = FuncInfo->getSRetReturnReg();
3276 if (!Reg) {
3277 MVT PtrTy = getPointerTy(DAG.getDataLayout());
3278 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
3279 FuncInfo->setSRetReturnReg(Reg);
3280 }
3281 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[I]);
3282 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
3283 break;
3284 }
3285 }
3286
3287 unsigned StackSize = CCInfo.getNextStackOffset();
3288 // Align stack specially for tail calls.
3289 if (shouldGuaranteeTCO(CallConv,
3290 MF.getTarget().Options.GuaranteedTailCallOpt))
3291 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
3292
3293 // If the function takes variable number of arguments, make a frame index for
3294 // the start of the first vararg value... for expansion of llvm.va_start. We
3295 // can skip this if there are no va_start calls.
3296 if (MFI.hasVAStart() &&
3297 (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
3298 CallConv != CallingConv::X86_ThisCall))) {
3299 FuncInfo->setVarArgsFrameIndex(MFI.CreateFixedObject(1, StackSize, true));
3300 }
3301
3302 // Figure out if XMM registers are in use.
3303 assert(!(Subtarget.useSoftFloat() &&((!(Subtarget.useSoftFloat() && F.hasFnAttribute(Attribute
::NoImplicitFloat)) && "SSE register cannot be used when SSE is disabled!"
) ? static_cast<void> (0) : __assert_fail ("!(Subtarget.useSoftFloat() && F.hasFnAttribute(Attribute::NoImplicitFloat)) && \"SSE register cannot be used when SSE is disabled!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 3305, __PRETTY_FUNCTION__))
3304 F.hasFnAttribute(Attribute::NoImplicitFloat)) &&((!(Subtarget.useSoftFloat() && F.hasFnAttribute(Attribute
::NoImplicitFloat)) && "SSE register cannot be used when SSE is disabled!"
) ? static_cast<void> (0) : __assert_fail ("!(Subtarget.useSoftFloat() && F.hasFnAttribute(Attribute::NoImplicitFloat)) && \"SSE register cannot be used when SSE is disabled!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 3305, __PRETTY_FUNCTION__))
3305 "SSE register cannot be used when SSE is disabled!")((!(Subtarget.useSoftFloat() && F.hasFnAttribute(Attribute
::NoImplicitFloat)) && "SSE register cannot be used when SSE is disabled!"
) ? static_cast<void> (0) : __assert_fail ("!(Subtarget.useSoftFloat() && F.hasFnAttribute(Attribute::NoImplicitFloat)) && \"SSE register cannot be used when SSE is disabled!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 3305, __PRETTY_FUNCTION__))
;
3306
3307 // 64-bit calling conventions support varargs and register parameters, so we
3308 // have to do extra work to spill them in the prologue.
3309 if (Is64Bit && isVarArg && MFI.hasVAStart()) {
3310 // Find the first unallocated argument registers.
3311 ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
3312 ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
3313 unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
3314 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
3315 assert(!(NumXMMRegs && !Subtarget.hasSSE1()) &&((!(NumXMMRegs && !Subtarget.hasSSE1()) && "SSE register cannot be used when SSE is disabled!"
) ? static_cast<void> (0) : __assert_fail ("!(NumXMMRegs && !Subtarget.hasSSE1()) && \"SSE register cannot be used when SSE is disabled!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 3316, __PRETTY_FUNCTION__))
3316 "SSE register cannot be used when SSE is disabled!")((!(NumXMMRegs && !Subtarget.hasSSE1()) && "SSE register cannot be used when SSE is disabled!"
) ? static_cast<void> (0) : __assert_fail ("!(NumXMMRegs && !Subtarget.hasSSE1()) && \"SSE register cannot be used when SSE is disabled!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 3316, __PRETTY_FUNCTION__))
;
3317
3318 // Gather all the live in physical registers.
3319 SmallVector<SDValue, 6> LiveGPRs;
3320 SmallVector<SDValue, 8> LiveXMMRegs;
3321 SDValue ALVal;
3322 for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
3323 unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
3324 LiveGPRs.push_back(
3325 DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
3326 }
3327 if (!ArgXMMs.empty()) {
3328 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
3329 ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
3330 for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
3331 unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
3332 LiveXMMRegs.push_back(
3333 DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
3334 }
3335 }
3336
3337 if (IsWin64) {
3338 // Get to the caller-allocated home save location. Add 8 to account
3339 // for the return address.
3340 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
3341 FuncInfo->setRegSaveFrameIndex(
3342 MFI.CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
3343 // Fixup to set vararg frame on shadow area (4 x i64).
3344 if (NumIntRegs < 4)
3345 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
3346 } else {
3347 // For X86-64, if there are vararg parameters that are passed via
3348 // registers, then we must store them to their spots on the stack so
3349 // they may be loaded by dereferencing the result of va_next.
3350 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
3351 FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
3352 FuncInfo->setRegSaveFrameIndex(MFI.CreateStackObject(
3353 ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
3354 }
3355
3356 // Store the integer parameter registers.
3357 SmallVector<SDValue, 8> MemOps;
3358 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
3359 getPointerTy(DAG.getDataLayout()));
3360 unsigned Offset = FuncInfo->getVarArgsGPOffset();
3361 for (SDValue Val : LiveGPRs) {
3362 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3363 RSFIN, DAG.getIntPtrConstant(Offset, dl));
3364 SDValue Store =
3365 DAG.getStore(Val.getValue(1), dl, Val, FIN,
3366 MachinePointerInfo::getFixedStack(
3367 DAG.getMachineFunction(),
3368 FuncInfo->getRegSaveFrameIndex(), Offset));
3369 MemOps.push_back(Store);
3370 Offset += 8;
3371 }
3372
3373 if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
3374 // Now store the XMM (fp + vector) parameter registers.
3375 SmallVector<SDValue, 12> SaveXMMOps;
3376 SaveXMMOps.push_back(Chain);
3377 SaveXMMOps.push_back(ALVal);
3378 SaveXMMOps.push_back(DAG.getIntPtrConstant(
3379 FuncInfo->getRegSaveFrameIndex(), dl));
3380 SaveXMMOps.push_back(DAG.getIntPtrConstant(
3381 FuncInfo->getVarArgsFPOffset(), dl));
3382 SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
3383 LiveXMMRegs.end());
3384 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
3385 MVT::Other, SaveXMMOps));
3386 }
3387
3388 if (!MemOps.empty())
3389 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3390 }
3391
3392 if (isVarArg && MFI.hasMustTailInVarArgFunc()) {
3393 // Find the largest legal vector type.
3394 MVT VecVT = MVT::Other;
3395 // FIXME: Only some x86_32 calling conventions support AVX512.
3396 if (Subtarget.hasAVX512() &&
3397 (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
3398 CallConv == CallingConv::Intel_OCL_BI)))
3399 VecVT = MVT::v16f32;
3400 else if (Subtarget.hasAVX())
3401 VecVT = MVT::v8f32;
3402 else if (Subtarget.hasSSE2())
3403 VecVT = MVT::v4f32;
3404
3405 // We forward some GPRs and some vector types.
3406 SmallVector<MVT, 2> RegParmTypes;
3407 MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
3408 RegParmTypes.push_back(IntVT);
3409 if (VecVT != MVT::Other)
3410 RegParmTypes.push_back(VecVT);
3411
3412 // Compute the set of forwarded registers. The rest are scratch.
3413 SmallVectorImpl<ForwardedRegister> &Forwards =
3414 FuncInfo->getForwardedMustTailRegParms();
3415 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
3416
3417 // Conservatively forward AL on x86_64, since it might be used for varargs.
3418 if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
3419 unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
3420 Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
3421 }
3422
3423 // Copy all forwards from physical to virtual registers.
3424 for (ForwardedRegister &FR : Forwards) {
3425 // FIXME: Can we use a less constrained schedule?
3426 SDValue RegVal = DAG.getCopyFromReg(Chain, dl, FR.VReg, FR.VT);
3427 FR.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(FR.VT));
3428 Chain = DAG.getCopyToReg(Chain, dl, FR.VReg, RegVal);
3429 }
3430 }
3431
3432 // Some CCs need callee pop.
3433 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3434 MF.getTarget().Options.GuaranteedTailCallOpt)) {
3435 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
3436 } else if (CallConv == CallingConv::X86_INTR && Ins.size() == 2) {
3437 // X86 interrupts must pop the error code (and the alignment padding) if
3438 // present.
3439 FuncInfo->setBytesToPopOnReturn(Is64Bit ? 16 : 4);
3440 } else {
3441 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
3442 // If this is an sret function, the return should pop the hidden pointer.
3443 if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
3444 !Subtarget.getTargetTriple().isOSMSVCRT() &&
3445 argsAreStructReturn(Ins, Subtarget.isTargetMCU()) == StackStructReturn)
3446 FuncInfo->setBytesToPopOnReturn(4);
3447 }
3448
3449 if (!Is64Bit) {
3450 // RegSaveFrameIndex is X86-64 only.
3451 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
3452 if (CallConv == CallingConv::X86_FastCall ||
3453 CallConv == CallingConv::X86_ThisCall)
3454 // fastcc functions can't have varargs.
3455 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
3456 }
3457
3458 FuncInfo->setArgumentStackSize(StackSize);
3459
3460 if (WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo()) {
3461 EHPersonality Personality = classifyEHPersonality(F.getPersonalityFn());
3462 if (Personality == EHPersonality::CoreCLR) {
3463 assert(Is64Bit)((Is64Bit) ? static_cast<void> (0) : __assert_fail ("Is64Bit"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 3463, __PRETTY_FUNCTION__))
;
3464 // TODO: Add a mechanism to frame lowering that will allow us to indicate
3465 // that we'd prefer this slot be allocated towards the bottom of the frame
3466 // (i.e. near the stack pointer after allocating the frame). Every
3467 // funclet needs a copy of this slot in its (mostly empty) frame, and the
3468 // offset from the bottom of this and each funclet's frame must be the
3469 // same, so the size of funclets' (mostly empty) frames is dictated by
3470 // how far this slot is from the bottom (since they allocate just enough
3471 // space to accommodate holding this slot at the correct offset).
3472 int PSPSymFI = MFI.CreateStackObject(8, 8, /*isSS=*/false);
3473 EHInfo->PSPSymFrameIdx = PSPSymFI;
3474 }
3475 }
3476
3477 if (CallConv == CallingConv::X86_RegCall ||
3478 F.hasFnAttribute("no_caller_saved_registers")) {
3479 MachineRegisterInfo &MRI = MF.getRegInfo();
3480 for (std::pair<unsigned, unsigned> Pair : MRI.liveins())
3481 MRI.disableCalleeSavedRegister(Pair.first);
3482 }
3483
3484 return Chain;
3485}
3486
3487SDValue X86TargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
3488 SDValue Arg, const SDLoc &dl,
3489 SelectionDAG &DAG,
3490 const CCValAssign &VA,
3491 ISD::ArgFlagsTy Flags) const {
3492 unsigned LocMemOffset = VA.getLocMemOffset();
3493 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
3494 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3495 StackPtr, PtrOff);
3496 if (Flags.isByVal())
3497 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
3498
3499 return DAG.getStore(
3500 Chain, dl, Arg, PtrOff,
3501 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
3502}
3503
3504/// Emit a load of return address if tail call
3505/// optimization is performed and it is required.
3506SDValue X86TargetLowering::EmitTailCallLoadRetAddr(
3507 SelectionDAG &DAG, SDValue &OutRetAddr, SDValue Chain, bool IsTailCall,
3508 bool Is64Bit, int FPDiff, const SDLoc &dl) const {
3509 // Adjust the Return address stack slot.
3510 EVT VT = getPointerTy(DAG.getDataLayout());
3511 OutRetAddr = getReturnAddressFrameIndex(DAG);
3512
3513 // Load the "old" Return address.
3514 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo());
3515 return SDValue(OutRetAddr.getNode(), 1);
3516}
3517
3518/// Emit a store of the return address if tail call
3519/// optimization is performed and it is required (FPDiff!=0).
3520static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
3521 SDValue Chain, SDValue RetAddrFrIdx,
3522 EVT PtrVT, unsigned SlotSize,
3523 int FPDiff, const SDLoc &dl) {
3524 // Store the return address to the appropriate stack slot.
3525 if (!FPDiff) return Chain;
3526 // Calculate the new stack slot for the return address.
3527 int NewReturnAddrFI =
3528 MF.getFrameInfo().CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
3529 false);
3530 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
3531 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
3532 MachinePointerInfo::getFixedStack(
3533 DAG.getMachineFunction(), NewReturnAddrFI));
3534 return Chain;
3535}
3536
3537/// Returns a vector_shuffle mask for an movs{s|d}, movd
3538/// operation of specified width.
3539static SDValue getMOVL(SelectionDAG &DAG, const SDLoc &dl, MVT VT, SDValue V1,
3540 SDValue V2) {
3541 unsigned NumElems = VT.getVectorNumElements();
3542 SmallVector<int, 8> Mask;
3543 Mask.push_back(NumElems);
3544 for (unsigned i = 1; i != NumElems; ++i)
3545 Mask.push_back(i);
3546 return DAG.getVectorShuffle(VT, dl, V1, V2, Mask);
3547}
3548
3549SDValue
3550X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3551 SmallVectorImpl<SDValue> &InVals) const {
3552 SelectionDAG &DAG = CLI.DAG;
3553 SDLoc &dl = CLI.DL;
3554 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3555 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
3556 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
3557 SDValue Chain = CLI.Chain;
3558 SDValue Callee = CLI.Callee;
3559 CallingConv::ID CallConv = CLI.CallConv;
3560 bool &isTailCall = CLI.IsTailCall;
3561 bool isVarArg = CLI.IsVarArg;
3562
3563 MachineFunction &MF = DAG.getMachineFunction();
3564 bool Is64Bit = Subtarget.is64Bit();
3565 bool IsWin64 = Subtarget.isCallingConvWin64(CallConv);
3566 StructReturnType SR = callIsStructReturn(Outs, Subtarget.isTargetMCU());
3567 bool IsSibcall = false;
3568 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
3569 auto Attr = MF.getFunction().getFnAttribute("disable-tail-calls");
3570 const auto *CI = dyn_cast_or_null<CallInst>(CLI.CS.getInstruction());
3571 const Function *Fn = CI ? CI->getCalledFunction() : nullptr;
3572 bool HasNCSR = (CI && CI->hasFnAttr("no_caller_saved_registers")) ||
3573 (Fn && Fn->hasFnAttribute("no_caller_saved_registers"));
3574 const auto *II = dyn_cast_or_null<InvokeInst>(CLI.CS.getInstruction());
3575 bool HasNoCfCheck =
3576 (CI && CI->doesNoCfCheck()) || (II && II->doesNoCfCheck());
3577 const Module *M = MF.getMMI().getModule();
3578 Metadata *IsCFProtectionSupported = M->getModuleFlag("cf-protection-branch");
3579
3580 if (CallConv == CallingConv::X86_INTR)
3581 report_fatal_error("X86 interrupts may not be called directly");
3582
3583 if (Attr.getValueAsString() == "true")
3584 isTailCall = false;
3585
3586 if (Subtarget.isPICStyleGOT() &&
3587 !MF.getTarget().Options.GuaranteedTailCallOpt) {
3588 // If we are using a GOT, disable tail calls to external symbols with
3589 // default visibility. Tail calling such a symbol requires using a GOT
3590 // relocation, which forces early binding of the symbol. This breaks code
3591 // that require lazy function symbol resolution. Using musttail or
3592 // GuaranteedTailCallOpt will override this.
3593 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3594 if (!G || (!G->getGlobal()->hasLocalLinkage() &&
3595 G->getGlobal()->hasDefaultVisibility()))
3596 isTailCall = false;
3597 }
3598
3599 bool IsMustTail = CLI.CS && CLI.CS.isMustTailCall();
3600 if (IsMustTail) {
3601 // Force this to be a tail call. The verifier rules are enough to ensure
3602 // that we can lower this successfully without moving the return address
3603 // around.
3604 isTailCall = true;
3605 } else if (isTailCall) {
3606 // Check if it's really possible to do a tail call.
3607 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
3608 isVarArg, SR != NotStructReturn,
3609 MF.getFunction().hasStructRetAttr(), CLI.RetTy,
3610 Outs, OutVals, Ins, DAG);
3611
3612 // Sibcalls are automatically detected tailcalls which do not require
3613 // ABI changes.
3614 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
3615 IsSibcall = true;
3616
3617 if (isTailCall)
3618 ++NumTailCalls;
3619 }
3620
3621 assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&((!(isVarArg && canGuaranteeTCO(CallConv)) &&
"Var args not supported with calling convention fastcc, ghc or hipe"
) ? static_cast<void> (0) : __assert_fail ("!(isVarArg && canGuaranteeTCO(CallConv)) && \"Var args not supported with calling convention fastcc, ghc or hipe\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 3622, __PRETTY_FUNCTION__))
3622 "Var args not supported with calling convention fastcc, ghc or hipe")((!(isVarArg && canGuaranteeTCO(CallConv)) &&
"Var args not supported with calling convention fastcc, ghc or hipe"
) ? static_cast<void> (0) : __assert_fail ("!(isVarArg && canGuaranteeTCO(CallConv)) && \"Var args not supported with calling convention fastcc, ghc or hipe\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 3622, __PRETTY_FUNCTION__))
;
3623
3624 // Analyze operands of the call, assigning locations to each operand.
3625 SmallVector<CCValAssign, 16> ArgLocs;
3626 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
3627
3628 // Allocate shadow area for Win64.
3629 if (IsWin64)
3630 CCInfo.AllocateStack(32, 8);
3631
3632 CCInfo.AnalyzeArguments(Outs, CC_X86);
3633
3634 // In vectorcall calling convention a second pass is required for the HVA
3635 // types.
3636 if (CallingConv::X86_VectorCall == CallConv) {
3637 CCInfo.AnalyzeArgumentsSecondPass(Outs, CC_X86);
3638 }
3639
3640 // Get a count of how many bytes are to be pushed on the stack.
3641 unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
3642 if (IsSibcall)
3643 // This is a sibcall. The memory operands are available in caller's
3644 // own caller's stack.
3645 NumBytes = 0;
3646 else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
3647 canGuaranteeTCO(CallConv))
3648 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
3649
3650 int FPDiff = 0;
3651 if (isTailCall && !IsSibcall && !IsMustTail) {
3652 // Lower arguments at fp - stackoffset + fpdiff.
3653 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
3654
3655 FPDiff = NumBytesCallerPushed - NumBytes;
3656
3657 // Set the delta of movement of the returnaddr stackslot.
3658 // But only set if delta is greater than previous delta.
3659 if (FPDiff < X86Info->getTCReturnAddrDelta())
3660 X86Info->setTCReturnAddrDelta(FPDiff);
3661 }
3662
3663 unsigned NumBytesToPush = NumBytes;
3664 unsigned NumBytesToPop = NumBytes;
3665
3666 // If we have an inalloca argument, all stack space has already been allocated
3667 // for us and be right at the top of the stack. We don't support multiple
3668 // arguments passed in memory when using inalloca.
3669 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
3670 NumBytesToPush = 0;
3671 if (!ArgLocs.back().isMemLoc())
3672 report_fatal_error("cannot use inalloca attribute on a register "
3673 "parameter");
3674 if (ArgLocs.back().getLocMemOffset() != 0)
3675 report_fatal_error("any parameter with the inalloca attribute must be "
3676 "the only memory argument");
3677 }
3678
3679 if (!IsSibcall)
3680 Chain = DAG.getCALLSEQ_START(Chain, NumBytesToPush,
3681 NumBytes - NumBytesToPush, dl);
3682
3683 SDValue RetAddrFrIdx;
3684 // Load return address for tail calls.
3685 if (isTailCall && FPDiff)
3686 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3687 Is64Bit, FPDiff, dl);
3688
3689 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3690 SmallVector<SDValue, 8> MemOpChains;
3691 SDValue StackPtr;
3692
3693 // The next loop assumes that the locations are in the same order of the
3694 // input arguments.
3695 assert(isSortedByValueNo(ArgLocs) &&((isSortedByValueNo(ArgLocs) && "Argument Location list must be sorted before lowering"
) ? static_cast<void> (0) : __assert_fail ("isSortedByValueNo(ArgLocs) && \"Argument Location list must be sorted before lowering\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 3696, __PRETTY_FUNCTION__))
3696 "Argument Location list must be sorted before lowering")((isSortedByValueNo(ArgLocs) && "Argument Location list must be sorted before lowering"
) ? static_cast<void> (0) : __assert_fail ("isSortedByValueNo(ArgLocs) && \"Argument Location list must be sorted before lowering\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 3696, __PRETTY_FUNCTION__))
;
3697
3698 // Walk the register/memloc assignments, inserting copies/loads. In the case
3699 // of tail call optimization arguments are handle later.
3700 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
3701 for (unsigned I = 0, OutIndex = 0, E = ArgLocs.size(); I != E;
3702 ++I, ++OutIndex) {
3703 assert(OutIndex < Outs.size() && "Invalid Out index")((OutIndex < Outs.size() && "Invalid Out index") ?
static_cast<void> (0) : __assert_fail ("OutIndex < Outs.size() && \"Invalid Out index\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 3703, __PRETTY_FUNCTION__))
;
3704 // Skip inalloca arguments, they have already been written.
3705 ISD::ArgFlagsTy Flags = Outs[OutIndex].Flags;
3706 if (Flags.isInAlloca())
3707 continue;
3708
3709 CCValAssign &VA = ArgLocs[I];
3710 EVT RegVT = VA.getLocVT();
3711 SDValue Arg = OutVals[OutIndex];
3712 bool isByVal = Flags.isByVal();
3713
3714 // Promote the value if needed.
3715 switch (VA.getLocInfo()) {
3716 default: llvm_unreachable("Unknown loc info!")::llvm::llvm_unreachable_internal("Unknown loc info!", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 3716)
;
3717 case CCValAssign::Full: break;
3718 case CCValAssign::SExt:
3719 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3720 break;
3721 case CCValAssign::ZExt:
3722 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3723 break;
3724 case CCValAssign::AExt:
3725 if (Arg.getValueType().isVector() &&
3726 Arg.getValueType().getVectorElementType() == MVT::i1)
3727 Arg = lowerMasksToReg(Arg, RegVT, dl, DAG);
3728 else if (RegVT.is128BitVector()) {
3729 // Special case: passing MMX values in XMM registers.
3730 Arg = DAG.getBitcast(MVT::i64, Arg);
3731 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3732 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3733 } else
3734 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3735 break;
3736 case CCValAssign::BCvt:
3737 Arg = DAG.getBitcast(RegVT, Arg);
3738 break;
3739 case CCValAssign::Indirect: {
3740 if (isByVal) {
3741 // Memcpy the argument to a temporary stack slot to prevent
3742 // the caller from seeing any modifications the callee may make
3743 // as guaranteed by the `byval` attribute.
3744 int FrameIdx = MF.getFrameInfo().CreateStackObject(
3745 Flags.getByValSize(), std::max(16, (int)Flags.getByValAlign()),
3746 false);
3747 SDValue StackSlot =
3748 DAG.getFrameIndex(FrameIdx, getPointerTy(DAG.getDataLayout()));
3749 Chain =
3750 CreateCopyOfByValArgument(Arg, StackSlot, Chain, Flags, DAG, dl);
3751 // From now on treat this as a regular pointer
3752 Arg = StackSlot;
3753 isByVal = false;
3754 } else {
3755 // Store the argument.
3756 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3757 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3758 Chain = DAG.getStore(
3759 Chain, dl, Arg, SpillSlot,
3760 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3761 Arg = SpillSlot;
3762 }
3763 break;
3764 }
3765 }
3766
3767 if (VA.needsCustom()) {
3768 assert(VA.getValVT() == MVT::v64i1 &&((VA.getValVT() == MVT::v64i1 && "Currently the only custom case is when we split v64i1 to 2 regs"
) ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 3769, __PRETTY_FUNCTION__))
3769 "Currently the only custom case is when we split v64i1 to 2 regs")((VA.getValVT() == MVT::v64i1 && "Currently the only custom case is when we split v64i1 to 2 regs"
) ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 3769, __PRETTY_FUNCTION__))
;
3770 // Split v64i1 value into two registers
3771 Passv64i1ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++I],
3772 Subtarget);
3773 } else if (VA.isRegLoc()) {
3774 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3775 if (isVarArg && IsWin64) {
3776 // Win64 ABI requires argument XMM reg to be copied to the corresponding
3777 // shadow reg if callee is a varargs function.
3778 unsigned ShadowReg = 0;
3779 switch (VA.getLocReg()) {
3780 case X86::XMM0: ShadowReg = X86::RCX; break;
3781 case X86::XMM1: ShadowReg = X86::RDX; break;
3782 case X86::XMM2: ShadowReg = X86::R8; break;
3783 case X86::XMM3: ShadowReg = X86::R9; break;
3784 }
3785 if (ShadowReg)
3786 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3787 }
3788 } else if (!IsSibcall && (!isTailCall || isByVal)) {
3789 assert(VA.isMemLoc())((VA.isMemLoc()) ? static_cast<void> (0) : __assert_fail
("VA.isMemLoc()", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 3789, __PRETTY_FUNCTION__))
;
3790 if (!StackPtr.getNode())
3791 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3792 getPointerTy(DAG.getDataLayout()));
3793 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3794 dl, DAG, VA, Flags));
3795 }
3796 }
3797
3798 if (!MemOpChains.empty())
3799 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3800
3801 if (Subtarget.isPICStyleGOT()) {
3802 // ELF / PIC requires GOT in the EBX register before function calls via PLT
3803 // GOT pointer.
3804 if (!isTailCall) {
3805 RegsToPass.push_back(std::make_pair(
3806 unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3807 getPointerTy(DAG.getDataLayout()))));
3808 } else {
3809 // If we are tail calling and generating PIC/GOT style code load the
3810 // address of the callee into ECX. The value in ecx is used as target of
3811 // the tail jump. This is done to circumvent the ebx/callee-saved problem
3812 // for tail calls on PIC/GOT architectures. Normally we would just put the
3813 // address of GOT into ebx and then call target@PLT. But for tail calls
3814 // ebx would be restored (since ebx is callee saved) before jumping to the
3815 // target@PLT.
3816
3817 // Note: The actual moving to ECX is done further down.
3818 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3819 if (G && !G->getGlobal()->hasLocalLinkage() &&
3820 G->getGlobal()->hasDefaultVisibility())
3821 Callee = LowerGlobalAddress(Callee, DAG);
3822 else if (isa<ExternalSymbolSDNode>(Callee))
3823 Callee = LowerExternalSymbol(Callee, DAG);
3824 }
3825 }
3826
3827 if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3828 // From AMD64 ABI document:
3829 // For calls that may call functions that use varargs or stdargs
3830 // (prototype-less calls or calls to functions containing ellipsis (...) in
3831 // the declaration) %al is used as hidden argument to specify the number
3832 // of SSE registers used. The contents of %al do not need to match exactly
3833 // the number of registers, but must be an ubound on the number of SSE
3834 // registers used and is in the range 0 - 8 inclusive.
3835
3836 // Count the number of XMM registers allocated.
3837 static const MCPhysReg XMMArgRegs[] = {
3838 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3839 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3840 };
3841 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3842 assert((Subtarget.hasSSE1() || !NumXMMRegs)(((Subtarget.hasSSE1() || !NumXMMRegs) && "SSE registers cannot be used when SSE is disabled"
) ? static_cast<void> (0) : __assert_fail ("(Subtarget.hasSSE1() || !NumXMMRegs) && \"SSE registers cannot be used when SSE is disabled\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 3843, __PRETTY_FUNCTION__))
3843 && "SSE registers cannot be used when SSE is disabled")(((Subtarget.hasSSE1() || !NumXMMRegs) && "SSE registers cannot be used when SSE is disabled"
) ? static_cast<void> (0) : __assert_fail ("(Subtarget.hasSSE1() || !NumXMMRegs) && \"SSE registers cannot be used when SSE is disabled\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 3843, __PRETTY_FUNCTION__))
;
3844
3845 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3846 DAG.getConstant(NumXMMRegs, dl,
3847 MVT::i8)));
3848 }
3849
3850 if (isVarArg && IsMustTail) {
3851 const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3852 for (const auto &F : Forwards) {
3853 SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3854 RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3855 }
3856 }
3857
3858 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
3859 // don't need this because the eligibility check rejects calls that require
3860 // shuffling arguments passed in memory.
3861 if (!IsSibcall && isTailCall) {
3862 // Force all the incoming stack arguments to be loaded from the stack
3863 // before any new outgoing arguments are stored to the stack, because the
3864 // outgoing stack slots may alias the incoming argument stack slots, and
3865 // the alias isn't otherwise explicit. This is slightly more conservative
3866 // than necessary, because it means that each store effectively depends
3867 // on every argument instead of just those arguments it would clobber.
3868 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3869
3870 SmallVector<SDValue, 8> MemOpChains2;
3871 SDValue FIN;
3872 int FI = 0;
3873 for (unsigned I = 0, OutsIndex = 0, E = ArgLocs.size(); I != E;
3874 ++I, ++OutsIndex) {
3875 CCValAssign &VA = ArgLocs[I];
3876
3877 if (VA.isRegLoc()) {
3878 if (VA.needsCustom()) {
3879 assert((CallConv == CallingConv::X86_RegCall) &&(((CallConv == CallingConv::X86_RegCall) && "Expecting custom case only in regcall calling convention"
) ? static_cast<void> (0) : __assert_fail ("(CallConv == CallingConv::X86_RegCall) && \"Expecting custom case only in regcall calling convention\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 3880, __PRETTY_FUNCTION__))
3880 "Expecting custom case only in regcall calling convention")(((CallConv == CallingConv::X86_RegCall) && "Expecting custom case only in regcall calling convention"
) ? static_cast<void> (0) : __assert_fail ("(CallConv == CallingConv::X86_RegCall) && \"Expecting custom case only in regcall calling convention\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 3880, __PRETTY_FUNCTION__))
;
3881 // This means that we are in special case where one argument was
3882 // passed through two register locations - Skip the next location
3883 ++I;
3884 }
3885
3886 continue;
3887 }
3888
3889 assert(VA.isMemLoc())((VA.isMemLoc()) ? static_cast<void> (0) : __assert_fail
("VA.isMemLoc()", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 3889, __PRETTY_FUNCTION__))
;
3890 SDValue Arg = OutVals[OutsIndex];
3891 ISD::ArgFlagsTy Flags = Outs[OutsIndex].Flags;
3892 // Skip inalloca arguments. They don't require any work.
3893 if (Flags.isInAlloca())
3894 continue;
3895 // Create frame index.
3896 int32_t Offset = VA.getLocMemOffset()+FPDiff;
3897 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3898 FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
3899 FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3900
3901 if (Flags.isByVal()) {
3902 // Copy relative to framepointer.
3903 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3904 if (!StackPtr.getNode())
3905 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3906 getPointerTy(DAG.getDataLayout()));
3907 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3908 StackPtr, Source);
3909
3910 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3911 ArgChain,
3912 Flags, DAG, dl));
3913 } else {
3914 // Store relative to framepointer.
3915 MemOpChains2.push_back(DAG.getStore(
3916 ArgChain, dl, Arg, FIN,
3917 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
3918 }
3919 }
3920
3921 if (!MemOpChains2.empty())
3922 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3923
3924 // Store the return address to the appropriate stack slot.
3925 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3926 getPointerTy(DAG.getDataLayout()),
3927 RegInfo->getSlotSize(), FPDiff, dl);
3928 }
3929
3930 // Build a sequence of copy-to-reg nodes chained together with token chain
3931 // and flag operands which copy the outgoing args into registers.
3932 SDValue InFlag;
3933 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3934 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3935 RegsToPass[i].second, InFlag);
3936 InFlag = Chain.getValue(1);
3937 }
3938
3939 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3940 assert(Is64Bit && "Large code model is only legal in 64-bit mode.")((Is64Bit && "Large code model is only legal in 64-bit mode."
) ? static_cast<void> (0) : __assert_fail ("Is64Bit && \"Large code model is only legal in 64-bit mode.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 3940, __PRETTY_FUNCTION__))
;
3941 // In the 64-bit large code model, we have to make all calls
3942 // through a register, since the call instruction's 32-bit
3943 // pc-relative offset may not be large enough to hold the whole
3944 // address.
3945 } else if (Callee->getOpcode() == ISD::GlobalAddress ||
3946 Callee->getOpcode() == ISD::ExternalSymbol) {
3947 // Lower direct calls to global addresses and external symbols. Setting
3948 // ForCall to true here has the effect of removing WrapperRIP when possible
3949 // to allow direct calls to be selected without first materializing the
3950 // address into a register.
3951 Callee = LowerGlobalOrExternal(Callee, DAG, /*ForCall=*/true);
3952 } else if (Subtarget.isTarget64BitILP32() &&
3953 Callee->getValueType(0) == MVT::i32) {
3954 // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3955 Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3956 }
3957
3958 // Returns a chain & a flag for retval copy to use.
3959 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3960 SmallVector<SDValue, 8> Ops;
3961
3962 if (!IsSibcall && isTailCall) {
3963 Chain = DAG.getCALLSEQ_END(Chain,
3964 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3965 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3966 InFlag = Chain.getValue(1);
3967 }
3968
3969 Ops.push_back(Chain);
3970 Ops.push_back(Callee);
3971
3972 if (isTailCall)
3973 Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3974
3975 // Add argument registers to the end of the list so that they are known live
3976 // into the call.
3977 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3978 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3979 RegsToPass[i].second.getValueType()));
3980
3981 // Add a register mask operand representing the call-preserved registers.
3982 // If HasNCSR is asserted (attribute NoCallerSavedRegisters exists) then we
3983 // set X86_INTR calling convention because it has the same CSR mask
3984 // (same preserved registers).
3985 const uint32_t *Mask = RegInfo->getCallPreservedMask(
3986 MF, HasNCSR ? (CallingConv::ID)CallingConv::X86_INTR : CallConv);
3987 assert(Mask && "Missing call preserved mask for calling convention")((Mask && "Missing call preserved mask for calling convention"
) ? static_cast<void> (0) : __assert_fail ("Mask && \"Missing call preserved mask for calling convention\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 3987, __PRETTY_FUNCTION__))
;
3988
3989 // If this is an invoke in a 32-bit function using a funclet-based
3990 // personality, assume the function clobbers all registers. If an exception
3991 // is thrown, the runtime will not restore CSRs.
3992 // FIXME: Model this more precisely so that we can register allocate across
3993 // the normal edge and spill and fill across the exceptional edge.
3994 if (!Is64Bit && CLI.CS && CLI.CS.isInvoke()) {
3995 const Function &CallerFn = MF.getFunction();
3996 EHPersonality Pers =
3997 CallerFn.hasPersonalityFn()
3998 ? classifyEHPersonality(CallerFn.getPersonalityFn())
3999 : EHPersonality::Unknown;
4000 if (isFuncletEHPersonality(Pers))
4001 Mask = RegInfo->getNoPreservedMask();
4002 }
4003
4004 // Define a new register mask from the existing mask.
4005 uint32_t *RegMask = nullptr;
4006
4007 // In some calling conventions we need to remove the used physical registers
4008 // from the reg mask.
4009 if (CallConv == CallingConv::X86_RegCall || HasNCSR) {
4010 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
4011
4012 // Allocate a new Reg Mask and copy Mask.
4013 RegMask = MF.allocateRegMask();
4014 unsigned RegMaskSize = MachineOperand::getRegMaskSize(TRI->getNumRegs());
4015 memcpy(RegMask, Mask, sizeof(RegMask[0]) * RegMaskSize);
4016
4017 // Make sure all sub registers of the argument registers are reset
4018 // in the RegMask.
4019 for (auto const &RegPair : RegsToPass)
4020 for (MCSubRegIterator SubRegs(RegPair.first, TRI, /*IncludeSelf=*/true);
4021 SubRegs.isValid(); ++SubRegs)
4022 RegMask[*SubRegs / 32] &= ~(1u << (*SubRegs % 32));
4023
4024 // Create the RegMask Operand according to our updated mask.
4025 Ops.push_back(DAG.getRegisterMask(RegMask));
4026 } else {
4027 // Create the RegMask Operand according to the static mask.
4028 Ops.push_back(DAG.getRegisterMask(Mask));
4029 }
4030
4031 if (InFlag.getNode())
4032 Ops.push_back(InFlag);
4033
4034 if (isTailCall) {
4035 // We used to do:
4036 //// If this is the first return lowered for this function, add the regs
4037 //// to the liveout set for the function.
4038 // This isn't right, although it's probably harmless on x86; liveouts
4039 // should be computed from returns not tail calls. Consider a void
4040 // function making a tail call to a function returning int.
4041 MF.getFrameInfo().setHasTailCall();
4042 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
4043 }
4044
4045 if (HasNoCfCheck && IsCFProtectionSupported) {
4046 Chain = DAG.getNode(X86ISD::NT_CALL, dl, NodeTys, Ops);
4047 } else {
4048 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
4049 }
4050 InFlag = Chain.getValue(1);
4051
4052 // Create the CALLSEQ_END node.
4053 unsigned NumBytesForCalleeToPop;
4054 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
4055 DAG.getTarget().Options.GuaranteedTailCallOpt))
4056 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
4057 else if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
4058 !Subtarget.getTargetTriple().isOSMSVCRT() &&
4059 SR == StackStructReturn)
4060 // If this is a call to a struct-return function, the callee
4061 // pops the hidden struct pointer, so we have to push it back.
4062 // This is common for Darwin/X86, Linux & Mingw32 targets.
4063 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
4064 NumBytesForCalleeToPop = 4;
4065 else
4066 NumBytesForCalleeToPop = 0; // Callee pops nothing.
4067
4068 if (CLI.DoesNotReturn && !getTargetMachine().Options.TrapUnreachable) {
4069 // No need to reset the stack after the call if the call doesn't return. To
4070 // make the MI verify, we'll pretend the callee does it for us.
4071 NumBytesForCalleeToPop = NumBytes;
4072 }
4073
4074 // Returns a flag for retval copy to use.
4075 if (!IsSibcall) {
4076 Chain = DAG.getCALLSEQ_END(Chain,
4077 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
4078 DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
4079 true),
4080 InFlag, dl);
4081 InFlag = Chain.getValue(1);
4082 }
4083
4084 // Handle result values, copying them out of physregs into vregs that we
4085 // return.
4086 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
4087 InVals, RegMask);
4088}
4089
4090//===----------------------------------------------------------------------===//
4091// Fast Calling Convention (tail call) implementation
4092//===----------------------------------------------------------------------===//
4093
4094// Like std call, callee cleans arguments, convention except that ECX is
4095// reserved for storing the tail called function address. Only 2 registers are
4096// free for argument passing (inreg). Tail call optimization is performed
4097// provided:
4098// * tailcallopt is enabled
4099// * caller/callee are fastcc
4100// On X86_64 architecture with GOT-style position independent code only local
4101// (within module) calls are supported at the moment.
4102// To keep the stack aligned according to platform abi the function
4103// GetAlignedArgumentStackSize ensures that argument delta is always multiples
4104// of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
4105// If a tail called function callee has more arguments than the caller the
4106// caller needs to make sure that there is room to move the RETADDR to. This is
4107// achieved by reserving an area the size of the argument delta right after the
4108// original RETADDR, but before the saved framepointer or the spilled registers
4109// e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
4110// stack layout:
4111// arg1
4112// arg2
4113// RETADDR
4114// [ new RETADDR
4115// move area ]
4116// (possible EBP)
4117// ESI
4118// EDI
4119// local1 ..
4120
4121/// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
4122/// requirement.
4123unsigned
4124X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
4125 SelectionDAG& DAG) const {
4126 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
4127 const TargetFrameLowering &TFI = *Subtarget.getFrameLowering();
4128 unsigned StackAlignment = TFI.getStackAlignment();
4129 uint64_t AlignMask = StackAlignment - 1;
4130 int64_t Offset = StackSize;
4131 unsigned SlotSize = RegInfo->getSlotSize();
4132 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
4133 // Number smaller than 12 so just add the difference.
4134 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
4135 } else {
4136 // Mask out lower bits, add stackalignment once plus the 12 bytes.
4137 Offset = ((~AlignMask) & Offset) + StackAlignment +
4138 (StackAlignment-SlotSize);
4139 }
4140 return Offset;
4141}
4142
4143/// Return true if the given stack call argument is already available in the
4144/// same position (relatively) of the caller's incoming argument stack.
4145static
4146bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
4147 MachineFrameInfo &MFI, const MachineRegisterInfo *MRI,
4148 const X86InstrInfo *TII, const CCValAssign &VA) {
4149 unsigned Bytes = Arg.getValueSizeInBits() / 8;
4150
4151 for (;;) {
4152 // Look through nodes that don't alter the bits of the incoming value.
4153 unsigned Op = Arg.getOpcode();
4154 if (Op == ISD::ZERO_EXTEND || Op == ISD::ANY_EXTEND || Op == ISD::BITCAST) {
4155 Arg = Arg.getOperand(0);
4156 continue;
4157 }
4158 if (Op == ISD::TRUNCATE) {
4159 const SDValue &TruncInput = Arg.getOperand(0);
4160 if (TruncInput.getOpcode() == ISD::AssertZext &&
4161 cast<VTSDNode>(TruncInput.getOperand(1))->getVT() ==
4162 Arg.getValueType()) {
4163 Arg = TruncInput.getOperand(0);
4164 continue;
4165 }
4166 }
4167 break;
4168 }
4169
4170 int FI = INT_MAX2147483647;
4171 if (Arg.getOpcode() == ISD::CopyFromReg) {
4172 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
4173 if (!TargetRegisterInfo::isVirtualRegister(VR))
4174 return false;
4175 MachineInstr *Def = MRI->getVRegDef(VR);
4176 if (!Def)
4177 return false;
4178 if (!Flags.isByVal()) {
4179 if (!TII->isLoadFromStackSlot(*Def, FI))
4180 return false;
4181 } else {
4182 unsigned Opcode = Def->getOpcode();
4183 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
4184 Opcode == X86::LEA64_32r) &&
4185 Def->getOperand(1).isFI()) {
4186 FI = Def->getOperand(1).getIndex();
4187 Bytes = Flags.getByValSize();
4188 } else
4189 return false;
4190 }
4191 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
4192 if (Flags.isByVal())
4193 // ByVal argument is passed in as a pointer but it's now being
4194 // dereferenced. e.g.
4195 // define @foo(%struct.X* %A) {
4196 // tail call @bar(%struct.X* byval %A)
4197 // }
4198 return false;
4199 SDValue Ptr = Ld->getBasePtr();
4200 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
4201 if (!FINode)
4202 return false;
4203 FI = FINode->getIndex();
4204 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
4205 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
4206 FI = FINode->getIndex();
4207 Bytes = Flags.getByValSize();
4208 } else
4209 return false;
4210
4211 assert(FI != INT_MAX)((FI != 2147483647) ? static_cast<void> (0) : __assert_fail
("FI != INT_MAX", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 4211, __PRETTY_FUNCTION__))
;
4212 if (!MFI.isFixedObjectIndex(FI))
4213 return false;
4214
4215 if (Offset != MFI.getObjectOffset(FI))
4216 return false;
4217
4218 // If this is not byval, check that the argument stack object is immutable.
4219 // inalloca and argument copy elision can create mutable argument stack
4220 // objects. Byval objects can be mutated, but a byval call intends to pass the
4221 // mutated memory.
4222 if (!Flags.isByVal() && !MFI.isImmutableObjectIndex(FI))
4223 return false;
4224
4225 if (VA.getLocVT().getSizeInBits() > Arg.getValueSizeInBits()) {
4226 // If the argument location is wider than the argument type, check that any
4227 // extension flags match.
4228 if (Flags.isZExt() != MFI.isObjectZExt(FI) ||
4229 Flags.isSExt() != MFI.isObjectSExt(FI)) {
4230 return false;
4231 }
4232 }
4233
4234 return Bytes == MFI.getObjectSize(FI);
4235}
4236
4237/// Check whether the call is eligible for tail call optimization. Targets
4238/// that want to do tail call optimization should implement this function.
4239bool X86TargetLowering::IsEligibleForTailCallOptimization(
4240 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
4241 bool isCalleeStructRet, bool isCallerStructRet, Type *RetTy,
4242 const SmallVectorImpl<ISD::OutputArg> &Outs,
4243 const SmallVectorImpl<SDValue> &OutVals,
4244 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
4245 if (!mayTailCallThisCC(CalleeCC))
4246 return false;
4247
4248 // If -tailcallopt is specified, make fastcc functions tail-callable.
4249 MachineFunction &MF = DAG.getMachineFunction();
4250 const Function &CallerF = MF.getFunction();
4251
4252 // If the function return type is x86_fp80 and the callee return type is not,
4253 // then the FP_EXTEND of the call result is not a nop. It's not safe to
4254 // perform a tailcall optimization here.
4255 if (CallerF.getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
4256 return false;
4257
4258 CallingConv::ID CallerCC = CallerF.getCallingConv();
4259 bool CCMatch = CallerCC == CalleeCC;
4260 bool IsCalleeWin64 = Subtarget.isCallingConvWin64(CalleeCC);
4261 bool IsCallerWin64 = Subtarget.isCallingConvWin64(CallerCC);
4262
4263 // Win64 functions have extra shadow space for argument homing. Don't do the
4264 // sibcall if the caller and callee have mismatched expectations for this
4265 // space.
4266 if (IsCalleeWin64 != IsCallerWin64)
4267 return false;
4268
4269 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
4270 if (canGuaranteeTCO(CalleeCC) && CCMatch)
4271 return true;
4272 return false;
4273 }
4274
4275 // Look for obvious safe cases to perform tail call optimization that do not
4276 // require ABI changes. This is what gcc calls sibcall.
4277
4278 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
4279 // emit a special epilogue.
4280 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
4281 if (RegInfo->needsStackRealignment(MF))
4282 return false;
4283
4284 // Also avoid sibcall optimization if either caller or callee uses struct
4285 // return semantics.
4286 if (isCalleeStructRet || isCallerStructRet)
4287 return false;
4288
4289 // Do not sibcall optimize vararg calls unless all arguments are passed via
4290 // registers.
4291 LLVMContext &C = *DAG.getContext();
4292 if (isVarArg && !Outs.empty()) {
4293 // Optimizing for varargs on Win64 is unlikely to be safe without
4294 // additional testing.
4295 if (IsCalleeWin64 || IsCallerWin64)
4296 return false;
4297
4298 SmallVector<CCValAssign, 16> ArgLocs;
4299 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
4300
4301 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
4302 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
4303 if (!ArgLocs[i].isRegLoc())
4304 return false;
4305 }
4306
4307 // If the call result is in ST0 / ST1, it needs to be popped off the x87
4308 // stack. Therefore, if it's not used by the call it is not safe to optimize
4309 // this into a sibcall.
4310 bool Unused = false;
4311 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
4312 if (!Ins[i].Used) {
4313 Unused = true;
4314 break;
4315 }
4316 }
4317 if (Unused) {
4318 SmallVector<CCValAssign, 16> RVLocs;
4319 CCState CCInfo(CalleeCC, false, MF, RVLocs, C);
4320 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
4321 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4322 CCValAssign &VA = RVLocs[i];
4323 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
4324 return false;
4325 }
4326 }
4327
4328 // Check that the call results are passed in the same way.
4329 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
4330 RetCC_X86, RetCC_X86))
4331 return false;
4332 // The callee has to preserve all registers the caller needs to preserve.
4333 const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
4334 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
4335 if (!CCMatch) {
4336 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
4337 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
4338 return false;
4339 }
4340
4341 unsigned StackArgsSize = 0;
4342
4343 // If the callee takes no arguments then go on to check the results of the
4344 // call.
4345 if (!Outs.empty()) {
4346 // Check if stack adjustment is needed. For now, do not do this if any
4347 // argument is passed on the stack.
4348 SmallVector<CCValAssign, 16> ArgLocs;
4349 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
4350
4351 // Allocate shadow area for Win64
4352 if (IsCalleeWin64)
4353 CCInfo.AllocateStack(32, 8);
4354
4355 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
4356 StackArgsSize = CCInfo.getNextStackOffset();
4357
4358 if (CCInfo.getNextStackOffset()) {
4359 // Check if the arguments are already laid out in the right way as
4360 // the caller's fixed stack objects.
4361 MachineFrameInfo &MFI = MF.getFrameInfo();
4362 const MachineRegisterInfo *MRI = &MF.getRegInfo();
4363 const X86InstrInfo *TII = Subtarget.getInstrInfo();
4364 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4365 CCValAssign &VA = ArgLocs[i];
4366 SDValue Arg = OutVals[i];
4367 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4368 if (VA.getLocInfo() == CCValAssign::Indirect)
4369 return false;
4370 if (!VA.isRegLoc()) {
4371 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
4372 MFI, MRI, TII, VA))
4373 return false;
4374 }
4375 }
4376 }
4377
4378 bool PositionIndependent = isPositionIndependent();
4379 // If the tailcall address may be in a register, then make sure it's
4380 // possible to register allocate for it. In 32-bit, the call address can
4381 // only target EAX, EDX, or ECX since the tail call must be scheduled after
4382 // callee-saved registers are restored. These happen to be the same
4383 // registers used to pass 'inreg' arguments so watch out for those.
4384 if (!Subtarget.is64Bit() && ((!isa<GlobalAddressSDNode>(Callee) &&
4385 !isa<ExternalSymbolSDNode>(Callee)) ||
4386 PositionIndependent)) {
4387 unsigned NumInRegs = 0;
4388 // In PIC we need an extra register to formulate the address computation
4389 // for the callee.
4390 unsigned MaxInRegs = PositionIndependent ? 2 : 3;
4391
4392 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4393 CCValAssign &VA = ArgLocs[i];
4394 if (!VA.isRegLoc())
4395 continue;
4396 unsigned Reg = VA.getLocReg();
4397 switch (Reg) {
4398 default: break;
4399 case X86::EAX: case X86::EDX: case X86::ECX:
4400 if (++NumInRegs == MaxInRegs)
4401 return false;
4402 break;
4403 }
4404 }
4405 }
4406
4407 const MachineRegisterInfo &MRI = MF.getRegInfo();
4408 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
4409 return false;
4410 }
4411
4412 bool CalleeWillPop =
4413 X86::isCalleePop(CalleeCC, Subtarget.is64Bit(), isVarArg,
4414 MF.getTarget().Options.GuaranteedTailCallOpt);
4415
4416 if (unsigned BytesToPop =
4417 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn()) {
4418 // If we have bytes to pop, the callee must pop them.
4419 bool CalleePopMatches = CalleeWillPop && BytesToPop == StackArgsSize;
4420 if (!CalleePopMatches)
4421 return false;
4422 } else if (CalleeWillPop && StackArgsSize > 0) {
4423 // If we don't have bytes to pop, make sure the callee doesn't pop any.
4424 return false;
4425 }
4426
4427 return true;
4428}
4429
4430FastISel *
4431X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
4432 const TargetLibraryInfo *libInfo) const {
4433 return X86::createFastISel(funcInfo, libInfo);
4434}
4435
4436//===----------------------------------------------------------------------===//
4437// Other Lowering Hooks
4438//===----------------------------------------------------------------------===//
4439
4440static bool MayFoldLoad(SDValue Op) {
4441 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
4442}
4443
4444static bool MayFoldIntoStore(SDValue Op) {
4445 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
4446}
4447
4448static bool MayFoldIntoZeroExtend(SDValue Op) {
4449 if (Op.hasOneUse()) {
4450 unsigned Opcode = Op.getNode()->use_begin()->getOpcode();
4451 return (ISD::ZERO_EXTEND == Opcode);
4452 }
4453 return false;
4454}
4455
4456static bool isTargetShuffle(unsigned Opcode) {
4457 switch(Opcode) {
4458 default: return false;
4459 case X86ISD::BLENDI:
4460 case X86ISD::PSHUFB:
4461 case X86ISD::PSHUFD:
4462 case X86ISD::PSHUFHW:
4463 case X86ISD::PSHUFLW:
4464 case X86ISD::SHUFP:
4465 case X86ISD::INSERTPS:
4466 case X86ISD::EXTRQI:
4467 case X86ISD::INSERTQI:
4468 case X86ISD::PALIGNR:
4469 case X86ISD::VSHLDQ:
4470 case X86ISD::VSRLDQ:
4471 case X86ISD::MOVLHPS:
4472 case X86ISD::MOVHLPS:
4473 case X86ISD::MOVSHDUP:
4474 case X86ISD::MOVSLDUP:
4475 case X86ISD::MOVDDUP:
4476 case X86ISD::MOVSS:
4477 case X86ISD::MOVSD:
4478 case X86ISD::UNPCKL:
4479 case X86ISD::UNPCKH:
4480 case X86ISD::VBROADCAST:
4481 case X86ISD::VPERMILPI:
4482 case X86ISD::VPERMILPV:
4483 case X86ISD::VPERM2X128:
4484 case X86ISD::SHUF128:
4485 case X86ISD::VPERMIL2:
4486 case X86ISD::VPERMI:
4487 case X86ISD::VPPERM:
4488 case X86ISD::VPERMV:
4489 case X86ISD::VPERMV3:
4490 case X86ISD::VZEXT_MOVL:
4491 return true;
4492 }
4493}
4494
4495static bool isTargetShuffleVariableMask(unsigned Opcode) {
4496 switch (Opcode) {
4497 default: return false;
4498 // Target Shuffles.
4499 case X86ISD::PSHUFB:
4500 case X86ISD::VPERMILPV:
4501 case X86ISD::VPERMIL2:
4502 case X86ISD::VPPERM:
4503 case X86ISD::VPERMV:
4504 case X86ISD::VPERMV3:
4505 return true;
4506 // 'Faux' Target Shuffles.
4507 case ISD::OR:
4508 case ISD::AND:
4509 case X86ISD::ANDNP:
4510 return true;
4511 }
4512}
4513
4514SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
4515 MachineFunction &MF = DAG.getMachineFunction();
4516 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
4517 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
4518 int ReturnAddrIndex = FuncInfo->getRAIndex();
4519
4520 if (ReturnAddrIndex == 0) {
4521 // Set up a frame object for the return address.
4522 unsigned SlotSize = RegInfo->getSlotSize();
4523 ReturnAddrIndex = MF.getFrameInfo().CreateFixedObject(SlotSize,
4524 -(int64_t)SlotSize,
4525 false);
4526 FuncInfo->setRAIndex(ReturnAddrIndex);
4527 }
4528
4529 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
4530}
4531
4532bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
4533 bool hasSymbolicDisplacement) {
4534 // Offset should fit into 32 bit immediate field.
4535 if (!isInt<32>(Offset))
4536 return false;
4537
4538 // If we don't have a symbolic displacement - we don't have any extra
4539 // restrictions.
4540 if (!hasSymbolicDisplacement)
4541 return true;
4542
4543 // FIXME: Some tweaks might be needed for medium code model.
4544 if (M != CodeModel::Small && M != CodeModel::Kernel)
4545 return false;
4546
4547 // For small code model we assume that latest object is 16MB before end of 31
4548 // bits boundary. We may also accept pretty large negative constants knowing
4549 // that all objects are in the positive half of address space.
4550 if (M == CodeModel::Small && Offset < 16*1024*1024)
4551 return true;
4552
4553 // For kernel code model we know that all object resist in the negative half
4554 // of 32bits address space. We may not accept negative offsets, since they may
4555 // be just off and we may accept pretty large positive ones.
4556 if (M == CodeModel::Kernel && Offset >= 0)
4557 return true;
4558
4559 return false;
4560}
4561
4562/// Determines whether the callee is required to pop its own arguments.
4563/// Callee pop is necessary to support tail calls.
4564bool X86::isCalleePop(CallingConv::ID CallingConv,
4565 bool is64Bit, bool IsVarArg, bool GuaranteeTCO) {
4566 // If GuaranteeTCO is true, we force some calls to be callee pop so that we
4567 // can guarantee TCO.
4568 if (!IsVarArg && shouldGuaranteeTCO(CallingConv, GuaranteeTCO))
4569 return true;
4570
4571 switch (CallingConv) {
4572 default:
4573 return false;
4574 case CallingConv::X86_StdCall:
4575 case CallingConv::X86_FastCall:
4576 case CallingConv::X86_ThisCall:
4577 case CallingConv::X86_VectorCall:
4578 return !is64Bit;
4579 }
4580}
4581
4582/// Return true if the condition is an unsigned comparison operation.
4583static bool isX86CCUnsigned(unsigned X86CC) {
4584 switch (X86CC) {
4585 default:
4586 llvm_unreachable("Invalid integer condition!")::llvm::llvm_unreachable_internal("Invalid integer condition!"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 4586)
;
4587 case X86::COND_E:
4588 case X86::COND_NE:
4589 case X86::COND_B:
4590 case X86::COND_A:
4591 case X86::COND_BE:
4592 case X86::COND_AE:
4593 return true;
4594 case X86::COND_G:
4595 case X86::COND_GE:
4596 case X86::COND_L:
4597 case X86::COND_LE:
4598 return false;
4599 }
4600}
4601
4602static X86::CondCode TranslateIntegerX86CC(ISD::CondCode SetCCOpcode) {
4603 switch (SetCCOpcode) {
4604 default: llvm_unreachable("Invalid integer condition!")::llvm::llvm_unreachable_internal("Invalid integer condition!"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 4604)
;
4605 case ISD::SETEQ: return X86::COND_E;
4606 case ISD::SETGT: return X86::COND_G;
4607 case ISD::SETGE: return X86::COND_GE;
4608 case ISD::SETLT: return X86::COND_L;
4609 case ISD::SETLE: return X86::COND_LE;
4610 case ISD::SETNE: return X86::COND_NE;
4611 case ISD::SETULT: return X86::COND_B;
4612 case ISD::SETUGT: return X86::COND_A;
4613 case ISD::SETULE: return X86::COND_BE;
4614 case ISD::SETUGE: return X86::COND_AE;
4615 }
4616}
4617
4618/// Do a one-to-one translation of a ISD::CondCode to the X86-specific
4619/// condition code, returning the condition code and the LHS/RHS of the
4620/// comparison to make.
4621static X86::CondCode TranslateX86CC(ISD::CondCode SetCCOpcode, const SDLoc &DL,
4622 bool isFP, SDValue &LHS, SDValue &RHS,
4623 SelectionDAG &DAG) {
4624 if (!isFP) {
4625 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4626 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
4627 // X > -1 -> X == 0, jump !sign.
4628 RHS = DAG.getConstant(0, DL, RHS.getValueType());
4629 return X86::COND_NS;
4630 }
4631 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
4632 // X < 0 -> X == 0, jump on sign.
4633 return X86::COND_S;
4634 }
4635 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
4636 // X < 1 -> X <= 0
4637 RHS = DAG.getConstant(0, DL, RHS.getValueType());
4638 return X86::COND_LE;
4639 }
4640 }
4641
4642 return TranslateIntegerX86CC(SetCCOpcode);
4643 }
4644
4645 // First determine if it is required or is profitable to flip the operands.
4646
4647 // If LHS is a foldable load, but RHS is not, flip the condition.
4648 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
4649 !ISD::isNON_EXTLoad(RHS.getNode())) {
4650 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
4651 std::swap(LHS, RHS);
4652 }
4653
4654 switch (SetCCOpcode) {
4655 default: break;
4656 case ISD::SETOLT:
4657 case ISD::SETOLE:
4658 case ISD::SETUGT:
4659 case ISD::SETUGE:
4660 std::swap(LHS, RHS);
4661 break;
4662 }
4663
4664 // On a floating point condition, the flags are set as follows:
4665 // ZF PF CF op
4666 // 0 | 0 | 0 | X > Y
4667 // 0 | 0 | 1 | X < Y
4668 // 1 | 0 | 0 | X == Y
4669 // 1 | 1 | 1 | unordered
4670 switch (SetCCOpcode) {
4671 default: llvm_unreachable("Condcode should be pre-legalized away")::llvm::llvm_unreachable_internal("Condcode should be pre-legalized away"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 4671)
;
4672 case ISD::SETUEQ:
4673 case ISD::SETEQ: return X86::COND_E;
4674 case ISD::SETOLT: // flipped
4675 case ISD::SETOGT:
4676 case ISD::SETGT: return X86::COND_A;
4677 case ISD::SETOLE: // flipped
4678 case ISD::SETOGE:
4679 case ISD::SETGE: return X86::COND_AE;
4680 case ISD::SETUGT: // flipped
4681 case ISD::SETULT:
4682 case ISD::SETLT: return X86::COND_B;
4683 case ISD::SETUGE: // flipped
4684 case ISD::SETULE:
4685 case ISD::SETLE: return X86::COND_BE;
4686 case ISD::SETONE:
4687 case ISD::SETNE: return X86::COND_NE;
4688 case ISD::SETUO: return X86::COND_P;
4689 case ISD::SETO: return X86::COND_NP;
4690 case ISD::SETOEQ:
4691 case ISD::SETUNE: return X86::COND_INVALID;
4692 }
4693}
4694
4695/// Is there a floating point cmov for the specific X86 condition code?
4696/// Current x86 isa includes the following FP cmov instructions:
4697/// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
4698static bool hasFPCMov(unsigned X86CC) {
4699 switch (X86CC) {
4700 default:
4701 return false;
4702 case X86::COND_B:
4703 case X86::COND_BE:
4704 case X86::COND_E:
4705 case X86::COND_P:
4706 case X86::COND_A:
4707 case X86::COND_AE:
4708 case X86::COND_NE:
4709 case X86::COND_NP:
4710 return true;
4711 }
4712}
4713
4714
4715bool X86TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
4716 const CallInst &I,
4717 MachineFunction &MF,
4718 unsigned Intrinsic) const {
4719
4720 const IntrinsicData* IntrData = getIntrinsicWithChain(Intrinsic);
4721 if (!IntrData)
4722 return false;
4723
4724 Info.flags = MachineMemOperand::MONone;
4725 Info.offset = 0;
4726
4727 switch (IntrData->Type) {
4728 case TRUNCATE_TO_MEM_VI8:
4729 case TRUNCATE_TO_MEM_VI16:
4730 case TRUNCATE_TO_MEM_VI32: {
4731 Info.opc = ISD::INTRINSIC_VOID;
4732 Info.ptrVal = I.getArgOperand(0);
4733 MVT VT = MVT::getVT(I.getArgOperand(1)->getType());
4734 MVT ScalarVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
4735 if (IntrData->Type == TRUNCATE_TO_MEM_VI8)
4736 ScalarVT = MVT::i8;
4737 else if (IntrData->Type == TRUNCATE_TO_MEM_VI16)
4738 ScalarVT = MVT::i16;
4739 else if (IntrData->Type == TRUNCATE_TO_MEM_VI32)
4740 ScalarVT = MVT::i32;
4741
4742 Info.memVT = MVT::getVectorVT(ScalarVT, VT.getVectorNumElements());
4743 Info.align = 1;
4744 Info.flags |= MachineMemOperand::MOStore;
4745 break;
4746 }
4747 case GATHER:
4748 case GATHER_AVX2: {
4749 Info.opc = ISD::INTRINSIC_W_CHAIN;
4750 Info.ptrVal = nullptr;
4751 MVT DataVT = MVT::getVT(I.getType());
4752 MVT IndexVT = MVT::getVT(I.getArgOperand(2)->getType());
4753 unsigned NumElts = std::min(DataVT.getVectorNumElements(),
4754 IndexVT.getVectorNumElements());
4755 Info.memVT = MVT::getVectorVT(DataVT.getVectorElementType(), NumElts);
4756 Info.align = 1;
4757 Info.flags |= MachineMemOperand::MOLoad;
4758 break;
4759 }
4760 case SCATTER: {
4761 Info.opc = ISD::INTRINSIC_VOID;
4762 Info.ptrVal = nullptr;
4763 MVT DataVT = MVT::getVT(I.getArgOperand(3)->getType());
4764 MVT IndexVT = MVT::getVT(I.getArgOperand(2)->getType());
4765 unsigned NumElts = std::min(DataVT.getVectorNumElements(),
4766 IndexVT.getVectorNumElements());
4767 Info.memVT = MVT::getVectorVT(DataVT.getVectorElementType(), NumElts);
4768 Info.align = 1;
4769 Info.flags |= MachineMemOperand::MOStore;
4770 break;
4771 }
4772 default:
4773 return false;
4774 }
4775
4776 return true;
4777}
4778
4779/// Returns true if the target can instruction select the
4780/// specified FP immediate natively. If false, the legalizer will
4781/// materialize the FP immediate as a load from a constant pool.
4782bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
4783 bool ForCodeSize) const {
4784 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
4785 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
4786 return true;
4787 }
4788 return false;
4789}
4790
4791bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
4792 ISD::LoadExtType ExtTy,
4793 EVT NewVT) const {
4794 // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
4795 // relocation target a movq or addq instruction: don't let the load shrink.
4796 SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
4797 if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
4798 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
4799 return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
4800 return true;
4801}
4802
4803/// Returns true if it is beneficial to convert a load of a constant
4804/// to just the constant itself.
4805bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
4806 Type *Ty) const {
4807 assert(Ty->isIntegerTy())((Ty->isIntegerTy()) ? static_cast<void> (0) : __assert_fail
("Ty->isIntegerTy()", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 4807, __PRETTY_FUNCTION__))
;
4808
4809 unsigned BitSize = Ty->getPrimitiveSizeInBits();
4810 if (BitSize == 0 || BitSize > 64)
4811 return false;
4812 return true;
4813}
4814
4815bool X86TargetLowering::reduceSelectOfFPConstantLoads(bool IsFPSetCC) const {
4816 // If we are using XMM registers in the ABI and the condition of the select is
4817 // a floating-point compare and we have blendv or conditional move, then it is
4818 // cheaper to select instead of doing a cross-register move and creating a
4819 // load that depends on the compare result.
4820 return !IsFPSetCC || !Subtarget.isTarget64BitLP64() || !Subtarget.hasAVX();
4821}
4822
4823bool X86TargetLowering::convertSelectOfConstantsToMath(EVT VT) const {
4824 // TODO: It might be a win to ease or lift this restriction, but the generic
4825 // folds in DAGCombiner conflict with vector folds for an AVX512 target.
4826 if (VT.isVector() && Subtarget.hasAVX512())
4827 return false;
4828
4829 return true;
4830}
4831
4832bool X86TargetLowering::decomposeMulByConstant(EVT VT, SDValue C) const {
4833 // TODO: We handle scalars using custom code, but generic combining could make
4834 // that unnecessary.
4835 APInt MulC;
4836 if (!ISD::isConstantSplatVector(C.getNode(), MulC))
4837 return false;
4838
4839 // If vector multiply is legal, assume that's faster than shl + add/sub.
4840 // TODO: Multiply is a complex op with higher latency and lower througput in
4841 // most implementations, so this check could be loosened based on type
4842 // and/or a CPU attribute.
4843 if (isOperationLegal(ISD::MUL, VT))
4844 return false;
4845
4846 // shl+add, shl+sub, shl+add+neg
4847 return (MulC + 1).isPowerOf2() || (MulC - 1).isPowerOf2() ||
4848 (1 - MulC).isPowerOf2() || (-(MulC + 1)).isPowerOf2();
4849}
4850
4851bool X86TargetLowering::shouldUseStrictFP_TO_INT(EVT FpVT, EVT IntVT,
4852 bool IsSigned) const {
4853 // f80 UINT_TO_FP is more efficient using Strict code if FCMOV is available.
4854 return !IsSigned && FpVT == MVT::f80 && Subtarget.hasCMov();
4855}
4856
4857bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
4858 unsigned Index) const {
4859 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4860 return false;
4861
4862 // Mask vectors support all subregister combinations and operations that
4863 // extract half of vector.
4864 if (ResVT.getVectorElementType() == MVT::i1)
4865 return Index == 0 || ((ResVT.getSizeInBits() == SrcVT.getSizeInBits()*2) &&
4866 (Index == ResVT.getVectorNumElements()));
4867
4868 return (Index % ResVT.getVectorNumElements()) == 0;
4869}
4870
4871bool X86TargetLowering::shouldScalarizeBinop(SDValue VecOp) const {
4872 // If the vector op is not supported, try to convert to scalar.
4873 EVT VecVT = VecOp.getValueType();
4874 if (!isOperationLegalOrCustomOrPromote(VecOp.getOpcode(), VecVT))
4875 return true;
4876
4877 // If the vector op is supported, but the scalar op is not, the transform may
4878 // not be worthwhile.
4879 EVT ScalarVT = VecVT.getScalarType();
4880 return isOperationLegalOrCustomOrPromote(VecOp.getOpcode(), ScalarVT);
4881}
4882
4883bool X86TargetLowering::shouldFormOverflowOp(unsigned Opcode, EVT VT) const {
4884 // TODO: Allow vectors?
4885 if (VT.isVector())
4886 return false;
4887 return VT.isSimple() || !isOperationExpand(Opcode, VT);
4888}
4889
4890bool X86TargetLowering::isCheapToSpeculateCttz() const {
4891 // Speculate cttz only if we can directly use TZCNT.
4892 return Subtarget.hasBMI();
4893}
4894
4895bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4896 // Speculate ctlz only if we can directly use LZCNT.
4897 return Subtarget.hasLZCNT();
4898}
4899
4900bool X86TargetLowering::isLoadBitCastBeneficial(EVT LoadVT,
4901 EVT BitcastVT) const {
4902 if (!Subtarget.hasAVX512() && !LoadVT.isVector() && BitcastVT.isVector() &&
4903 BitcastVT.getVectorElementType() == MVT::i1)
4904 return false;
4905
4906 if (!Subtarget.hasDQI() && BitcastVT == MVT::v8i1 && LoadVT == MVT::i8)
4907 return false;
4908
4909 return TargetLowering::isLoadBitCastBeneficial(LoadVT, BitcastVT);
4910}
4911
4912bool X86TargetLowering::canMergeStoresTo(unsigned AddressSpace, EVT MemVT,
4913 const SelectionDAG &DAG) const {
4914 // Do not merge to float value size (128 bytes) if no implicit
4915 // float attribute is set.
4916 bool NoFloat = DAG.getMachineFunction().getFunction().hasFnAttribute(
4917 Attribute::NoImplicitFloat);
4918
4919 if (NoFloat) {
4920 unsigned MaxIntSize = Subtarget.is64Bit() ? 64 : 32;
4921 return (MemVT.getSizeInBits() <= MaxIntSize);
4922 }
4923 // Make sure we don't merge greater than our preferred vector
4924 // width.
4925 if (MemVT.getSizeInBits() > Subtarget.getPreferVectorWidth())
4926 return false;
4927 return true;
4928}
4929
4930bool X86TargetLowering::isCtlzFast() const {
4931 return Subtarget.hasFastLZCNT();
4932}
4933
4934bool X86TargetLowering::isMaskAndCmp0FoldingBeneficial(
4935 const Instruction &AndI) const {
4936 return true;
4937}
4938
4939bool X86TargetLowering::hasAndNotCompare(SDValue Y) const {
4940 EVT VT = Y.getValueType();
4941
4942 if (VT.isVector())
4943 return false;
4944
4945 if (!Subtarget.hasBMI())
4946 return false;
4947
4948 // There are only 32-bit and 64-bit forms for 'andn'.
4949 if (VT != MVT::i32 && VT != MVT::i64)
4950 return false;
4951
4952 return !isa<ConstantSDNode>(Y);
4953}
4954
4955bool X86TargetLowering::hasAndNot(SDValue Y) const {
4956 EVT VT = Y.getValueType();
4957
4958 if (!VT.isVector())
4959 return hasAndNotCompare(Y);
4960
4961 // Vector.
4962
4963 if (!Subtarget.hasSSE1() || VT.getSizeInBits() < 128)
4964 return false;
4965
4966 if (VT == MVT::v4i32)
4967 return true;
4968
4969 return Subtarget.hasSSE2();
4970}
4971
4972bool X86TargetLowering::shouldFoldConstantShiftPairToMask(
4973 const SDNode *N, CombineLevel Level) const {
4974 assert(((N->getOpcode() == ISD::SHL &&((((N->getOpcode() == ISD::SHL && N->getOperand
(0).getOpcode() == ISD::SRL) || (N->getOpcode() == ISD::SRL
&& N->getOperand(0).getOpcode() == ISD::SHL)) &&
"Expected shift-shift mask") ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 4978, __PRETTY_FUNCTION__))
4975 N->getOperand(0).getOpcode() == ISD::SRL) ||((((N->getOpcode() == ISD::SHL && N->getOperand
(0).getOpcode() == ISD::SRL) || (N->getOpcode() == ISD::SRL
&& N->getOperand(0).getOpcode() == ISD::SHL)) &&
"Expected shift-shift mask") ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 4978, __PRETTY_FUNCTION__))
4976 (N->getOpcode() == ISD::SRL &&((((N->getOpcode() == ISD::SHL && N->getOperand
(0).getOpcode() == ISD::SRL) || (N->getOpcode() == ISD::SRL
&& N->getOperand(0).getOpcode() == ISD::SHL)) &&
"Expected shift-shift mask") ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 4978, __PRETTY_FUNCTION__))
4977 N->getOperand(0).getOpcode() == ISD::SHL)) &&((((N->getOpcode() == ISD::SHL && N->getOperand
(0).getOpcode() == ISD::SRL) || (N->getOpcode() == ISD::SRL
&& N->getOperand(0).getOpcode() == ISD::SHL)) &&
"Expected shift-shift mask") ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 4978, __PRETTY_FUNCTION__))
4978 "Expected shift-shift mask")((((N->getOpcode() == ISD::SHL && N->getOperand
(0).getOpcode() == ISD::SRL) || (N->getOpcode() == ISD::SRL
&& N->getOperand(0).getOpcode() == ISD::SHL)) &&
"Expected shift-shift mask") ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 4978, __PRETTY_FUNCTION__))
;
4979 EVT VT = N->getValueType(0);
4980 if ((Subtarget.hasFastVectorShiftMasks() && VT.isVector()) ||
4981 (Subtarget.hasFastScalarShiftMasks() && !VT.isVector())) {
4982 // Only fold if the shift values are equal - so it folds to AND.
4983 // TODO - we should fold if either is a non-uniform vector but we don't do
4984 // the fold for non-splats yet.
4985 return N->getOperand(1) == N->getOperand(0).getOperand(1);
4986 }
4987 return TargetLoweringBase::shouldFoldConstantShiftPairToMask(N, Level);
4988}
4989
4990bool X86TargetLowering::shouldFoldMaskToVariableShiftPair(SDValue Y) const {
4991 EVT VT = Y.getValueType();
4992
4993 // For vectors, we don't have a preference, but we probably want a mask.
4994 if (VT.isVector())
4995 return false;
4996
4997 // 64-bit shifts on 32-bit targets produce really bad bloated code.
4998 if (VT == MVT::i64 && !Subtarget.is64Bit())
4999 return false;
5000
5001 return true;
5002}
5003
5004bool X86TargetLowering::shouldSplatInsEltVarIndex(EVT VT) const {
5005 // Any legal vector type can be splatted more efficiently than
5006 // loading/spilling from memory.
5007 return isTypeLegal(VT);
5008}
5009
5010MVT X86TargetLowering::hasFastEqualityCompare(unsigned NumBits) const {
5011 MVT VT = MVT::getIntegerVT(NumBits);
5012 if (isTypeLegal(VT))
5013 return VT;
5014
5015 // PMOVMSKB can handle this.
5016 if (NumBits == 128 && isTypeLegal(MVT::v16i8))
5017 return MVT::v16i8;
5018
5019 // VPMOVMSKB can handle this.
5020 if (NumBits == 256 && isTypeLegal(MVT::v32i8))
5021 return MVT::v32i8;
5022
5023 // TODO: Allow 64-bit type for 32-bit target.
5024 // TODO: 512-bit types should be allowed, but make sure that those
5025 // cases are handled in combineVectorSizedSetCCEquality().
5026
5027 return MVT::INVALID_SIMPLE_VALUE_TYPE;
5028}
5029
5030/// Val is the undef sentinel value or equal to the specified value.
5031static bool isUndefOrEqual(int Val, int CmpVal) {
5032 return ((Val == SM_SentinelUndef) || (Val == CmpVal));
5033}
5034
5035/// Val is either the undef or zero sentinel value.
5036static bool isUndefOrZero(int Val) {
5037 return ((Val == SM_SentinelUndef) || (Val == SM_SentinelZero));
5038}
5039
5040/// Return true if every element in Mask, beginning from position Pos and ending
5041/// in Pos+Size is the undef sentinel value.
5042static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
5043 for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
5044 if (Mask[i] != SM_SentinelUndef)
5045 return false;
5046 return true;
5047}
5048
5049/// Return true if the mask creates a vector whose lower half is undefined.
5050static bool isUndefLowerHalf(ArrayRef<int> Mask) {
5051 unsigned NumElts = Mask.size();
5052 return isUndefInRange(Mask, 0, NumElts / 2);
5053}
5054
5055/// Return true if the mask creates a vector whose upper half is undefined.
5056static bool isUndefUpperHalf(ArrayRef<int> Mask) {
5057 unsigned NumElts = Mask.size();
5058 return isUndefInRange(Mask, NumElts / 2, NumElts / 2);
5059}
5060
5061/// Return true if Val falls within the specified range (L, H].
5062static bool isInRange(int Val, int Low, int Hi) {
5063 return (Val >= Low && Val < Hi);
5064}
5065
5066/// Return true if the value of any element in Mask falls within the specified
5067/// range (L, H].
5068static bool isAnyInRange(ArrayRef<int> Mask, int Low, int Hi) {
5069 for (int M : Mask)
5070 if (isInRange(M, Low, Hi))
5071 return true;
5072 return false;
5073}
5074
5075/// Return true if Val is undef or if its value falls within the
5076/// specified range (L, H].
5077static bool isUndefOrInRange(int Val, int Low, int Hi) {
5078 return (Val == SM_SentinelUndef) || isInRange(Val, Low, Hi);
5079}
5080
5081/// Return true if every element in Mask is undef or if its value
5082/// falls within the specified range (L, H].
5083static bool isUndefOrInRange(ArrayRef<int> Mask,
5084 int Low, int Hi) {
5085 for (int M : Mask)
5086 if (!isUndefOrInRange(M, Low, Hi))
5087 return false;
5088 return true;
5089}
5090
5091/// Return true if Val is undef, zero or if its value falls within the
5092/// specified range (L, H].
5093static bool isUndefOrZeroOrInRange(int Val, int Low, int Hi) {
5094 return isUndefOrZero(Val) || isInRange(Val, Low, Hi);
5095}
5096
5097/// Return true if every element in Mask is undef, zero or if its value
5098/// falls within the specified range (L, H].
5099static bool isUndefOrZeroOrInRange(ArrayRef<int> Mask, int Low, int Hi) {
5100 for (int M : Mask)
5101 if (!isUndefOrZeroOrInRange(M, Low, Hi))
5102 return false;
5103 return true;
5104}
5105
5106/// Return true if every element in Mask, beginning
5107/// from position Pos and ending in Pos + Size, falls within the specified
5108/// sequence (Low, Low + Step, ..., Low + (Size - 1) * Step) or is undef.
5109static bool isSequentialOrUndefInRange(ArrayRef<int> Mask, unsigned Pos,
5110 unsigned Size, int Low, int Step = 1) {
5111 for (unsigned i = Pos, e = Pos + Size; i != e; ++i, Low += Step)
5112 if (!isUndefOrEqual(Mask[i], Low))
5113 return false;
5114 return true;
5115}
5116
5117/// Return true if every element in Mask, beginning
5118/// from position Pos and ending in Pos+Size, falls within the specified
5119/// sequential range (Low, Low+Size], or is undef or is zero.
5120static bool isSequentialOrUndefOrZeroInRange(ArrayRef<int> Mask, unsigned Pos,
5121 unsigned Size, int Low) {
5122 for (unsigned i = Pos, e = Pos + Size; i != e; ++i, ++Low)
5123 if (!isUndefOrZero(Mask[i]) && Mask[i] != Low)
5124 return false;
5125 return true;
5126}
5127
5128/// Return true if every element in Mask, beginning
5129/// from position Pos and ending in Pos+Size is undef or is zero.
5130static bool isUndefOrZeroInRange(ArrayRef<int> Mask, unsigned Pos,
5131 unsigned Size) {
5132 for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
5133 if (!isUndefOrZero(Mask[i]))
5134 return false;
5135 return true;
5136}
5137
5138/// Helper function to test whether a shuffle mask could be
5139/// simplified by widening the elements being shuffled.
5140///
5141/// Appends the mask for wider elements in WidenedMask if valid. Otherwise
5142/// leaves it in an unspecified state.
5143///
5144/// NOTE: This must handle normal vector shuffle masks and *target* vector
5145/// shuffle masks. The latter have the special property of a '-2' representing
5146/// a zero-ed lane of a vector.
5147static bool canWidenShuffleElements(ArrayRef<int> Mask,
5148 SmallVectorImpl<int> &WidenedMask) {
5149 WidenedMask.assign(Mask.size() / 2, 0);
5150 for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
5151 int M0 = Mask[i];
5152 int M1 = Mask[i + 1];
5153
5154 // If both elements are undef, its trivial.
5155 if (M0 == SM_SentinelUndef && M1 == SM_SentinelUndef) {
5156 WidenedMask[i / 2] = SM_SentinelUndef;
5157 continue;
5158 }
5159
5160 // Check for an undef mask and a mask value properly aligned to fit with
5161 // a pair of values. If we find such a case, use the non-undef mask's value.
5162 if (M0 == SM_SentinelUndef && M1 >= 0 && (M1 % 2) == 1) {
5163 WidenedMask[i / 2] = M1 / 2;
5164 continue;
5165 }
5166 if (M1 == SM_SentinelUndef && M0 >= 0 && (M0 % 2) == 0) {
5167 WidenedMask[i / 2] = M0 / 2;
5168 continue;
5169 }
5170
5171 // When zeroing, we need to spread the zeroing across both lanes to widen.
5172 if (M0 == SM_SentinelZero || M1 == SM_SentinelZero) {
5173 if ((M0 == SM_SentinelZero || M0 == SM_SentinelUndef) &&
5174 (M1 == SM_SentinelZero || M1 == SM_SentinelUndef)) {
5175 WidenedMask[i / 2] = SM_SentinelZero;
5176 continue;
5177 }
5178 return false;
5179 }
5180
5181 // Finally check if the two mask values are adjacent and aligned with
5182 // a pair.
5183 if (M0 != SM_SentinelUndef && (M0 % 2) == 0 && (M0 + 1) == M1) {
5184 WidenedMask[i / 2] = M0 / 2;
5185 continue;
5186 }
5187
5188 // Otherwise we can't safely widen the elements used in this shuffle.
5189 return false;
5190 }
5191 assert(WidenedMask.size() == Mask.size() / 2 &&((WidenedMask.size() == Mask.size() / 2 && "Incorrect size of mask after widening the elements!"
) ? static_cast<void> (0) : __assert_fail ("WidenedMask.size() == Mask.size() / 2 && \"Incorrect size of mask after widening the elements!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 5192, __PRETTY_FUNCTION__))
5192 "Incorrect size of mask after widening the elements!")((WidenedMask.size() == Mask.size() / 2 && "Incorrect size of mask after widening the elements!"
) ? static_cast<void> (0) : __assert_fail ("WidenedMask.size() == Mask.size() / 2 && \"Incorrect size of mask after widening the elements!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 5192, __PRETTY_FUNCTION__))
;
5193
5194 return true;
5195}
5196
5197static bool canWidenShuffleElements(ArrayRef<int> Mask,
5198 const APInt &Zeroable,
5199 SmallVectorImpl<int> &WidenedMask) {
5200 SmallVector<int, 32> TargetMask(Mask.begin(), Mask.end());
5201 for (int i = 0, Size = TargetMask.size(); i < Size; ++i) {
5202 if (TargetMask[i] == SM_SentinelUndef)
5203 continue;
5204 if (Zeroable[i])
5205 TargetMask[i] = SM_SentinelZero;
5206 }
5207 return canWidenShuffleElements(TargetMask, WidenedMask);
5208}
5209
5210static bool canWidenShuffleElements(ArrayRef<int> Mask) {
5211 SmallVector<int, 32> WidenedMask;
5212 return canWidenShuffleElements(Mask, WidenedMask);
5213}
5214
5215/// Returns true if Elt is a constant zero or a floating point constant +0.0.
5216bool X86::isZeroNode(SDValue Elt) {
5217 return isNullConstant(Elt) || isNullFPConstant(Elt);
5218}
5219
5220// Build a vector of constants.
5221// Use an UNDEF node if MaskElt == -1.
5222// Split 64-bit constants in the 32-bit mode.
5223static SDValue getConstVector(ArrayRef<int> Values, MVT VT, SelectionDAG &DAG,
5224 const SDLoc &dl, bool IsMask = false) {
5225
5226 SmallVector<SDValue, 32> Ops;
5227 bool Split = false;
5228
5229 MVT ConstVecVT = VT;
5230 unsigned NumElts = VT.getVectorNumElements();
5231 bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
5232 if (!In64BitMode && VT.getVectorElementType() == MVT::i64) {
5233 ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
5234 Split = true;
5235 }
5236
5237 MVT EltVT = ConstVecVT.getVectorElementType();
5238 for (unsigned i = 0; i < NumElts; ++i) {
5239 bool IsUndef = Values[i] < 0 && IsMask;
5240 SDValue OpNode = IsUndef ? DAG.getUNDEF(EltVT) :
5241 DAG.getConstant(Values[i], dl, EltVT);
5242 Ops.push_back(OpNode);
5243 if (Split)
5244 Ops.push_back(IsUndef ? DAG.getUNDEF(EltVT) :
5245 DAG.getConstant(0, dl, EltVT));
5246 }
5247 SDValue ConstsNode = DAG.getBuildVector(ConstVecVT, dl, Ops);
5248 if (Split)
5249 ConstsNode = DAG.getBitcast(VT, ConstsNode);
5250 return ConstsNode;
5251}
5252
5253static SDValue getConstVector(ArrayRef<APInt> Bits, APInt &Undefs,
5254 MVT VT, SelectionDAG &DAG, const SDLoc &dl) {
5255 assert(Bits.size() == Undefs.getBitWidth() &&((Bits.size() == Undefs.getBitWidth() && "Unequal constant and undef arrays"
) ? static_cast<void> (0) : __assert_fail ("Bits.size() == Undefs.getBitWidth() && \"Unequal constant and undef arrays\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 5256, __PRETTY_FUNCTION__))
5256 "Unequal constant and undef arrays")((Bits.size() == Undefs.getBitWidth() && "Unequal constant and undef arrays"
) ? static_cast<void> (0) : __assert_fail ("Bits.size() == Undefs.getBitWidth() && \"Unequal constant and undef arrays\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 5256, __PRETTY_FUNCTION__))
;
5257 SmallVector<SDValue, 32> Ops;
5258 bool Split = false;
5259
5260 MVT ConstVecVT = VT;
5261 unsigned NumElts = VT.getVectorNumElements();
5262 bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
5263 if (!In64BitMode && VT.getVectorElementType() == MVT::i64) {
5264 ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
5265 Split = true;
5266 }
5267
5268 MVT EltVT = ConstVecVT.getVectorElementType();
5269 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
5270 if (Undefs[i]) {
5271 Ops.append(Split ? 2 : 1, DAG.getUNDEF(EltVT));
5272 continue;
5273 }
5274 const APInt &V = Bits[i];
5275 assert(V.getBitWidth() == VT.getScalarSizeInBits() && "Unexpected sizes")((V.getBitWidth() == VT.getScalarSizeInBits() && "Unexpected sizes"
) ? static_cast<void> (0) : __assert_fail ("V.getBitWidth() == VT.getScalarSizeInBits() && \"Unexpected sizes\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 5275, __PRETTY_FUNCTION__))
;
5276 if (Split) {
5277 Ops.push_back(DAG.getConstant(V.trunc(32), dl, EltVT));
5278 Ops.push_back(DAG.getConstant(V.lshr(32).trunc(32), dl, EltVT));
5279 } else if (EltVT == MVT::f32) {
5280 APFloat FV(APFloat::IEEEsingle(), V);
5281 Ops.push_back(DAG.getConstantFP(FV, dl, EltVT));
5282 } else if (EltVT == MVT::f64) {
5283 APFloat FV(APFloat::IEEEdouble(), V);
5284 Ops.push_back(DAG.getConstantFP(FV, dl, EltVT));
5285 } else {
5286 Ops.push_back(DAG.getConstant(V, dl, EltVT));
5287 }
5288 }
5289
5290 SDValue ConstsNode = DAG.getBuildVector(ConstVecVT, dl, Ops);
5291 return DAG.getBitcast(VT, ConstsNode);
5292}
5293
5294/// Returns a vector of specified type with all zero elements.
5295static SDValue getZeroVector(MVT VT, const X86Subtarget &Subtarget,
5296 SelectionDAG &DAG, const SDLoc &dl) {
5297 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector() ||(((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector
() || VT.getVectorElementType() == MVT::i1) && "Unexpected vector type"
) ? static_cast<void> (0) : __assert_fail ("(VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector() || VT.getVectorElementType() == MVT::i1) && \"Unexpected vector type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 5299, __PRETTY_FUNCTION__))
5298 VT.getVectorElementType() == MVT::i1) &&(((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector
() || VT.getVectorElementType() == MVT::i1) && "Unexpected vector type"
) ? static_cast<void> (0) : __assert_fail ("(VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector() || VT.getVectorElementType() == MVT::i1) && \"Unexpected vector type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 5299, __PRETTY_FUNCTION__))
5299 "Unexpected vector type")(((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector
() || VT.getVectorElementType() == MVT::i1) && "Unexpected vector type"
) ? static_cast<void> (0) : __assert_fail ("(VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector() || VT.getVectorElementType() == MVT::i1) && \"Unexpected vector type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 5299, __PRETTY_FUNCTION__))
;
5300
5301 // Try to build SSE/AVX zero vectors as <N x i32> bitcasted to their dest
5302 // type. This ensures they get CSE'd. But if the integer type is not
5303 // available, use a floating-point +0.0 instead.
5304 SDValue Vec;
5305 if (!Subtarget.hasSSE2() && VT.is128BitVector()) {
5306 Vec = DAG.getConstantFP(+0.0, dl, MVT::v4f32);
5307 } else if (VT.getVectorElementType() == MVT::i1) {
5308 assert((Subtarget.hasBWI() || VT.getVectorNumElements() <= 16) &&(((Subtarget.hasBWI() || VT.getVectorNumElements() <= 16) &&
"Unexpected vector type") ? static_cast<void> (0) : __assert_fail
("(Subtarget.hasBWI() || VT.getVectorNumElements() <= 16) && \"Unexpected vector type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 5309, __PRETTY_FUNCTION__))
5309 "Unexpected vector type")(((Subtarget.hasBWI() || VT.getVectorNumElements() <= 16) &&
"Unexpected vector type") ? static_cast<void> (0) : __assert_fail
("(Subtarget.hasBWI() || VT.getVectorNumElements() <= 16) && \"Unexpected vector type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 5309, __PRETTY_FUNCTION__))
;
5310 Vec = DAG.getConstant(0, dl, VT);
5311 } else {
5312 unsigned Num32BitElts = VT.getSizeInBits() / 32;
5313 Vec = DAG.getConstant(0, dl, MVT::getVectorVT(MVT::i32, Num32BitElts));
5314 }
5315 return DAG.getBitcast(VT, Vec);
5316}
5317
5318static SDValue extractSubVector(SDValue Vec, unsigned IdxVal, SelectionDAG &DAG,
5319 const SDLoc &dl, unsigned vectorWidth) {
5320 EVT VT = Vec.getValueType();
5321 EVT ElVT = VT.getVectorElementType();
5322 unsigned Factor = VT.getSizeInBits()/vectorWidth;
5323 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
5324 VT.getVectorNumElements()/Factor);
5325
5326 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
5327 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
5328 assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2")((isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2"
) ? static_cast<void> (0) : __assert_fail ("isPowerOf2_32(ElemsPerChunk) && \"Elements per chunk not power of 2\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 5328, __PRETTY_FUNCTION__))
;
5329
5330 // This is the index of the first element of the vectorWidth-bit chunk
5331 // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
5332 IdxVal &= ~(ElemsPerChunk - 1);
5333
5334 // If the input is a buildvector just emit a smaller one.
5335 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
5336 return DAG.getBuildVector(ResultVT, dl,
5337 Vec->ops().slice(IdxVal, ElemsPerChunk));
5338
5339 SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
5340 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
5341}
5342
5343/// Generate a DAG to grab 128-bits from a vector > 128 bits. This
5344/// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
5345/// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
5346/// instructions or a simple subregister reference. Idx is an index in the
5347/// 128 bits we want. It need not be aligned to a 128-bit boundary. That makes
5348/// lowering EXTRACT_VECTOR_ELT operations easier.
5349static SDValue extract128BitVector(SDValue Vec, unsigned IdxVal,
5350 SelectionDAG &DAG, const SDLoc &dl) {
5351 assert((Vec.getValueType().is256BitVector() ||(((Vec.getValueType().is256BitVector() || Vec.getValueType().
is512BitVector()) && "Unexpected vector size!") ? static_cast
<void> (0) : __assert_fail ("(Vec.getValueType().is256BitVector() || Vec.getValueType().is512BitVector()) && \"Unexpected vector size!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 5352, __PRETTY_FUNCTION__))
5352 Vec.getValueType().is512BitVector()) && "Unexpected vector size!")(((Vec.getValueType().is256BitVector() || Vec.getValueType().
is512BitVector()) && "Unexpected vector size!") ? static_cast
<void> (0) : __assert_fail ("(Vec.getValueType().is256BitVector() || Vec.getValueType().is512BitVector()) && \"Unexpected vector size!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 5352, __PRETTY_FUNCTION__))
;
5353 return extractSubVector(Vec, IdxVal, DAG, dl, 128);
5354}
5355
5356/// Generate a DAG to grab 256-bits from a 512-bit vector.
5357static SDValue extract256BitVector(SDValue Vec, unsigned IdxVal,
5358 SelectionDAG &DAG, const SDLoc &dl) {
5359 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!")((Vec.getValueType().is512BitVector() && "Unexpected vector size!"
) ? static_cast<void> (0) : __assert_fail ("Vec.getValueType().is512BitVector() && \"Unexpected vector size!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 5359, __PRETTY_FUNCTION__))
;
5360 return extractSubVector(Vec, IdxVal, DAG, dl, 256);
5361}
5362
5363static SDValue insertSubVector(SDValue Result, SDValue Vec, unsigned IdxVal,
5364 SelectionDAG &DAG, const SDLoc &dl,
5365 unsigned vectorWidth) {
5366 assert((vectorWidth == 128 || vectorWidth == 256) &&(((vectorWidth == 128 || vectorWidth == 256) && "Unsupported vector width"
) ? static_cast<void> (0) : __assert_fail ("(vectorWidth == 128 || vectorWidth == 256) && \"Unsupported vector width\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 5367, __PRETTY_FUNCTION__))
5367 "Unsupported vector width")(((vectorWidth == 128 || vectorWidth == 256) && "Unsupported vector width"
) ? static_cast<void> (0) : __assert_fail ("(vectorWidth == 128 || vectorWidth == 256) && \"Unsupported vector width\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 5367, __PRETTY_FUNCTION__))
;
5368 // Inserting UNDEF is Result
5369 if (Vec.isUndef())
5370 return Result;
5371 EVT VT = Vec.getValueType();
5372 EVT ElVT = VT.getVectorElementType();
5373 EVT ResultVT = Result.getValueType();
5374
5375 // Insert the relevant vectorWidth bits.
5376 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
5377 assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2")((isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2"
) ? static_cast<void> (0) : __assert_fail ("isPowerOf2_32(ElemsPerChunk) && \"Elements per chunk not power of 2\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 5377, __PRETTY_FUNCTION__))
;
5378
5379 // This is the index of the first element of the vectorWidth-bit chunk
5380 // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
5381 IdxVal &= ~(ElemsPerChunk - 1);
5382
5383 SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
5384 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
5385}
5386
5387/// Generate a DAG to put 128-bits into a vector > 128 bits. This
5388/// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
5389/// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
5390/// simple superregister reference. Idx is an index in the 128 bits
5391/// we want. It need not be aligned to a 128-bit boundary. That makes
5392/// lowering INSERT_VECTOR_ELT operations easier.
5393static SDValue insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
5394 SelectionDAG &DAG, const SDLoc &dl) {
5395 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!")((Vec.getValueType().is128BitVector() && "Unexpected vector size!"
) ? static_cast<void> (0) : __assert_fail ("Vec.getValueType().is128BitVector() && \"Unexpected vector size!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 5395, __PRETTY_FUNCTION__))
;
5396 return insertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
5397}
5398
5399/// Widen a vector to a larger size with the same scalar type, with the new
5400/// elements either zero or undef.
5401static SDValue widenSubVector(MVT VT, SDValue Vec, bool ZeroNewElements,
5402 const X86Subtarget &Subtarget, SelectionDAG &DAG,
5403 const SDLoc &dl) {
5404 assert(Vec.getValueSizeInBits() < VT.getSizeInBits() &&((Vec.getValueSizeInBits() < VT.getSizeInBits() &&
Vec.getValueType().getScalarType() == VT.getScalarType() &&
"Unsupported vector widening type") ? static_cast<void>
(0) : __assert_fail ("Vec.getValueSizeInBits() < VT.getSizeInBits() && Vec.getValueType().getScalarType() == VT.getScalarType() && \"Unsupported vector widening type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 5406, __PRETTY_FUNCTION__))
5405 Vec.getValueType().getScalarType() == VT.getScalarType() &&((Vec.getValueSizeInBits() < VT.getSizeInBits() &&
Vec.getValueType().getScalarType() == VT.getScalarType() &&
"Unsupported vector widening type") ? static_cast<void>
(0) : __assert_fail ("Vec.getValueSizeInBits() < VT.getSizeInBits() && Vec.getValueType().getScalarType() == VT.getScalarType() && \"Unsupported vector widening type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 5406, __PRETTY_FUNCTION__))
5406 "Unsupported vector widening type")((Vec.getValueSizeInBits() < VT.getSizeInBits() &&
Vec.getValueType().getScalarType() == VT.getScalarType() &&
"Unsupported vector widening type") ? static_cast<void>
(0) : __assert_fail ("Vec.getValueSizeInBits() < VT.getSizeInBits() && Vec.getValueType().getScalarType() == VT.getScalarType() && \"Unsupported vector widening type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 5406, __PRETTY_FUNCTION__))
;
5407 SDValue Res = ZeroNewElements ? getZeroVector(VT, Subtarget, DAG, dl)
5408 : DAG.getUNDEF(VT);
5409 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, VT, Res, Vec,
5410 DAG.getIntPtrConstant(0, dl));
5411}
5412
5413// Helper function to collect subvector ops that are concated together,
5414// either by ISD::CONCAT_VECTORS or a ISD::INSERT_SUBVECTOR series.
5415// The subvectors in Ops are guaranteed to be the same type.
5416static bool collectConcatOps(SDNode *N, SmallVectorImpl<SDValue> &Ops) {
5417 assert(Ops.empty() && "Expected an empty ops vector")((Ops.empty() && "Expected an empty ops vector") ? static_cast
<void> (0) : __assert_fail ("Ops.empty() && \"Expected an empty ops vector\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 5417, __PRETTY_FUNCTION__))
;
5418
5419 if (N->getOpcode() == ISD::CONCAT_VECTORS) {
5420 Ops.append(N->op_begin(), N->op_end());
5421 return true;
5422 }
5423
5424 if (N->getOpcode() == ISD::INSERT_SUBVECTOR &&
5425 isa<ConstantSDNode>(N->getOperand(2))) {
5426 SDValue Src = N->getOperand(0);
5427 SDValue Sub = N->getOperand(1);
5428 const APInt &Idx = N->getConstantOperandAPInt(2);
5429 EVT VT = Src.getValueType();
5430 EVT SubVT = Sub.getValueType();
5431
5432 // TODO - Handle more general insert_subvector chains.
5433 if (VT.getSizeInBits() == (SubVT.getSizeInBits() * 2) &&
5434 Idx == (VT.getVectorNumElements() / 2) &&
5435 Src.getOpcode() == ISD::INSERT_SUBVECTOR &&
5436 isNullConstant(Src.getOperand(2))) {
5437 Ops.push_back(Src.getOperand(1));
5438 Ops.push_back(Sub);
5439 return true;
5440 }
5441 }
5442
5443 return false;
5444}
5445
5446// Helper for splitting operands of an operation to legal target size and
5447// apply a function on each part.
5448// Useful for operations that are available on SSE2 in 128-bit, on AVX2 in
5449// 256-bit and on AVX512BW in 512-bit. The argument VT is the type used for
5450// deciding if/how to split Ops. Ops elements do *not* have to be of type VT.
5451// The argument Builder is a function that will be applied on each split part:
5452// SDValue Builder(SelectionDAG&G, SDLoc, ArrayRef<SDValue>)
5453template <typename F>
5454SDValue SplitOpsAndApply(SelectionDAG &DAG, const X86Subtarget &Subtarget,
5455 const SDLoc &DL, EVT VT, ArrayRef<SDValue> Ops,
5456 F Builder, bool CheckBWI = true) {
5457 assert(Subtarget.hasSSE2() && "Target assumed to support at least SSE2")((Subtarget.hasSSE2() && "Target assumed to support at least SSE2"
) ? static_cast<void> (0) : __assert_fail ("Subtarget.hasSSE2() && \"Target assumed to support at least SSE2\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 5457, __PRETTY_FUNCTION__))
;
5458 unsigned NumSubs = 1;
5459 if ((CheckBWI && Subtarget.useBWIRegs()) ||
5460 (!CheckBWI && Subtarget.useAVX512Regs())) {
5461 if (VT.getSizeInBits() > 512) {
5462 NumSubs = VT.getSizeInBits() / 512;
5463 assert((VT.getSizeInBits() % 512) == 0 && "Illegal vector size")(((VT.getSizeInBits() % 512) == 0 && "Illegal vector size"
) ? static_cast<void> (0) : __assert_fail ("(VT.getSizeInBits() % 512) == 0 && \"Illegal vector size\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 5463, __PRETTY_FUNCTION__))
;
5464 }
5465 } else if (Subtarget.hasAVX2()) {
5466 if (VT.getSizeInBits() > 256) {
5467 NumSubs = VT.getSizeInBits() / 256;
5468 assert((VT.getSizeInBits() % 256) == 0 && "Illegal vector size")(((VT.getSizeInBits() % 256) == 0 && "Illegal vector size"
) ? static_cast<void> (0) : __assert_fail ("(VT.getSizeInBits() % 256) == 0 && \"Illegal vector size\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 5468, __PRETTY_FUNCTION__))
;
5469 }
5470 } else {
5471 if (VT.getSizeInBits() > 128) {
5472 NumSubs = VT.getSizeInBits() / 128;
5473 assert((VT.getSizeInBits() % 128) == 0 && "Illegal vector size")(((VT.getSizeInBits() % 128) == 0 && "Illegal vector size"
) ? static_cast<void> (0) : __assert_fail ("(VT.getSizeInBits() % 128) == 0 && \"Illegal vector size\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 5473, __PRETTY_FUNCTION__))
;
5474 }
5475 }
5476
5477 if (NumSubs == 1)
5478 return Builder(DAG, DL, Ops);
5479
5480 SmallVector<SDValue, 4> Subs;
5481 for (unsigned i = 0; i != NumSubs; ++i) {
5482 SmallVector<SDValue, 2> SubOps;
5483 for (SDValue Op : Ops) {
5484 EVT OpVT = Op.getValueType();
5485 unsigned NumSubElts = OpVT.getVectorNumElements() / NumSubs;
5486 unsigned SizeSub = OpVT.getSizeInBits() / NumSubs;
5487 SubOps.push_back(extractSubVector(Op, i * NumSubElts, DAG, DL, SizeSub));
5488 }
5489 Subs.push_back(Builder(DAG, DL, SubOps));
5490 }
5491 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Subs);
5492}
5493
5494// Return true if the instruction zeroes the unused upper part of the
5495// destination and accepts mask.
5496static bool isMaskedZeroUpperBitsvXi1(unsigned int Opcode) {
5497 switch (Opcode) {
5498 default:
5499 return false;
5500 case X86ISD::CMPM:
5501 case X86ISD::CMPM_SAE:
5502 case ISD::SETCC:
5503 return true;
5504 }
5505}
5506
5507/// Insert i1-subvector to i1-vector.
5508static SDValue insert1BitVector(SDValue Op, SelectionDAG &DAG,
5509 const X86Subtarget &Subtarget) {
5510
5511 SDLoc dl(Op);
5512 SDValue Vec = Op.getOperand(0);
5513 SDValue SubVec = Op.getOperand(1);
5514 SDValue Idx = Op.getOperand(2);
5515
5516 if (!isa<ConstantSDNode>(Idx))
5517 return SDValue();
5518
5519 // Inserting undef is a nop. We can just return the original vector.
5520 if (SubVec.isUndef())
5521 return Vec;
5522
5523 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5524 if (IdxVal == 0 && Vec.isUndef()) // the operation is legal
5525 return Op;
5526
5527 MVT OpVT = Op.getSimpleValueType();
5528 unsigned NumElems = OpVT.getVectorNumElements();
5529
5530 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
5531
5532 // Extend to natively supported kshift.
5533 MVT WideOpVT = OpVT;
5534 if ((!Subtarget.hasDQI() && NumElems == 8) || NumElems < 8)
5535 WideOpVT = Subtarget.hasDQI() ? MVT::v8i1 : MVT::v16i1;
5536
5537 // Inserting into the lsbs of a zero vector is legal. ISel will insert shifts
5538 // if necessary.
5539 if (IdxVal == 0 && ISD::isBuildVectorAllZeros(Vec.getNode())) {
5540 // May need to promote to a legal type.
5541 Op = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
5542 getZeroVector(WideOpVT, Subtarget, DAG, dl),
5543 SubVec, Idx);
5544 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
5545 }
5546
5547 MVT SubVecVT = SubVec.getSimpleValueType();
5548 unsigned SubVecNumElems = SubVecVT.getVectorNumElements();
5549
5550 assert(IdxVal + SubVecNumElems <= NumElems &&((IdxVal + SubVecNumElems <= NumElems && IdxVal % SubVecVT
.getSizeInBits() == 0 && "Unexpected index value in INSERT_SUBVECTOR"
) ? static_cast<void> (0) : __assert_fail ("IdxVal + SubVecNumElems <= NumElems && IdxVal % SubVecVT.getSizeInBits() == 0 && \"Unexpected index value in INSERT_SUBVECTOR\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 5552, __PRETTY_FUNCTION__))
5551 IdxVal % SubVecVT.getSizeInBits() == 0 &&((IdxVal + SubVecNumElems <= NumElems && IdxVal % SubVecVT
.getSizeInBits() == 0 && "Unexpected index value in INSERT_SUBVECTOR"
) ? static_cast<void> (0) : __assert_fail ("IdxVal + SubVecNumElems <= NumElems && IdxVal % SubVecVT.getSizeInBits() == 0 && \"Unexpected index value in INSERT_SUBVECTOR\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 5552, __PRETTY_FUNCTION__))
5552 "Unexpected index value in INSERT_SUBVECTOR")((IdxVal + SubVecNumElems <= NumElems && IdxVal % SubVecVT
.getSizeInBits() == 0 && "Unexpected index value in INSERT_SUBVECTOR"
) ? static_cast<void> (0) : __assert_fail ("IdxVal + SubVecNumElems <= NumElems && IdxVal % SubVecVT.getSizeInBits() == 0 && \"Unexpected index value in INSERT_SUBVECTOR\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 5552, __PRETTY_FUNCTION__))
;
5553
5554 SDValue Undef = DAG.getUNDEF(WideOpVT);
5555
5556 if (IdxVal == 0) {
5557 // Zero lower bits of the Vec
5558 SDValue ShiftBits = DAG.getConstant(SubVecNumElems, dl, MVT::i8);
5559 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT, Undef, Vec,
5560 ZeroIdx);
5561 Vec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Vec, ShiftBits);
5562 Vec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, Vec, ShiftBits);
5563 // Merge them together, SubVec should be zero extended.
5564 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
5565 getZeroVector(WideOpVT, Subtarget, DAG, dl),
5566 SubVec, ZeroIdx);
5567 Op = DAG.getNode(ISD::OR, dl, WideOpVT, Vec, SubVec);
5568 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
5569 }
5570
5571 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
5572 Undef, SubVec, ZeroIdx);
5573
5574 if (Vec.isUndef()) {
5575 assert(IdxVal != 0 && "Unexpected index")((IdxVal != 0 && "Unexpected index") ? static_cast<
void> (0) : __assert_fail ("IdxVal != 0 && \"Unexpected index\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 5575, __PRETTY_FUNCTION__))
;
5576 SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
5577 DAG.getConstant(IdxVal, dl, MVT::i8));
5578 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, SubVec, ZeroIdx);
5579 }
5580
5581 if (ISD::isBuildVectorAllZeros(Vec.getNode())) {
5582 assert(IdxVal != 0 && "Unexpected index")((IdxVal != 0 && "Unexpected index") ? static_cast<
void> (0) : __assert_fail ("IdxVal != 0 && \"Unexpected index\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 5582, __PRETTY_FUNCTION__))
;
5583 NumElems = WideOpVT.getVectorNumElements();
5584 unsigned ShiftLeft = NumElems - SubVecNumElems;
5585 unsigned ShiftRight = NumElems - SubVecNumElems - IdxVal;
5586 SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
5587 DAG.getConstant(ShiftLeft, dl, MVT::i8));
5588 if (ShiftRight != 0)
5589 SubVec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, SubVec,
5590 DAG.getConstant(ShiftRight, dl, MVT::i8));
5591 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, SubVec, ZeroIdx);
5592 }
5593
5594 // Simple case when we put subvector in the upper part
5595 if (IdxVal + SubVecNumElems == NumElems) {
5596 SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
5597 DAG.getConstant(IdxVal, dl, MVT::i8));
5598 if (SubVecNumElems * 2 == NumElems) {
5599 // Special case, use legal zero extending insert_subvector. This allows
5600 // isel to opimitize when bits are known zero.
5601 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVecVT, Vec, ZeroIdx);
5602 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
5603 getZeroVector(WideOpVT, Subtarget, DAG, dl),
5604 Vec, ZeroIdx);
5605 } else {
5606 // Otherwise use explicit shifts to zero the bits.
5607 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
5608 Undef, Vec, ZeroIdx);
5609 NumElems = WideOpVT.getVectorNumElements();
5610 SDValue ShiftBits = DAG.getConstant(NumElems - IdxVal, dl, MVT::i8);
5611 Vec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, Vec, ShiftBits);
5612 Vec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Vec, ShiftBits);
5613 }
5614 Op = DAG.getNode(ISD::OR, dl, WideOpVT, Vec, SubVec);
5615 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
5616 }
5617
5618 // Inserting into the middle is more complicated.
5619
5620 NumElems = WideOpVT.getVectorNumElements();
5621
5622 // Widen the vector if needed.
5623 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT, Undef, Vec, ZeroIdx);
5624 // Move the current value of the bit to be replace to the lsbs.
5625 Op = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Vec,
5626 DAG.getConstant(IdxVal, dl, MVT::i8));
5627 // Xor with the new bit.
5628 Op = DAG.getNode(ISD::XOR, dl, WideOpVT, Op, SubVec);
5629 // Shift to MSB, filling bottom bits with 0.
5630 unsigned ShiftLeft = NumElems - SubVecNumElems;
5631 Op = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, Op,
5632 DAG.getConstant(ShiftLeft, dl, MVT::i8));
5633 // Shift to the final position, filling upper bits with 0.
5634 unsigned ShiftRight = NumElems - SubVecNumElems - IdxVal;
5635 Op = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Op,
5636 DAG.getConstant(ShiftRight, dl, MVT::i8));
5637 // Xor with original vector leaving the new value.
5638 Op = DAG.getNode(ISD::XOR, dl, WideOpVT, Vec, Op);
5639 // Reduce to original width if needed.
5640 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
5641}
5642
5643static SDValue concatSubVectors(SDValue V1, SDValue V2, EVT VT,
5644 unsigned NumElems, SelectionDAG &DAG,
5645 const SDLoc &dl, unsigned VectorWidth) {
5646 SDValue V = insertSubVector(DAG.getUNDEF(VT), V1, 0, DAG, dl, VectorWidth);
5647 return insertSubVector(V, V2, NumElems / 2, DAG, dl, VectorWidth);
5648}
5649
5650/// Returns a vector of specified type with all bits set.
5651/// Always build ones vectors as <4 x i32>, <8 x i32> or <16 x i32>.
5652/// Then bitcast to their original type, ensuring they get CSE'd.
5653static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
5654 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&(((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector
()) && "Expected a 128/256/512-bit vector type") ? static_cast
<void> (0) : __assert_fail ("(VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) && \"Expected a 128/256/512-bit vector type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 5655, __PRETTY_FUNCTION__))
5655 "Expected a 128/256/512-bit vector type")(((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector
()) && "Expected a 128/256/512-bit vector type") ? static_cast
<void> (0) : __assert_fail ("(VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) && \"Expected a 128/256/512-bit vector type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 5655, __PRETTY_FUNCTION__))
;
5656
5657 APInt Ones = APInt::getAllOnesValue(32);
5658 unsigned NumElts = VT.getSizeInBits() / 32;
5659 SDValue Vec = DAG.getConstant(Ones, dl, MVT::getVectorVT(MVT::i32, NumElts));
5660 return DAG.getBitcast(VT, Vec);
5661}
5662
5663static SDValue getExtendInVec(bool Signed, const SDLoc &DL, EVT VT, SDValue In,
5664 SelectionDAG &DAG) {
5665 EVT InVT = In.getValueType();
5666 assert(VT.isVector() && InVT.isVector() && "Expected vector VTs.")((VT.isVector() && InVT.isVector() && "Expected vector VTs."
) ? static_cast<void> (0) : __assert_fail ("VT.isVector() && InVT.isVector() && \"Expected vector VTs.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 5666, __PRETTY_FUNCTION__))
;
5667
5668 // For 256-bit vectors, we only need the lower (128-bit) input half.
5669 // For 512-bit vectors, we only need the lower input half or quarter.
5670 if (InVT.getSizeInBits() > 128) {
5671 assert(VT.getSizeInBits() == InVT.getSizeInBits() &&((VT.getSizeInBits() == InVT.getSizeInBits() && "Expected VTs to be the same size!"
) ? static_cast<void> (0) : __assert_fail ("VT.getSizeInBits() == InVT.getSizeInBits() && \"Expected VTs to be the same size!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 5672, __PRETTY_FUNCTION__))
5672 "Expected VTs to be the same size!")((VT.getSizeInBits() == InVT.getSizeInBits() && "Expected VTs to be the same size!"
) ? static_cast<void> (0) : __assert_fail ("VT.getSizeInBits() == InVT.getSizeInBits() && \"Expected VTs to be the same size!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 5672, __PRETTY_FUNCTION__))
;
5673 unsigned Scale = VT.getScalarSizeInBits() / InVT.getScalarSizeInBits();
5674 In = extractSubVector(In, 0, DAG, DL,
5675 std::max(128U, VT.getSizeInBits() / Scale));
5676 InVT = In.getValueType();
5677 }
5678
5679 if (VT.getVectorNumElements() == InVT.getVectorNumElements())
5680 return DAG.getNode(Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
5681 DL, VT, In);
5682
5683 return DAG.getNode(Signed ? ISD::SIGN_EXTEND_VECTOR_INREG
5684 : ISD::ZERO_EXTEND_VECTOR_INREG,
5685 DL, VT, In);
5686}
5687
5688/// Returns a vector_shuffle node for an unpackl operation.
5689static SDValue getUnpackl(SelectionDAG &DAG, const SDLoc &dl, MVT VT,
5690 SDValue V1, SDValue V2) {
5691 SmallVector<int, 8> Mask;
5692 createUnpackShuffleMask(VT, Mask, /* Lo = */ true, /* Unary = */ false);
5693 return DAG.getVectorShuffle(VT, dl, V1, V2, Mask);
5694}
5695
5696/// Returns a vector_shuffle node for an unpackh operation.
5697static SDValue getUnpackh(SelectionDAG &DAG, const SDLoc &dl, MVT VT,
5698 SDValue V1, SDValue V2) {
5699 SmallVector<int, 8> Mask;
5700 createUnpackShuffleMask(VT, Mask, /* Lo = */ false, /* Unary = */ false);
5701 return DAG.getVectorShuffle(VT, dl, V1, V2, Mask);
5702}
5703
5704/// Return a vector_shuffle of the specified vector of zero or undef vector.
5705/// This produces a shuffle where the low element of V2 is swizzled into the
5706/// zero/undef vector, landing at element Idx.
5707/// This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
5708static SDValue getShuffleVectorZeroOrUndef(SDValue V2, int Idx,
5709 bool IsZero,
5710 const X86Subtarget &Subtarget,
5711 SelectionDAG &DAG) {
5712 MVT VT = V2.getSimpleValueType();
5713 SDValue V1 = IsZero
5714 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5715 int NumElems = VT.getVectorNumElements();
5716 SmallVector<int, 16> MaskVec(NumElems);
5717 for (int i = 0; i != NumElems; ++i)
5718 // If this is the insertion idx, put the low elt of V2 here.
5719 MaskVec[i] = (i == Idx) ? NumElems : i;
5720 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, MaskVec);
5721}
5722
5723static const Constant *getTargetConstantFromNode(LoadSDNode *Load) {
5724 if (!Load)
5725 return nullptr;
5726
5727 SDValue Ptr = Load->getBasePtr();
5728 if (Ptr->getOpcode() == X86ISD::Wrapper ||
5729 Ptr->getOpcode() == X86ISD::WrapperRIP)
5730 Ptr = Ptr->getOperand(0);
5731
5732 auto *CNode = dyn_cast<ConstantPoolSDNode>(Ptr);
5733 if (!CNode || CNode->isMachineConstantPoolEntry() || CNode->getOffset() != 0)
5734 return nullptr;
5735
5736 return CNode->getConstVal();
5737}
5738
5739static const Constant *getTargetConstantFromNode(SDValue Op) {
5740 Op = peekThroughBitcasts(Op);
5741 return getTargetConstantFromNode(dyn_cast<LoadSDNode>(Op));
5742}
5743
5744const Constant *
5745X86TargetLowering::getTargetConstantFromLoad(LoadSDNode *LD) const {
5746 assert(LD && "Unexpected null LoadSDNode")((LD && "Unexpected null LoadSDNode") ? static_cast<
void> (0) : __assert_fail ("LD && \"Unexpected null LoadSDNode\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 5746, __PRETTY_FUNCTION__))
;
5747 return getTargetConstantFromNode(LD);
5748}
5749
5750// Extract raw constant bits from constant pools.
5751static bool getTargetConstantBitsFromNode(SDValue Op, unsigned EltSizeInBits,
5752 APInt &UndefElts,
5753 SmallVectorImpl<APInt> &EltBits,
5754 bool AllowWholeUndefs = true,
5755 bool AllowPartialUndefs = true) {
5756 assert(EltBits.empty() && "Expected an empty EltBits vector")((EltBits.empty() && "Expected an empty EltBits vector"
) ? static_cast<void> (0) : __assert_fail ("EltBits.empty() && \"Expected an empty EltBits vector\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 5756, __PRETTY_FUNCTION__))
;
5757
5758 Op = peekThroughBitcasts(Op);
5759
5760 EVT VT = Op.getValueType();
5761 unsigned SizeInBits = VT.getSizeInBits();
5762 assert((SizeInBits % EltSizeInBits) == 0 && "Can't split constant!")(((SizeInBits % EltSizeInBits) == 0 && "Can't split constant!"
) ? static_cast<void> (0) : __assert_fail ("(SizeInBits % EltSizeInBits) == 0 && \"Can't split constant!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 5762, __PRETTY_FUNCTION__))
;
5763 unsigned NumElts = SizeInBits / EltSizeInBits;
5764
5765 // Bitcast a source array of element bits to the target size.
5766 auto CastBitData = [&](APInt &UndefSrcElts, ArrayRef<APInt> SrcEltBits) {
5767 unsigned NumSrcElts = UndefSrcElts.getBitWidth();
5768 unsigned SrcEltSizeInBits = SrcEltBits[0].getBitWidth();
5769 assert((NumSrcElts * SrcEltSizeInBits) == SizeInBits &&(((NumSrcElts * SrcEltSizeInBits) == SizeInBits && "Constant bit sizes don't match"
) ? static_cast<void> (0) : __assert_fail ("(NumSrcElts * SrcEltSizeInBits) == SizeInBits && \"Constant bit sizes don't match\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 5770, __PRETTY_FUNCTION__))
5770 "Constant bit sizes don't match")(((NumSrcElts * SrcEltSizeInBits) == SizeInBits && "Constant bit sizes don't match"
) ? static_cast<void> (0) : __assert_fail ("(NumSrcElts * SrcEltSizeInBits) == SizeInBits && \"Constant bit sizes don't match\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 5770, __PRETTY_FUNCTION__))
;
5771
5772 // Don't split if we don't allow undef bits.
5773 bool AllowUndefs = AllowWholeUndefs || AllowPartialUndefs;
5774 if (UndefSrcElts.getBoolValue() && !AllowUndefs)
5775 return false;
5776
5777 // If we're already the right size, don't bother bitcasting.
5778 if (NumSrcElts == NumElts) {
5779 UndefElts = UndefSrcElts;
5780 EltBits.assign(SrcEltBits.begin(), SrcEltBits.end());
5781 return true;
5782 }
5783
5784 // Extract all the undef/constant element data and pack into single bitsets.
5785 APInt UndefBits(SizeInBits, 0);
5786 APInt MaskBits(SizeInBits, 0);
5787
5788 for (unsigned i = 0; i != NumSrcElts; ++i) {
5789 unsigned BitOffset = i * SrcEltSizeInBits;
5790 if (UndefSrcElts[i])
5791 UndefBits.setBits(BitOffset, BitOffset + SrcEltSizeInBits);
5792 MaskBits.insertBits(SrcEltBits[i], BitOffset);
5793 }
5794
5795 // Split the undef/constant single bitset data into the target elements.
5796 UndefElts = APInt(NumElts, 0);
5797 EltBits.resize(NumElts, APInt(EltSizeInBits, 0));
5798
5799 for (unsigned i = 0; i != NumElts; ++i) {
5800 unsigned BitOffset = i * EltSizeInBits;
5801 APInt UndefEltBits = UndefBits.extractBits(EltSizeInBits, BitOffset);
5802
5803 // Only treat an element as UNDEF if all bits are UNDEF.
5804 if (UndefEltBits.isAllOnesValue()) {
5805 if (!AllowWholeUndefs)
5806 return false;
5807 UndefElts.setBit(i);
5808 continue;
5809 }
5810
5811 // If only some bits are UNDEF then treat them as zero (or bail if not
5812 // supported).
5813 if (UndefEltBits.getBoolValue() && !AllowPartialUndefs)
5814 return false;
5815
5816 APInt Bits = MaskBits.extractBits(EltSizeInBits, BitOffset);
5817 EltBits[i] = Bits.getZExtValue();
5818 }
5819 return true;
5820 };
5821
5822 // Collect constant bits and insert into mask/undef bit masks.
5823 auto CollectConstantBits = [](const Constant *Cst, APInt &Mask, APInt &Undefs,
5824 unsigned UndefBitIndex) {
5825 if (!Cst)
5826 return false;
5827 if (isa<UndefValue>(Cst)) {
5828 Undefs.setBit(UndefBitIndex);
5829 return true;
5830 }
5831 if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
5832 Mask = CInt->getValue();
5833 return true;
5834 }
5835 if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
5836 Mask = CFP->getValueAPF().bitcastToAPInt();
5837 return true;
5838 }
5839 return false;
5840 };
5841
5842 // Handle UNDEFs.
5843 if (Op.isUndef()) {
5844 APInt UndefSrcElts = APInt::getAllOnesValue(NumElts);
5845 SmallVector<APInt, 64> SrcEltBits(NumElts, APInt(EltSizeInBits, 0));
5846 return CastBitData(UndefSrcElts, SrcEltBits);
5847 }
5848
5849 // Extract scalar constant bits.
5850 if (auto *Cst = dyn_cast<ConstantSDNode>(Op)) {
5851 APInt UndefSrcElts = APInt::getNullValue(1);
5852 SmallVector<APInt, 64> SrcEltBits(1, Cst->getAPIntValue());
5853 return CastBitData(UndefSrcElts, SrcEltBits);
5854 }
5855 if (auto *Cst = dyn_cast<ConstantFPSDNode>(Op)) {
5856 APInt UndefSrcElts = APInt::getNullValue(1);
5857 APInt RawBits = Cst->getValueAPF().bitcastToAPInt();
5858 SmallVector<APInt, 64> SrcEltBits(1, RawBits);
5859 return CastBitData(UndefSrcElts, SrcEltBits);
5860 }
5861
5862 // Extract constant bits from build vector.
5863 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5864 unsigned SrcEltSizeInBits = VT.getScalarSizeInBits();
5865 unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
5866
5867 APInt UndefSrcElts(NumSrcElts, 0);
5868 SmallVector<APInt, 64> SrcEltBits(NumSrcElts, APInt(SrcEltSizeInBits, 0));
5869 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
5870 const SDValue &Src = Op.getOperand(i);
5871 if (Src.isUndef()) {
5872 UndefSrcElts.setBit(i);
5873 continue;
5874 }
5875 auto *Cst = cast<ConstantSDNode>(Src);
5876 SrcEltBits[i] = Cst->getAPIntValue().zextOrTrunc(SrcEltSizeInBits);
5877 }
5878 return CastBitData(UndefSrcElts, SrcEltBits);
5879 }
5880 if (ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode())) {
5881 unsigned SrcEltSizeInBits = VT.getScalarSizeInBits();
5882 unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
5883
5884 APInt UndefSrcElts(NumSrcElts, 0);
5885 SmallVector<APInt, 64> SrcEltBits(NumSrcElts, APInt(SrcEltSizeInBits, 0));
5886 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
5887 const SDValue &Src = Op.getOperand(i);
5888 if (Src.isUndef()) {
5889 UndefSrcElts.setBit(i);
5890 continue;
5891 }
5892 auto *Cst = cast<ConstantFPSDNode>(Src);
5893 APInt RawBits = Cst->getValueAPF().bitcastToAPInt();
5894 SrcEltBits[i] = RawBits.zextOrTrunc(SrcEltSizeInBits);
5895 }
5896 return CastBitData(UndefSrcElts, SrcEltBits);
5897 }
5898
5899 // Extract constant bits from constant pool vector.
5900 if (auto *Cst = getTargetConstantFromNode(Op)) {
5901 Type *CstTy = Cst->getType();
5902 unsigned CstSizeInBits = CstTy->getPrimitiveSizeInBits();
5903 if (!CstTy->isVectorTy() || (CstSizeInBits % SizeInBits) != 0)
5904 return false;
5905
5906 unsigned SrcEltSizeInBits = CstTy->getScalarSizeInBits();
5907 unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
5908
5909 APInt UndefSrcElts(NumSrcElts, 0);
5910 SmallVector<APInt, 64> SrcEltBits(NumSrcElts, APInt(SrcEltSizeInBits, 0));
5911 for (unsigned i = 0; i != NumSrcElts; ++i)
5912 if (!CollectConstantBits(Cst->getAggregateElement(i), SrcEltBits[i],
5913 UndefSrcElts, i))
5914 return false;
5915
5916 return CastBitData(UndefSrcElts, SrcEltBits);
5917 }
5918
5919 // Extract constant bits from a broadcasted constant pool scalar.
5920 if (Op.getOpcode() == X86ISD::VBROADCAST &&
5921 EltSizeInBits <= VT.getScalarSizeInBits()) {
5922 if (auto *Broadcast = getTargetConstantFromNode(Op.getOperand(0))) {
5923 unsigned SrcEltSizeInBits = Broadcast->getType()->getScalarSizeInBits();
5924 unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
5925
5926 APInt UndefSrcElts(NumSrcElts, 0);
5927 SmallVector<APInt, 64> SrcEltBits(1, APInt(SrcEltSizeInBits, 0));
5928 if (CollectConstantBits(Broadcast, SrcEltBits[0], UndefSrcElts, 0)) {
5929 if (UndefSrcElts[0])
5930 UndefSrcElts.setBits(0, NumSrcElts);
5931 SrcEltBits.append(NumSrcElts - 1, SrcEltBits[0]);
5932 return CastBitData(UndefSrcElts, SrcEltBits);
5933 }
5934 }
5935 }
5936
5937 // Extract constant bits from a subvector broadcast.
5938 if (Op.getOpcode() == X86ISD::SUBV_BROADCAST) {
5939 SmallVector<APInt, 16> SubEltBits;
5940 if (getTargetConstantBitsFromNode(Op.getOperand(0), EltSizeInBits,
5941 UndefElts, SubEltBits, AllowWholeUndefs,
5942 AllowPartialUndefs)) {
5943 UndefElts = APInt::getSplat(NumElts, UndefElts);
5944 while (EltBits.size() < NumElts)
5945 EltBits.append(SubEltBits.begin(), SubEltBits.end());
5946 return true;
5947 }
5948 }
5949
5950 // Extract a rematerialized scalar constant insertion.
5951 if (Op.getOpcode() == X86ISD::VZEXT_MOVL &&
5952 Op.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
5953 isa<ConstantSDNode>(Op.getOperand(0).getOperand(0))) {
5954 unsigned SrcEltSizeInBits = VT.getScalarSizeInBits();
5955 unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
5956
5957 APInt UndefSrcElts(NumSrcElts, 0);
5958 SmallVector<APInt, 64> SrcEltBits;
5959 auto *CN = cast<ConstantSDNode>(Op.getOperand(0).getOperand(0));
5960 SrcEltBits.push_back(CN->getAPIntValue().zextOrTrunc(SrcEltSizeInBits));
5961 SrcEltBits.append(NumSrcElts - 1, APInt(SrcEltSizeInBits, 0));
5962 return CastBitData(UndefSrcElts, SrcEltBits);
5963 }
5964
5965 // Extract constant bits from a subvector's source.
5966 if (Op.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
5967 isa<ConstantSDNode>(Op.getOperand(1))) {
5968 // TODO - support extract_subvector through bitcasts.
5969 if (EltSizeInBits != VT.getScalarSizeInBits())
5970 return false;
5971
5972 if (getTargetConstantBitsFromNode(Op.getOperand(0), EltSizeInBits,
5973 UndefElts, EltBits, AllowWholeUndefs,
5974 AllowPartialUndefs)) {
5975 EVT SrcVT = Op.getOperand(0).getValueType();
5976 unsigned NumSrcElts = SrcVT.getVectorNumElements();
5977 unsigned NumSubElts = VT.getVectorNumElements();
5978 unsigned BaseIdx = Op.getConstantOperandVal(1);
5979 UndefElts = UndefElts.extractBits(NumSubElts, BaseIdx);
5980 if ((BaseIdx + NumSubElts) != NumSrcElts)
5981 EltBits.erase(EltBits.begin() + BaseIdx + NumSubElts, EltBits.end());
5982 if (BaseIdx != 0)
5983 EltBits.erase(EltBits.begin(), EltBits.begin() + BaseIdx);
5984 return true;
5985 }
5986 }
5987
5988 // Extract constant bits from shuffle node sources.
5989 if (auto *SVN = dyn_cast<ShuffleVectorSDNode>(Op)) {
5990 // TODO - support shuffle through bitcasts.
5991 if (EltSizeInBits != VT.getScalarSizeInBits())
5992 return false;
5993
5994 ArrayRef<int> Mask = SVN->getMask();
5995 if ((!AllowWholeUndefs || !AllowPartialUndefs) &&
5996 llvm::any_of(Mask, [](int M) { return M < 0; }))
5997 return false;
5998
5999 APInt UndefElts0, UndefElts1;
6000 SmallVector<APInt, 32> EltBits0, EltBits1;
6001 if (isAnyInRange(Mask, 0, NumElts) &&
6002 !getTargetConstantBitsFromNode(Op.getOperand(0), EltSizeInBits,
6003 UndefElts0, EltBits0, AllowWholeUndefs,
6004 AllowPartialUndefs))
6005 return false;
6006 if (isAnyInRange(Mask, NumElts, 2 * NumElts) &&
6007 !getTargetConstantBitsFromNode(Op.getOperand(1), EltSizeInBits,
6008 UndefElts1, EltBits1, AllowWholeUndefs,
6009 AllowPartialUndefs))
6010 return false;
6011
6012 UndefElts = APInt::getNullValue(NumElts);
6013 for (int i = 0; i != (int)NumElts; ++i) {
6014 int M = Mask[i];
6015 if (M < 0) {
6016 UndefElts.setBit(i);
6017 EltBits.push_back(APInt::getNullValue(EltSizeInBits));
6018 } else if (M < (int)NumElts) {
6019 if (UndefElts0[M])
6020 UndefElts.setBit(i);
6021 EltBits.push_back(EltBits0[M]);
6022 } else {
6023 if (UndefElts1[M - NumElts])
6024 UndefElts.setBit(i);
6025 EltBits.push_back(EltBits1[M - NumElts]);
6026 }
6027 }
6028 return true;
6029 }
6030
6031 return false;
6032}
6033
6034static bool isConstantSplat(SDValue Op, APInt &SplatVal) {
6035 APInt UndefElts;
6036 SmallVector<APInt, 16> EltBits;
6037 if (getTargetConstantBitsFromNode(Op, Op.getScalarValueSizeInBits(),
6038 UndefElts, EltBits, true, false)) {
6039 int SplatIndex = -1;
6040 for (int i = 0, e = EltBits.size(); i != e; ++i) {
6041 if (UndefElts[i])
6042 continue;
6043 if (0 <= SplatIndex && EltBits[i] != EltBits[SplatIndex]) {
6044 SplatIndex = -1;
6045 break;
6046 }
6047 SplatIndex = i;
6048 }
6049 if (0 <= SplatIndex) {
6050 SplatVal = EltBits[SplatIndex];
6051 return true;
6052 }
6053 }
6054
6055 return false;
6056}
6057
6058static bool getTargetShuffleMaskIndices(SDValue MaskNode,
6059 unsigned MaskEltSizeInBits,
6060 SmallVectorImpl<uint64_t> &RawMask,
6061 APInt &UndefElts) {
6062 // Extract the raw target constant bits.
6063 SmallVector<APInt, 64> EltBits;
6064 if (!getTargetConstantBitsFromNode(MaskNode, MaskEltSizeInBits, UndefElts,
6065 EltBits, /* AllowWholeUndefs */ true,
6066 /* AllowPartialUndefs */ false))
6067 return false;
6068
6069 // Insert the extracted elements into the mask.
6070 for (APInt Elt : EltBits)
6071 RawMask.push_back(Elt.getZExtValue());
6072
6073 return true;
6074}
6075
6076/// Create a shuffle mask that matches the PACKSS/PACKUS truncation.
6077/// Note: This ignores saturation, so inputs must be checked first.
6078static void createPackShuffleMask(MVT VT, SmallVectorImpl<int> &Mask,
6079 bool Unary) {
6080 assert(Mask.empty() && "Expected an empty shuffle mask vector")((Mask.empty() && "Expected an empty shuffle mask vector"
) ? static_cast<void> (0) : __assert_fail ("Mask.empty() && \"Expected an empty shuffle mask vector\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6080, __PRETTY_FUNCTION__))
;
6081 unsigned NumElts = VT.getVectorNumElements();
6082 unsigned NumLanes = VT.getSizeInBits() / 128;
6083 unsigned NumEltsPerLane = 128 / VT.getScalarSizeInBits();
6084 unsigned Offset = Unary ? 0 : NumElts;
6085
6086 for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
6087 for (unsigned Elt = 0; Elt != NumEltsPerLane; Elt += 2)
6088 Mask.push_back(Elt + (Lane * NumEltsPerLane));
6089 for (unsigned Elt = 0; Elt != NumEltsPerLane; Elt += 2)
6090 Mask.push_back(Elt + (Lane * NumEltsPerLane) + Offset);
6091 }
6092}
6093
6094// Split the demanded elts of a PACKSS/PACKUS node between its operands.
6095static void getPackDemandedElts(EVT VT, const APInt &DemandedElts,
6096 APInt &DemandedLHS, APInt &DemandedRHS) {
6097 int NumLanes = VT.getSizeInBits() / 128;
6098 int NumElts = DemandedElts.getBitWidth();
6099 int NumInnerElts = NumElts / 2;
6100 int NumEltsPerLane = NumElts / NumLanes;
6101 int NumInnerEltsPerLane = NumInnerElts / NumLanes;
6102
6103 DemandedLHS = APInt::getNullValue(NumInnerElts);
6104 DemandedRHS = APInt::getNullValue(NumInnerElts);
6105
6106 // Map DemandedElts to the packed operands.
6107 for (int Lane = 0; Lane != NumLanes; ++Lane) {
6108 for (int Elt = 0; Elt != NumInnerEltsPerLane; ++Elt) {
6109 int OuterIdx = (Lane * NumEltsPerLane) + Elt;
6110 int InnerIdx = (Lane * NumInnerEltsPerLane) + Elt;
6111 if (DemandedElts[OuterIdx])
6112 DemandedLHS.setBit(InnerIdx);
6113 if (DemandedElts[OuterIdx + NumInnerEltsPerLane])
6114 DemandedRHS.setBit(InnerIdx);
6115 }
6116 }
6117}
6118
6119// Split the demanded elts of a HADD/HSUB node between its operands.
6120static void getHorizDemandedElts(EVT VT, const APInt &DemandedElts,
6121 APInt &DemandedLHS, APInt &DemandedRHS) {
6122 int NumLanes = VT.getSizeInBits() / 128;
6123 int NumElts = DemandedElts.getBitWidth();
6124 int NumEltsPerLane = NumElts / NumLanes;
6125 int HalfEltsPerLane = NumEltsPerLane / 2;
6126
6127 DemandedLHS = APInt::getNullValue(NumElts);
6128 DemandedRHS = APInt::getNullValue(NumElts);
6129
6130 // Map DemandedElts to the horizontal operands.
6131 for (int Idx = 0; Idx != NumElts; ++Idx) {
6132 if (!DemandedElts[Idx])
6133 continue;
6134 int LaneIdx = (Idx / NumEltsPerLane) * NumEltsPerLane;
6135 int LocalIdx = Idx % NumEltsPerLane;
6136 if (LocalIdx < HalfEltsPerLane) {
6137 DemandedLHS.setBit(LaneIdx + 2 * LocalIdx + 0);
6138 DemandedLHS.setBit(LaneIdx + 2 * LocalIdx + 1);
6139 } else {
6140 LocalIdx -= HalfEltsPerLane;
6141 DemandedRHS.setBit(LaneIdx + 2 * LocalIdx + 0);
6142 DemandedRHS.setBit(LaneIdx + 2 * LocalIdx + 1);
6143 }
6144 }
6145}
6146
6147/// Calculates the shuffle mask corresponding to the target-specific opcode.
6148/// If the mask could be calculated, returns it in \p Mask, returns the shuffle
6149/// operands in \p Ops, and returns true.
6150/// Sets \p IsUnary to true if only one source is used. Note that this will set
6151/// IsUnary for shuffles which use a single input multiple times, and in those
6152/// cases it will adjust the mask to only have indices within that single input.
6153/// It is an error to call this with non-empty Mask/Ops vectors.
6154static bool getTargetShuffleMask(SDNode *N, MVT VT, bool AllowSentinelZero,
6155 SmallVectorImpl<SDValue> &Ops,
6156 SmallVectorImpl<int> &Mask, bool &IsUnary) {
6157 unsigned NumElems = VT.getVectorNumElements();
6158 unsigned MaskEltSize = VT.getScalarSizeInBits();
6159 SmallVector<uint64_t, 32> RawMask;
6160 APInt RawUndefs;
6161 SDValue ImmN;
6162
6163 assert(Mask.empty() && "getTargetShuffleMask expects an empty Mask vector")((Mask.empty() && "getTargetShuffleMask expects an empty Mask vector"
) ? static_cast<void> (0) : __assert_fail ("Mask.empty() && \"getTargetShuffleMask expects an empty Mask vector\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6163, __PRETTY_FUNCTION__))
;
6164 assert(Ops.empty() && "getTargetShuffleMask expects an empty Ops vector")((Ops.empty() && "getTargetShuffleMask expects an empty Ops vector"
) ? static_cast<void> (0) : __assert_fail ("Ops.empty() && \"getTargetShuffleMask expects an empty Ops vector\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6164, __PRETTY_FUNCTION__))
;
6165
6166 IsUnary = false;
6167 bool IsFakeUnary = false;
6168 switch (N->getOpcode()) {
6169 case X86ISD::BLENDI:
6170 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")((N->getOperand(0).getValueType() == VT && "Unexpected value type"
) ? static_cast<void> (0) : __assert_fail ("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6170, __PRETTY_FUNCTION__))
;
6171 assert(N->getOperand(1).getValueType() == VT && "Unexpected value type")((N->getOperand(1).getValueType() == VT && "Unexpected value type"
) ? static_cast<void> (0) : __assert_fail ("N->getOperand(1).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6171, __PRETTY_FUNCTION__))
;
6172 ImmN = N->getOperand(N->getNumOperands() - 1);
6173 DecodeBLENDMask(NumElems, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
6174 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
6175 break;
6176 case X86ISD::SHUFP:
6177 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")((N->getOperand(0).getValueType() == VT && "Unexpected value type"
) ? static_cast<void> (0) : __assert_fail ("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6177, __PRETTY_FUNCTION__))
;
6178 assert(N->getOperand(1).getValueType() == VT && "Unexpected value type")((N->getOperand(1).getValueType() == VT && "Unexpected value type"
) ? static_cast<void> (0) : __assert_fail ("N->getOperand(1).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6178, __PRETTY_FUNCTION__))
;
6179 ImmN = N->getOperand(N->getNumOperands() - 1);
6180 DecodeSHUFPMask(NumElems, MaskEltSize,
6181 cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
6182 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
6183 break;
6184 case X86ISD::INSERTPS:
6185 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")((N->getOperand(0).getValueType() == VT && "Unexpected value type"
) ? static_cast<void> (0) : __assert_fail ("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6185, __PRETTY_FUNCTION__))
;
6186 assert(N->getOperand(1).getValueType() == VT && "Unexpected value type")((N->getOperand(1).getValueType() == VT && "Unexpected value type"
) ? static_cast<void> (0) : __assert_fail ("N->getOperand(1).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6186, __PRETTY_FUNCTION__))
;
6187 ImmN = N->getOperand(N->getNumOperands() - 1);
6188 DecodeINSERTPSMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
6189 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
6190 break;
6191 case X86ISD::EXTRQI:
6192 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")((N->getOperand(0).getValueType() == VT && "Unexpected value type"
) ? static_cast<void> (0) : __assert_fail ("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6192, __PRETTY_FUNCTION__))
;
6193 if (isa<ConstantSDNode>(N->getOperand(1)) &&
6194 isa<ConstantSDNode>(N->getOperand(2))) {
6195 int BitLen = N->getConstantOperandVal(1);
6196 int BitIdx = N->getConstantOperandVal(2);
6197 DecodeEXTRQIMask(NumElems, MaskEltSize, BitLen, BitIdx, Mask);
6198 IsUnary = true;
6199 }
6200 break;
6201 case X86ISD::INSERTQI:
6202 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")((N->getOperand(0).getValueType() == VT && "Unexpected value type"
) ? static_cast<void> (0) : __assert_fail ("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6202, __PRETTY_FUNCTION__))
;
6203 assert(N->getOperand(1).getValueType() == VT && "Unexpected value type")((N->getOperand(1).getValueType() == VT && "Unexpected value type"
) ? static_cast<void> (0) : __assert_fail ("N->getOperand(1).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6203, __PRETTY_FUNCTION__))
;
6204 if (isa<ConstantSDNode>(N->getOperand(2)) &&
6205 isa<ConstantSDNode>(N->getOperand(3))) {
6206 int BitLen = N->getConstantOperandVal(2);
6207 int BitIdx = N->getConstantOperandVal(3);
6208 DecodeINSERTQIMask(NumElems, MaskEltSize, BitLen, BitIdx, Mask);
6209 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
6210 }
6211 break;
6212 case X86ISD::UNPCKH:
6213 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")((N->getOperand(0).getValueType() == VT && "Unexpected value type"
) ? static_cast<void> (0) : __assert_fail ("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6213, __PRETTY_FUNCTION__))
;
6214 assert(N->getOperand(1).getValueType() == VT && "Unexpected value type")((N->getOperand(1).getValueType() == VT && "Unexpected value type"
) ? static_cast<void> (0) : __assert_fail ("N->getOperand(1).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6214, __PRETTY_FUNCTION__))
;
6215 DecodeUNPCKHMask(NumElems, MaskEltSize, Mask);
6216 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
6217 break;
6218 case X86ISD::UNPCKL:
6219 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")((N->getOperand(0).getValueType() == VT && "Unexpected value type"
) ? static_cast<void> (0) : __assert_fail ("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6219, __PRETTY_FUNCTION__))
;
6220 assert(N->getOperand(1).getValueType() == VT && "Unexpected value type")((N->getOperand(1).getValueType() == VT && "Unexpected value type"
) ? static_cast<void> (0) : __assert_fail ("N->getOperand(1).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6220, __PRETTY_FUNCTION__))
;
6221 DecodeUNPCKLMask(NumElems, MaskEltSize, Mask);
6222 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
6223 break;
6224 case X86ISD::MOVHLPS:
6225 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")((N->getOperand(0).getValueType() == VT && "Unexpected value type"
) ? static_cast<void> (0) : __assert_fail ("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6225, __PRETTY_FUNCTION__))
;
6226 assert(N->getOperand(1).getValueType() == VT && "Unexpected value type")((N->getOperand(1).getValueType() == VT && "Unexpected value type"
) ? static_cast<void> (0) : __assert_fail ("N->getOperand(1).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6226, __PRETTY_FUNCTION__))
;
6227 DecodeMOVHLPSMask(NumElems, Mask);
6228 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
6229 break;
6230 case X86ISD::MOVLHPS:
6231 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")((N->getOperand(0).getValueType() == VT && "Unexpected value type"
) ? static_cast<void> (0) : __assert_fail ("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6231, __PRETTY_FUNCTION__))
;
6232 assert(N->getOperand(1).getValueType() == VT && "Unexpected value type")((N->getOperand(1).getValueType() == VT && "Unexpected value type"
) ? static_cast<void> (0) : __assert_fail ("N->getOperand(1).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6232, __PRETTY_FUNCTION__))
;
6233 DecodeMOVLHPSMask(NumElems, Mask);
6234 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
6235 break;
6236 case X86ISD::PALIGNR:
6237 assert(VT.getScalarType() == MVT::i8 && "Byte vector expected")((VT.getScalarType() == MVT::i8 && "Byte vector expected"
) ? static_cast<void> (0) : __assert_fail ("VT.getScalarType() == MVT::i8 && \"Byte vector expected\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6237, __PRETTY_FUNCTION__))
;
6238 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")((N->getOperand(0).getValueType() == VT && "Unexpected value type"
) ? static_cast<void> (0) : __assert_fail ("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6238, __PRETTY_FUNCTION__))
;
6239 assert(N->getOperand(1).getValueType() == VT && "Unexpected value type")((N->getOperand(1).getValueType() == VT && "Unexpected value type"
) ? static_cast<void> (0) : __assert_fail ("N->getOperand(1).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6239, __PRETTY_FUNCTION__))
;
6240 ImmN = N->getOperand(N->getNumOperands() - 1);
6241 DecodePALIGNRMask(NumElems, cast<ConstantSDNode>(ImmN)->getZExtValue(),
6242 Mask);
6243 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
6244 Ops.push_back(N->getOperand(1));
6245 Ops.push_back(N->getOperand(0));
6246 break;
6247 case X86ISD::VSHLDQ:
6248 assert(VT.getScalarType() == MVT::i8 && "Byte vector expected")((VT.getScalarType() == MVT::i8 && "Byte vector expected"
) ? static_cast<void> (0) : __assert_fail ("VT.getScalarType() == MVT::i8 && \"Byte vector expected\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6248, __PRETTY_FUNCTION__))
;
6249 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")((N->getOperand(0).getValueType() == VT && "Unexpected value type"
) ? static_cast<void> (0) : __assert_fail ("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6249, __PRETTY_FUNCTION__))
;
6250 ImmN = N->getOperand(N->getNumOperands() - 1);
6251 DecodePSLLDQMask(NumElems, cast<ConstantSDNode>(ImmN)->getZExtValue(),
6252 Mask);
6253 IsUnary = true;
6254 break;
6255 case X86ISD::VSRLDQ:
6256 assert(VT.getScalarType() == MVT::i8 && "Byte vector expected")((VT.getScalarType() == MVT::i8 && "Byte vector expected"
) ? static_cast<void> (0) : __assert_fail ("VT.getScalarType() == MVT::i8 && \"Byte vector expected\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6256, __PRETTY_FUNCTION__))
;
6257 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")((N->getOperand(0).getValueType() == VT && "Unexpected value type"
) ? static_cast<void> (0) : __assert_fail ("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6257, __PRETTY_FUNCTION__))
;
6258 ImmN = N->getOperand(N->getNumOperands() - 1);
6259 DecodePSRLDQMask(NumElems, cast<ConstantSDNode>(ImmN)->getZExtValue(),
6260 Mask);
6261 IsUnary = true;
6262 break;
6263 case X86ISD::PSHUFD:
6264 case X86ISD::VPERMILPI:
6265 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")((N->getOperand(0).getValueType() == VT && "Unexpected value type"
) ? static_cast<void> (0) : __assert_fail ("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6265, __PRETTY_FUNCTION__))
;
6266 ImmN = N->getOperand(N->getNumOperands() - 1);
6267 DecodePSHUFMask(NumElems, MaskEltSize,
6268 cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
6269 IsUnary = true;
6270 break;
6271 case X86ISD::PSHUFHW:
6272 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")((N->getOperand(0).getValueType() == VT && "Unexpected value type"
) ? static_cast<void> (0) : __assert_fail ("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6272, __PRETTY_FUNCTION__))
;
6273 ImmN = N->getOperand(N->getNumOperands() - 1);
6274 DecodePSHUFHWMask(NumElems, cast<ConstantSDNode>(ImmN)->getZExtValue(),
6275 Mask);
6276 IsUnary = true;
6277 break;
6278 case X86ISD::PSHUFLW:
6279 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")((N->getOperand(0).getValueType() == VT && "Unexpected value type"
) ? static_cast<void> (0) : __assert_fail ("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6279, __PRETTY_FUNCTION__))
;
6280 ImmN = N->getOperand(N->getNumOperands() - 1);
6281 DecodePSHUFLWMask(NumElems, cast<ConstantSDNode>(ImmN)->getZExtValue(),
6282 Mask);
6283 IsUnary = true;
6284 break;
6285 case X86ISD::VZEXT_MOVL:
6286 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")((N->getOperand(0).getValueType() == VT && "Unexpected value type"
) ? static_cast<void> (0) : __assert_fail ("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6286, __PRETTY_FUNCTION__))
;
6287 DecodeZeroMoveLowMask(NumElems, Mask);
6288 IsUnary = true;
6289 break;
6290 case X86ISD::VBROADCAST: {
6291 SDValue N0 = N->getOperand(0);
6292 // See if we're broadcasting from index 0 of an EXTRACT_SUBVECTOR. If so,
6293 // add the pre-extracted value to the Ops vector.
6294 if (N0.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
6295 N0.getOperand(0).getValueType() == VT &&
6296 N0.getConstantOperandVal(1) == 0)
6297 Ops.push_back(N0.getOperand(0));
6298
6299 // We only decode broadcasts of same-sized vectors, unless the broadcast
6300 // came from an extract from the original width. If we found one, we
6301 // pushed it the Ops vector above.
6302 if (N0.getValueType() == VT || !Ops.empty()) {
6303 DecodeVectorBroadcast(NumElems, Mask);
6304 IsUnary = true;
6305 break;
6306 }
6307 return false;
6308 }
6309 case X86ISD::VPERMILPV: {
6310 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")((N->getOperand(0).getValueType() == VT && "Unexpected value type"
) ? static_cast<void> (0) : __assert_fail ("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6310, __PRETTY_FUNCTION__))
;
6311 IsUnary = true;
6312 SDValue MaskNode = N->getOperand(1);
6313 if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask,
6314 RawUndefs)) {
6315 DecodeVPERMILPMask(NumElems, MaskEltSize, RawMask, RawUndefs, Mask);
6316 break;
6317 }
6318 return false;
6319 }
6320 case X86ISD::PSHUFB: {
6321 assert(VT.getScalarType() == MVT::i8 && "Byte vector expected")((VT.getScalarType() == MVT::i8 && "Byte vector expected"
) ? static_cast<void> (0) : __assert_fail ("VT.getScalarType() == MVT::i8 && \"Byte vector expected\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6321, __PRETTY_FUNCTION__))
;
6322 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")((N->getOperand(0).getValueType() == VT && "Unexpected value type"
) ? static_cast<void> (0) : __assert_fail ("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6322, __PRETTY_FUNCTION__))
;
6323 assert(N->getOperand(1).getValueType() == VT && "Unexpected value type")((N->getOperand(1).getValueType() == VT && "Unexpected value type"
) ? static_cast<void> (0) : __assert_fail ("N->getOperand(1).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6323, __PRETTY_FUNCTION__))
;
6324 IsUnary = true;
6325 SDValue MaskNode = N->getOperand(1);
6326 if (getTargetShuffleMaskIndices(MaskNode, 8, RawMask, RawUndefs)) {
6327 DecodePSHUFBMask(RawMask, RawUndefs, Mask);
6328 break;
6329 }
6330 return false;
6331 }
6332 case X86ISD::VPERMI:
6333 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")((N->getOperand(0).getValueType() == VT && "Unexpected value type"
) ? static_cast<void> (0) : __assert_fail ("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6333, __PRETTY_FUNCTION__))
;
6334 ImmN = N->getOperand(N->getNumOperands() - 1);
6335 DecodeVPERMMask(NumElems, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
6336 IsUnary = true;
6337 break;
6338 case X86ISD::MOVSS:
6339 case X86ISD::MOVSD:
6340 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")((N->getOperand(0).getValueType() == VT && "Unexpected value type"
) ? static_cast<void> (0) : __assert_fail ("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6340, __PRETTY_FUNCTION__))
;
6341 assert(N->getOperand(1).getValueType() == VT && "Unexpected value type")((N->getOperand(1).getValueType() == VT && "Unexpected value type"
) ? static_cast<void> (0) : __assert_fail ("N->getOperand(1).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6341, __PRETTY_FUNCTION__))
;
6342 DecodeScalarMoveMask(NumElems, /* IsLoad */ false, Mask);
6343 break;
6344 case X86ISD::VPERM2X128:
6345 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")((N->getOperand(0).getValueType() == VT && "Unexpected value type"
) ? static_cast<void> (0) : __assert_fail ("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6345, __PRETTY_FUNCTION__))
;
6346 assert(N->getOperand(1).getValueType() == VT && "Unexpected value type")((N->getOperand(1).getValueType() == VT && "Unexpected value type"
) ? static_cast<void> (0) : __assert_fail ("N->getOperand(1).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6346, __PRETTY_FUNCTION__))
;
6347 ImmN = N->getOperand(N->getNumOperands() - 1);
6348 DecodeVPERM2X128Mask(NumElems, cast<ConstantSDNode>(ImmN)->getZExtValue(),
6349 Mask);
6350 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
6351 break;
6352 case X86ISD::SHUF128:
6353 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")((N->getOperand(0).getValueType() == VT && "Unexpected value type"
) ? static_cast<void> (0) : __assert_fail ("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6353, __PRETTY_FUNCTION__))
;
6354 assert(N->getOperand(1).getValueType() == VT && "Unexpected value type")((N->getOperand(1).getValueType() == VT && "Unexpected value type"
) ? static_cast<void> (0) : __assert_fail ("N->getOperand(1).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6354, __PRETTY_FUNCTION__))
;
6355 ImmN = N->getOperand(N->getNumOperands() - 1);
6356 decodeVSHUF64x2FamilyMask(NumElems, MaskEltSize,
6357 cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
6358 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
6359 break;
6360 case X86ISD::MOVSLDUP:
6361 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")((N->getOperand(0).getValueType() == VT && "Unexpected value type"
) ? static_cast<void> (0) : __assert_fail ("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6361, __PRETTY_FUNCTION__))
;
6362 DecodeMOVSLDUPMask(NumElems, Mask);
6363 IsUnary = true;
6364 break;
6365 case X86ISD::MOVSHDUP:
6366 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")((N->getOperand(0).getValueType() == VT && "Unexpected value type"
) ? static_cast<void> (0) : __assert_fail ("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6366, __PRETTY_FUNCTION__))
;
6367 DecodeMOVSHDUPMask(NumElems, Mask);
6368 IsUnary = true;
6369 break;
6370 case X86ISD::MOVDDUP:
6371 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")((N->getOperand(0).getValueType() == VT && "Unexpected value type"
) ? static_cast<void> (0) : __assert_fail ("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6371, __PRETTY_FUNCTION__))
;
6372 DecodeMOVDDUPMask(NumElems, Mask);
6373 IsUnary = true;
6374 break;
6375 case X86ISD::VPERMIL2: {
6376 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")((N->getOperand(0).getValueType() == VT && "Unexpected value type"
) ? static_cast<void> (0) : __assert_fail ("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6376, __PRETTY_FUNCTION__))
;
6377 assert(N->getOperand(1).getValueType() == VT && "Unexpected value type")((N->getOperand(1).getValueType() == VT && "Unexpected value type"
) ? static_cast<void> (0) : __assert_fail ("N->getOperand(1).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6377, __PRETTY_FUNCTION__))
;
6378 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
6379 SDValue MaskNode = N->getOperand(2);
6380 SDValue CtrlNode = N->getOperand(3);
6381 if (ConstantSDNode *CtrlOp = dyn_cast<ConstantSDNode>(CtrlNode)) {
6382 unsigned CtrlImm = CtrlOp->getZExtValue();
6383 if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask,
6384 RawUndefs)) {
6385 DecodeVPERMIL2PMask(NumElems, MaskEltSize, CtrlImm, RawMask, RawUndefs,
6386 Mask);
6387 break;
6388 }
6389 }
6390 return false;
6391 }
6392 case X86ISD::VPPERM: {
6393 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")((N->getOperand(0).getValueType() == VT && "Unexpected value type"
) ? static_cast<void> (0) : __assert_fail ("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6393, __PRETTY_FUNCTION__))
;
6394 assert(N->getOperand(1).getValueType() == VT && "Unexpected value type")((N->getOperand(1).getValueType() == VT && "Unexpected value type"
) ? static_cast<void> (0) : __assert_fail ("N->getOperand(1).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6394, __PRETTY_FUNCTION__))
;
6395 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
6396 SDValue MaskNode = N->getOperand(2);
6397 if (getTargetShuffleMaskIndices(MaskNode, 8, RawMask, RawUndefs)) {
6398 DecodeVPPERMMask(RawMask, RawUndefs, Mask);
6399 break;
6400 }
6401 return false;
6402 }
6403 case X86ISD::VPERMV: {
6404 assert(N->getOperand(1).getValueType() == VT && "Unexpected value type")((N->getOperand(1).getValueType() == VT && "Unexpected value type"
) ? static_cast<void> (0) : __assert_fail ("N->getOperand(1).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6404, __PRETTY_FUNCTION__))
;
6405 IsUnary = true;
6406 // Unlike most shuffle nodes, VPERMV's mask operand is operand 0.
6407 Ops.push_back(N->getOperand(1));
6408 SDValue MaskNode = N->getOperand(0);
6409 if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask,
6410 RawUndefs)) {
6411 DecodeVPERMVMask(RawMask, RawUndefs, Mask);
6412 break;
6413 }
6414 return false;
6415 }
6416 case X86ISD::VPERMV3: {
6417 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")((N->getOperand(0).getValueType() == VT && "Unexpected value type"
) ? static_cast<void> (0) : __assert_fail ("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6417, __PRETTY_FUNCTION__))
;
6418 assert(N->getOperand(2).getValueType() == VT && "Unexpected value type")((N->getOperand(2).getValueType() == VT && "Unexpected value type"
) ? static_cast<void> (0) : __assert_fail ("N->getOperand(2).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6418, __PRETTY_FUNCTION__))
;
6419 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(2);
6420 // Unlike most shuffle nodes, VPERMV3's mask operand is the middle one.
6421 Ops.push_back(N->getOperand(0));
6422 Ops.push_back(N->getOperand(2));
6423 SDValue MaskNode = N->getOperand(1);
6424 if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask,
6425 RawUndefs)) {
6426 DecodeVPERMV3Mask(RawMask, RawUndefs, Mask);
6427 break;
6428 }
6429 return false;
6430 }
6431 default: llvm_unreachable("unknown target shuffle node")::llvm::llvm_unreachable_internal("unknown target shuffle node"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6431)
;
6432 }
6433
6434 // Empty mask indicates the decode failed.
6435 if (Mask.empty())
6436 return false;
6437
6438 // Check if we're getting a shuffle mask with zero'd elements.
6439 if (!AllowSentinelZero)
6440 if (any_of(Mask, [](int M) { return M == SM_SentinelZero; }))
6441 return false;
6442
6443 // If we have a fake unary shuffle, the shuffle mask is spread across two
6444 // inputs that are actually the same node. Re-map the mask to always point
6445 // into the first input.
6446 if (IsFakeUnary)
6447 for (int &M : Mask)
6448 if (M >= (int)Mask.size())
6449 M -= Mask.size();
6450
6451 // If we didn't already add operands in the opcode-specific code, default to
6452 // adding 1 or 2 operands starting at 0.
6453 if (Ops.empty()) {
6454 Ops.push_back(N->getOperand(0));
6455 if (!IsUnary || IsFakeUnary)
6456 Ops.push_back(N->getOperand(1));
6457 }
6458
6459 return true;
6460}
6461
6462/// Check a target shuffle mask's inputs to see if we can set any values to
6463/// SM_SentinelZero - this is for elements that are known to be zero
6464/// (not just zeroable) from their inputs.
6465/// Returns true if the target shuffle mask was decoded.
6466static bool setTargetShuffleZeroElements(SDValue N,
6467 SmallVectorImpl<int> &Mask,
6468 SmallVectorImpl<SDValue> &Ops) {
6469 bool IsUnary;
6470 if (!isTargetShuffle(N.getOpcode()))
6471 return false;
6472
6473 MVT VT = N.getSimpleValueType();
6474 if (!getTargetShuffleMask(N.getNode(), VT, true, Ops, Mask, IsUnary))
6475 return false;
6476
6477 SDValue V1 = Ops[0];
6478 SDValue V2 = IsUnary ? V1 : Ops[1];
6479
6480 V1 = peekThroughBitcasts(V1);
6481 V2 = peekThroughBitcasts(V2);
6482
6483 assert((VT.getSizeInBits() % Mask.size()) == 0 &&(((VT.getSizeInBits() % Mask.size()) == 0 && "Illegal split of shuffle value type"
) ? static_cast<void> (0) : __assert_fail ("(VT.getSizeInBits() % Mask.size()) == 0 && \"Illegal split of shuffle value type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6484, __PRETTY_FUNCTION__))
6484 "Illegal split of shuffle value type")(((VT.getSizeInBits() % Mask.size()) == 0 && "Illegal split of shuffle value type"
) ? static_cast<void> (0) : __assert_fail ("(VT.getSizeInBits() % Mask.size()) == 0 && \"Illegal split of shuffle value type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6484, __PRETTY_FUNCTION__))
;
6485 unsigned EltSizeInBits = VT.getSizeInBits() / Mask.size();
6486
6487 // Extract known constant input data.
6488 APInt UndefSrcElts[2];
6489 SmallVector<APInt, 32> SrcEltBits[2];
6490 bool IsSrcConstant[2] = {
6491 getTargetConstantBitsFromNode(V1, EltSizeInBits, UndefSrcElts[0],
6492 SrcEltBits[0], true, false),
6493 getTargetConstantBitsFromNode(V2, EltSizeInBits, UndefSrcElts[1],
6494 SrcEltBits[1], true, false)};
6495
6496 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6497 int M = Mask[i];
6498
6499 // Already decoded as SM_SentinelZero / SM_SentinelUndef.
6500 if (M < 0)
6501 continue;
6502
6503 // Determine shuffle input and normalize the mask.
6504 unsigned SrcIdx = M / Size;
6505 SDValue V = M < Size ? V1 : V2;
6506 M %= Size;
6507
6508 // We are referencing an UNDEF input.
6509 if (V.isUndef()) {
6510 Mask[i] = SM_SentinelUndef;
6511 continue;
6512 }
6513
6514 // SCALAR_TO_VECTOR - only the first element is defined, and the rest UNDEF.
6515 // TODO: We currently only set UNDEF for integer types - floats use the same
6516 // registers as vectors and many of the scalar folded loads rely on the
6517 // SCALAR_TO_VECTOR pattern.
6518 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6519 (Size % V.getValueType().getVectorNumElements()) == 0) {
6520 int Scale = Size / V.getValueType().getVectorNumElements();
6521 int Idx = M / Scale;
6522 if (Idx != 0 && !VT.isFloatingPoint())
6523 Mask[i] = SM_SentinelUndef;
6524 else if (Idx == 0 && X86::isZeroNode(V.getOperand(0)))
6525 Mask[i] = SM_SentinelZero;
6526 continue;
6527 }
6528
6529 // Attempt to extract from the source's constant bits.
6530 if (IsSrcConstant[SrcIdx]) {
6531 if (UndefSrcElts[SrcIdx][M])
6532 Mask[i] = SM_SentinelUndef;
6533 else if (SrcEltBits[SrcIdx][M] == 0)
6534 Mask[i] = SM_SentinelZero;
6535 }
6536 }
6537
6538 assert(VT.getVectorNumElements() == Mask.size() &&((VT.getVectorNumElements() == Mask.size() && "Different mask size from vector size!"
) ? static_cast<void> (0) : __assert_fail ("VT.getVectorNumElements() == Mask.size() && \"Different mask size from vector size!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6539, __PRETTY_FUNCTION__))
6539 "Different mask size from vector size!")((VT.getVectorNumElements() == Mask.size() && "Different mask size from vector size!"
) ? static_cast<void> (0) : __assert_fail ("VT.getVectorNumElements() == Mask.size() && \"Different mask size from vector size!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6539, __PRETTY_FUNCTION__))
;
6540 return true;
6541}
6542
6543// Forward declaration (for getFauxShuffleMask recursive check).
6544static bool resolveTargetShuffleInputs(SDValue Op,
6545 SmallVectorImpl<SDValue> &Inputs,
6546 SmallVectorImpl<int> &Mask,
6547 SelectionDAG &DAG);
6548
6549// Attempt to decode ops that could be represented as a shuffle mask.
6550// The decoded shuffle mask may contain a different number of elements to the
6551// destination value type.
6552static bool getFauxShuffleMask(SDValue N, SmallVectorImpl<int> &Mask,
6553 SmallVectorImpl<SDValue> &Ops,
6554 SelectionDAG &DAG) {
6555 Mask.clear();
6556 Ops.clear();
6557
6558 MVT VT = N.getSimpleValueType();
6559 unsigned NumElts = VT.getVectorNumElements();
6560 unsigned NumSizeInBits = VT.getSizeInBits();
6561 unsigned NumBitsPerElt = VT.getScalarSizeInBits();
6562 if ((NumBitsPerElt % 8) != 0 || (NumSizeInBits % 8) != 0)
6563 return false;
6564
6565 unsigned Opcode = N.getOpcode();
6566 switch (Opcode) {
6567 case ISD::VECTOR_SHUFFLE: {
6568 // Don't treat ISD::VECTOR_SHUFFLE as a target shuffle so decode it here.
6569 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(N)->getMask();
6570 if (isUndefOrInRange(ShuffleMask, 0, 2 * NumElts)) {
6571 Mask.append(ShuffleMask.begin(), ShuffleMask.end());
6572 Ops.push_back(N.getOperand(0));
6573 Ops.push_back(N.getOperand(1));
6574 return true;
6575 }
6576 return false;
6577 }
6578 case ISD::AND:
6579 case X86ISD::ANDNP: {
6580 // Attempt to decode as a per-byte mask.
6581 APInt UndefElts;
6582 SmallVector<APInt, 32> EltBits;
6583 SDValue N0 = N.getOperand(0);
6584 SDValue N1 = N.getOperand(1);
6585 bool IsAndN = (X86ISD::ANDNP == Opcode);
6586 uint64_t ZeroMask = IsAndN ? 255 : 0;
6587 if (!getTargetConstantBitsFromNode(IsAndN ? N0 : N1, 8, UndefElts, EltBits))
6588 return false;
6589 for (int i = 0, e = (int)EltBits.size(); i != e; ++i) {
6590 if (UndefElts[i]) {
6591 Mask.push_back(SM_SentinelUndef);
6592 continue;
6593 }
6594 uint64_t ByteBits = EltBits[i].getZExtValue();
6595 if (ByteBits != 0 && ByteBits != 255)
6596 return false;
6597 Mask.push_back(ByteBits == ZeroMask ? SM_SentinelZero : i);
6598 }
6599 Ops.push_back(IsAndN ? N1 : N0);
6600 return true;
6601 }
6602 case ISD::OR: {
6603 // Handle OR(SHUFFLE,SHUFFLE) case where one source is zero and the other
6604 // is a valid shuffle index.
6605 SDValue N0 = peekThroughOneUseBitcasts(N.getOperand(0));
6606 SDValue N1 = peekThroughOneUseBitcasts(N.getOperand(1));
6607 if (!N0.getValueType().isVector() || !N1.getValueType().isVector())
6608 return false;
6609 SmallVector<int, 64> SrcMask0, SrcMask1;
6610 SmallVector<SDValue, 2> SrcInputs0, SrcInputs1;
6611 if (!resolveTargetShuffleInputs(N0, SrcInputs0, SrcMask0, DAG) ||
6612 !resolveTargetShuffleInputs(N1, SrcInputs1, SrcMask1, DAG))
6613 return false;
6614 int MaskSize = std::max(SrcMask0.size(), SrcMask1.size());
6615 SmallVector<int, 64> Mask0, Mask1;
6616 scaleShuffleMask<int>(MaskSize / SrcMask0.size(), SrcMask0, Mask0);
6617 scaleShuffleMask<int>(MaskSize / SrcMask1.size(), SrcMask1, Mask1);
6618 for (int i = 0; i != MaskSize; ++i) {
6619 if (Mask0[i] == SM_SentinelUndef && Mask1[i] == SM_SentinelUndef)
6620 Mask.push_back(SM_SentinelUndef);
6621 else if (Mask0[i] == SM_SentinelZero && Mask1[i] == SM_SentinelZero)
6622 Mask.push_back(SM_SentinelZero);
6623 else if (Mask1[i] == SM_SentinelZero)
6624 Mask.push_back(Mask0[i]);
6625 else if (Mask0[i] == SM_SentinelZero)
6626 Mask.push_back(Mask1[i] + (MaskSize * SrcInputs0.size()));
6627 else
6628 return false;
6629 }
6630 for (SDValue &Op : SrcInputs0)
6631 Ops.push_back(Op);
6632 for (SDValue &Op : SrcInputs1)
6633 Ops.push_back(Op);
6634 return true;
6635 }
6636 case ISD::INSERT_SUBVECTOR: {
6637 // Handle INSERT_SUBVECTOR(SRC0, SHUFFLE(SRC1)).
6638 SDValue Src = N.getOperand(0);
6639 SDValue Sub = N.getOperand(1);
6640 EVT SubVT = Sub.getValueType();
6641 unsigned NumSubElts = SubVT.getVectorNumElements();
6642 if (!isa<ConstantSDNode>(N.getOperand(2)) ||
6643 !N->isOnlyUserOf(Sub.getNode()))
6644 return false;
6645 SmallVector<int, 64> SubMask;
6646 SmallVector<SDValue, 2> SubInputs;
6647 if (!resolveTargetShuffleInputs(peekThroughOneUseBitcasts(Sub), SubInputs,
6648 SubMask, DAG))
6649 return false;
6650 int InsertIdx = N.getConstantOperandVal(2);
6651 if (SubMask.size() != NumSubElts) {
6652 assert(((SubMask.size() % NumSubElts) == 0 ||((((SubMask.size() % NumSubElts) == 0 || (NumSubElts % SubMask
.size()) == 0) && "Illegal submask scale") ? static_cast
<void> (0) : __assert_fail ("((SubMask.size() % NumSubElts) == 0 || (NumSubElts % SubMask.size()) == 0) && \"Illegal submask scale\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6653, __PRETTY_FUNCTION__))
6653 (NumSubElts % SubMask.size()) == 0) && "Illegal submask scale")((((SubMask.size() % NumSubElts) == 0 || (NumSubElts % SubMask
.size()) == 0) && "Illegal submask scale") ? static_cast
<void> (0) : __assert_fail ("((SubMask.size() % NumSubElts) == 0 || (NumSubElts % SubMask.size()) == 0) && \"Illegal submask scale\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6653, __PRETTY_FUNCTION__))
;
6654 if ((NumSubElts % SubMask.size()) == 0) {
6655 int Scale = NumSubElts / SubMask.size();
6656 SmallVector<int,64> ScaledSubMask;
6657 scaleShuffleMask<int>(Scale, SubMask, ScaledSubMask);
6658 SubMask = ScaledSubMask;
6659 } else {
6660 int Scale = SubMask.size() / NumSubElts;
6661 NumSubElts = SubMask.size();
6662 NumElts *= Scale;
6663 InsertIdx *= Scale;
6664 }
6665 }
6666 Ops.push_back(Src);
6667 for (SDValue &SubInput : SubInputs) {
6668 EVT SubSVT = SubInput.getValueType().getScalarType();
6669 EVT AltVT = EVT::getVectorVT(*DAG.getContext(), SubSVT,
6670 NumSizeInBits / SubSVT.getSizeInBits());
6671 Ops.push_back(DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), AltVT,
6672 DAG.getUNDEF(AltVT), SubInput,
6673 DAG.getIntPtrConstant(0, SDLoc(N))));
6674 }
6675 for (int i = 0; i != (int)NumElts; ++i)
6676 Mask.push_back(i);
6677 for (int i = 0; i != (int)NumSubElts; ++i) {
6678 int M = SubMask[i];
6679 if (0 <= M) {
6680 int InputIdx = M / NumSubElts;
6681 M = (NumElts * (1 + InputIdx)) + (M % NumSubElts);
6682 }
6683 Mask[i + InsertIdx] = M;
6684 }
6685 return true;
6686 }
6687 case ISD::SCALAR_TO_VECTOR: {
6688 // Match against a scalar_to_vector of an extract from a vector,
6689 // for PEXTRW/PEXTRB we must handle the implicit zext of the scalar.
6690 SDValue N0 = N.getOperand(0);
6691 SDValue SrcExtract;
6692
6693 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6694 N0.getOperand(0).getValueType() == VT) ||
6695 (N0.getOpcode() == X86ISD::PEXTRW &&
6696 N0.getOperand(0).getValueType() == MVT::v8i16) ||
6697 (N0.getOpcode() == X86ISD::PEXTRB &&
6698 N0.getOperand(0).getValueType() == MVT::v16i8)) {
6699 SrcExtract = N0;
6700 }
6701
6702 if (!SrcExtract || !isa<ConstantSDNode>(SrcExtract.getOperand(1)))
6703 return false;
6704
6705 SDValue SrcVec = SrcExtract.getOperand(0);
6706 EVT SrcVT = SrcVec.getValueType();
6707 unsigned NumSrcElts = SrcVT.getVectorNumElements();
6708 unsigned NumZeros = (NumBitsPerElt / SrcVT.getScalarSizeInBits()) - 1;
6709
6710 unsigned SrcIdx = SrcExtract.getConstantOperandVal(1);
6711 if (NumSrcElts <= SrcIdx)
6712 return false;
6713
6714 Ops.push_back(SrcVec);
6715 Mask.push_back(SrcIdx);
6716 Mask.append(NumZeros, SM_SentinelZero);
6717 Mask.append(NumSrcElts - Mask.size(), SM_SentinelUndef);
6718 return true;
6719 }
6720 case X86ISD::PINSRB:
6721 case X86ISD::PINSRW: {
6722 SDValue InVec = N.getOperand(0);
6723 SDValue InScl = N.getOperand(1);
6724 SDValue InIndex = N.getOperand(2);
6725 if (!isa<ConstantSDNode>(InIndex) ||
6726 cast<ConstantSDNode>(InIndex)->getAPIntValue().uge(NumElts))
6727 return false;
6728 uint64_t InIdx = N.getConstantOperandVal(2);
6729
6730 // Attempt to recognise a PINSR*(VEC, 0, Idx) shuffle pattern.
6731 if (X86::isZeroNode(InScl)) {
6732 Ops.push_back(InVec);
6733 for (unsigned i = 0; i != NumElts; ++i)
6734 Mask.push_back(i == InIdx ? SM_SentinelZero : (int)i);
6735 return true;
6736 }
6737
6738 // Attempt to recognise a PINSR*(PEXTR*) shuffle pattern.
6739 // TODO: Expand this to support INSERT_VECTOR_ELT/etc.
6740 unsigned ExOp =
6741 (X86ISD::PINSRB == Opcode ? X86ISD::PEXTRB : X86ISD::PEXTRW);
6742 if (InScl.getOpcode() != ExOp)
6743 return false;
6744
6745 SDValue ExVec = InScl.getOperand(0);
6746 SDValue ExIndex = InScl.getOperand(1);
6747 if (!isa<ConstantSDNode>(ExIndex) ||
6748 cast<ConstantSDNode>(ExIndex)->getAPIntValue().uge(NumElts))
6749 return false;
6750 uint64_t ExIdx = InScl.getConstantOperandVal(1);
6751
6752 Ops.push_back(InVec);
6753 Ops.push_back(ExVec);
6754 for (unsigned i = 0; i != NumElts; ++i)
6755 Mask.push_back(i == InIdx ? NumElts + ExIdx : i);
6756 return true;
6757 }
6758 case X86ISD::PACKSS:
6759 case X86ISD::PACKUS: {
6760 SDValue N0 = N.getOperand(0);
6761 SDValue N1 = N.getOperand(1);
6762 assert(N0.getValueType().getVectorNumElements() == (NumElts / 2) &&((N0.getValueType().getVectorNumElements() == (NumElts / 2) &&
N1.getValueType().getVectorNumElements() == (NumElts / 2) &&
"Unexpected input value type") ? static_cast<void> (0)
: __assert_fail ("N0.getValueType().getVectorNumElements() == (NumElts / 2) && N1.getValueType().getVectorNumElements() == (NumElts / 2) && \"Unexpected input value type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6764, __PRETTY_FUNCTION__))
6763 N1.getValueType().getVectorNumElements() == (NumElts / 2) &&((N0.getValueType().getVectorNumElements() == (NumElts / 2) &&
N1.getValueType().getVectorNumElements() == (NumElts / 2) &&
"Unexpected input value type") ? static_cast<void> (0)
: __assert_fail ("N0.getValueType().getVectorNumElements() == (NumElts / 2) && N1.getValueType().getVectorNumElements() == (NumElts / 2) && \"Unexpected input value type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6764, __PRETTY_FUNCTION__))
6764 "Unexpected input value type")((N0.getValueType().getVectorNumElements() == (NumElts / 2) &&
N1.getValueType().getVectorNumElements() == (NumElts / 2) &&
"Unexpected input value type") ? static_cast<void> (0)
: __assert_fail ("N0.getValueType().getVectorNumElements() == (NumElts / 2) && N1.getValueType().getVectorNumElements() == (NumElts / 2) && \"Unexpected input value type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6764, __PRETTY_FUNCTION__))
;
6765
6766 // If we know input saturation won't happen we can treat this
6767 // as a truncation shuffle.
6768 if (Opcode == X86ISD::PACKSS) {
6769 if ((!N0.isUndef() && DAG.ComputeNumSignBits(N0) <= NumBitsPerElt) ||
6770 (!N1.isUndef() && DAG.ComputeNumSignBits(N1) <= NumBitsPerElt))
6771 return false;
6772 } else {
6773 APInt ZeroMask = APInt::getHighBitsSet(2 * NumBitsPerElt, NumBitsPerElt);
6774 if ((!N0.isUndef() && !DAG.MaskedValueIsZero(N0, ZeroMask)) ||
6775 (!N1.isUndef() && !DAG.MaskedValueIsZero(N1, ZeroMask)))
6776 return false;
6777 }
6778
6779 bool IsUnary = (N0 == N1);
6780
6781 Ops.push_back(N0);
6782 if (!IsUnary)
6783 Ops.push_back(N1);
6784
6785 createPackShuffleMask(VT, Mask, IsUnary);
6786 return true;
6787 }
6788 case X86ISD::VSHLI:
6789 case X86ISD::VSRLI: {
6790 uint64_t ShiftVal = N.getConstantOperandVal(1);
6791 // Out of range bit shifts are guaranteed to be zero.
6792 if (NumBitsPerElt <= ShiftVal) {
6793 Mask.append(NumElts, SM_SentinelZero);
6794 return true;
6795 }
6796
6797 // We can only decode 'whole byte' bit shifts as shuffles.
6798 if ((ShiftVal % 8) != 0)
6799 break;
6800
6801 uint64_t ByteShift = ShiftVal / 8;
6802 unsigned NumBytes = NumSizeInBits / 8;
6803 unsigned NumBytesPerElt = NumBitsPerElt / 8;
6804 Ops.push_back(N.getOperand(0));
6805
6806 // Clear mask to all zeros and insert the shifted byte indices.
6807 Mask.append(NumBytes, SM_SentinelZero);
6808
6809 if (X86ISD::VSHLI == Opcode) {
6810 for (unsigned i = 0; i != NumBytes; i += NumBytesPerElt)
6811 for (unsigned j = ByteShift; j != NumBytesPerElt; ++j)
6812 Mask[i + j] = i + j - ByteShift;
6813 } else {
6814 for (unsigned i = 0; i != NumBytes; i += NumBytesPerElt)
6815 for (unsigned j = ByteShift; j != NumBytesPerElt; ++j)
6816 Mask[i + j - ByteShift] = i + j;
6817 }
6818 return true;
6819 }
6820 case X86ISD::VBROADCAST: {
6821 SDValue Src = N.getOperand(0);
6822 MVT SrcVT = Src.getSimpleValueType();
6823 if (!SrcVT.isVector())
6824 return false;
6825
6826 if (NumSizeInBits != SrcVT.getSizeInBits()) {
6827 assert((NumSizeInBits % SrcVT.getSizeInBits()) == 0 &&(((NumSizeInBits % SrcVT.getSizeInBits()) == 0 && "Illegal broadcast type"
) ? static_cast<void> (0) : __assert_fail ("(NumSizeInBits % SrcVT.getSizeInBits()) == 0 && \"Illegal broadcast type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6828, __PRETTY_FUNCTION__))
6828 "Illegal broadcast type")(((NumSizeInBits % SrcVT.getSizeInBits()) == 0 && "Illegal broadcast type"
) ? static_cast<void> (0) : __assert_fail ("(NumSizeInBits % SrcVT.getSizeInBits()) == 0 && \"Illegal broadcast type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6828, __PRETTY_FUNCTION__))
;
6829 SrcVT = MVT::getVectorVT(SrcVT.getScalarType(),
6830 NumSizeInBits / SrcVT.getScalarSizeInBits());
6831 Src = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), SrcVT,
6832 DAG.getUNDEF(SrcVT), Src,
6833 DAG.getIntPtrConstant(0, SDLoc(N)));
6834 }
6835
6836 Ops.push_back(Src);
6837 Mask.append(NumElts, 0);
6838 return true;
6839 }
6840 case ISD::ZERO_EXTEND:
6841 case ISD::ZERO_EXTEND_VECTOR_INREG:
6842 case ISD::ANY_EXTEND_VECTOR_INREG: {
6843 SDValue Src = N.getOperand(0);
6844 EVT SrcVT = Src.getValueType();
6845
6846 // Extended source must be a simple vector.
6847 if (!SrcVT.isSimple() || (SrcVT.getSizeInBits() % 128) != 0 ||
6848 (SrcVT.getScalarSizeInBits() % 8) != 0)
6849 return false;
6850
6851 unsigned NumSrcBitsPerElt = SrcVT.getScalarSizeInBits();
6852 bool IsAnyExtend = (ISD::ANY_EXTEND_VECTOR_INREG == Opcode);
6853 DecodeZeroExtendMask(NumSrcBitsPerElt, NumBitsPerElt, NumElts, IsAnyExtend,
6854 Mask);
6855
6856 if (NumSizeInBits != SrcVT.getSizeInBits()) {
6857 assert((NumSizeInBits % SrcVT.getSizeInBits()) == 0 &&(((NumSizeInBits % SrcVT.getSizeInBits()) == 0 && "Illegal zero-extension type"
) ? static_cast<void> (0) : __assert_fail ("(NumSizeInBits % SrcVT.getSizeInBits()) == 0 && \"Illegal zero-extension type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6858, __PRETTY_FUNCTION__))
6858 "Illegal zero-extension type")(((NumSizeInBits % SrcVT.getSizeInBits()) == 0 && "Illegal zero-extension type"
) ? static_cast<void> (0) : __assert_fail ("(NumSizeInBits % SrcVT.getSizeInBits()) == 0 && \"Illegal zero-extension type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6858, __PRETTY_FUNCTION__))
;
6859 SrcVT = MVT::getVectorVT(SrcVT.getSimpleVT().getScalarType(),
6860 NumSizeInBits / NumSrcBitsPerElt);
6861 Src = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), SrcVT,
6862 DAG.getUNDEF(SrcVT), Src,
6863 DAG.getIntPtrConstant(0, SDLoc(N)));
6864 }
6865
6866 Ops.push_back(Src);
6867 return true;
6868 }
6869 }
6870
6871 return false;
6872}
6873
6874/// Removes unused shuffle source inputs and adjusts the shuffle mask accordingly.
6875static void resolveTargetShuffleInputsAndMask(SmallVectorImpl<SDValue> &Inputs,
6876 SmallVectorImpl<int> &Mask) {
6877 int MaskWidth = Mask.size();
6878 SmallVector<SDValue, 16> UsedInputs;
6879 for (int i = 0, e = Inputs.size(); i < e; ++i) {
6880 int lo = UsedInputs.size() * MaskWidth;
6881 int hi = lo + MaskWidth;
6882
6883 // Strip UNDEF input usage.
6884 if (Inputs[i].isUndef())
6885 for (int &M : Mask)
6886 if ((lo <= M) && (M < hi))
6887 M = SM_SentinelUndef;
6888
6889 // Check for unused inputs.
6890 if (any_of(Mask, [lo, hi](int i) { return (lo <= i) && (i < hi); })) {
6891 UsedInputs.push_back(Inputs[i]);
6892 continue;
6893 }
6894 for (int &M : Mask)
6895 if (lo <= M)
6896 M -= MaskWidth;
6897 }
6898 Inputs = UsedInputs;
6899}
6900
6901/// Calls setTargetShuffleZeroElements to resolve a target shuffle mask's inputs
6902/// and set the SM_SentinelUndef and SM_SentinelZero values. Then check the
6903/// remaining input indices in case we now have a unary shuffle and adjust the
6904/// inputs accordingly.
6905/// Returns true if the target shuffle mask was decoded.
6906static bool resolveTargetShuffleInputs(SDValue Op,
6907 SmallVectorImpl<SDValue> &Inputs,
6908 SmallVectorImpl<int> &Mask,
6909 SelectionDAG &DAG) {
6910 if (!setTargetShuffleZeroElements(Op, Mask, Inputs))
6911 if (!getFauxShuffleMask(Op, Mask, Inputs, DAG))
6912 return false;
6913
6914 resolveTargetShuffleInputsAndMask(Inputs, Mask);
6915 return true;
6916}
6917
6918/// Returns the scalar element that will make up the ith
6919/// element of the result of the vector shuffle.
6920static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
6921 unsigned Depth) {
6922 if (Depth == 6)
6923 return SDValue(); // Limit search depth.
6924
6925 SDValue V = SDValue(N, 0);
6926 EVT VT = V.getValueType();
6927 unsigned Opcode = V.getOpcode();
6928
6929 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
6930 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
6931 int Elt = SV->getMaskElt(Index);
6932
6933 if (Elt < 0)
6934 return DAG.getUNDEF(VT.getVectorElementType());
6935
6936 unsigned NumElems = VT.getVectorNumElements();
6937 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
6938 : SV->getOperand(1);
6939 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
6940 }
6941
6942 // Recurse into target specific vector shuffles to find scalars.
6943 if (isTargetShuffle(Opcode)) {
6944 MVT ShufVT = V.getSimpleValueType();
6945 MVT ShufSVT = ShufVT.getVectorElementType();
6946 int NumElems = (int)ShufVT.getVectorNumElements();
6947 SmallVector<int, 16> ShuffleMask;
6948 SmallVector<SDValue, 16> ShuffleOps;
6949 bool IsUnary;
6950
6951 if (!getTargetShuffleMask(N, ShufVT, true, ShuffleOps, ShuffleMask, IsUnary))
6952 return SDValue();
6953
6954 int Elt = ShuffleMask[Index];
6955 if (Elt == SM_SentinelZero)
6956 return ShufSVT.isInteger() ? DAG.getConstant(0, SDLoc(N), ShufSVT)
6957 : DAG.getConstantFP(+0.0, SDLoc(N), ShufSVT);
6958 if (Elt == SM_SentinelUndef)
6959 return DAG.getUNDEF(ShufSVT);
6960
6961 assert(0 <= Elt && Elt < (2*NumElems) && "Shuffle index out of range")((0 <= Elt && Elt < (2*NumElems) && "Shuffle index out of range"
) ? static_cast<void> (0) : __assert_fail ("0 <= Elt && Elt < (2*NumElems) && \"Shuffle index out of range\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 6961, __PRETTY_FUNCTION__))
;
6962 SDValue NewV = (Elt < NumElems) ? ShuffleOps[0] : ShuffleOps[1];
6963 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
6964 Depth+1);
6965 }
6966
6967 // Recurse into insert_subvector base/sub vector to find scalars.
6968 if (Opcode == ISD::INSERT_SUBVECTOR &&
6969 isa<ConstantSDNode>(N->getOperand(2))) {
6970 SDValue Vec = N->getOperand(0);
6971 SDValue Sub = N->getOperand(1);
6972 EVT SubVT = Sub.getValueType();
6973 unsigned NumSubElts = SubVT.getVectorNumElements();
6974 uint64_t SubIdx = N->getConstantOperandVal(2);
6975
6976 if (SubIdx <= Index && Index < (SubIdx + NumSubElts))
6977 return getShuffleScalarElt(Sub.getNode(), Index - SubIdx, DAG, Depth + 1);
6978 return getShuffleScalarElt(Vec.getNode(), Index, DAG, Depth + 1);
6979 }
6980
6981 // Recurse into extract_subvector src vector to find scalars.
6982 if (Opcode == ISD::EXTRACT_SUBVECTOR &&
6983 isa<ConstantSDNode>(N->getOperand(1))) {
6984 SDValue Src = N->getOperand(0);
6985 uint64_t SrcIdx = N->getConstantOperandVal(1);
6986 return getShuffleScalarElt(Src.getNode(), Index + SrcIdx, DAG, Depth + 1);
6987 }
6988
6989 // Actual nodes that may contain scalar elements
6990 if (Opcode == ISD::BITCAST) {
6991 V = V.getOperand(0);
6992 EVT SrcVT = V.getValueType();
6993 unsigned NumElems = VT.getVectorNumElements();
6994
6995 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
6996 return SDValue();
6997 }
6998
6999 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7000 return (Index == 0) ? V.getOperand(0)
7001 : DAG.getUNDEF(VT.getVectorElementType());
7002
7003 if (V.getOpcode() == ISD::BUILD_VECTOR)
7004 return V.getOperand(Index);
7005
7006 return SDValue();
7007}
7008
7009// Use PINSRB/PINSRW/PINSRD to create a build vector.
7010static SDValue LowerBuildVectorAsInsert(SDValue Op, unsigned NonZeros,
7011 unsigned NumNonZero, unsigned NumZero,
7012 SelectionDAG &DAG,
7013 const X86Subtarget &Subtarget) {
7014 MVT VT = Op.getSimpleValueType();
7015 unsigned NumElts = VT.getVectorNumElements();
7016 assert(((VT == MVT::v8i16 && Subtarget.hasSSE2()) ||((((VT == MVT::v8i16 && Subtarget.hasSSE2()) || ((VT ==
MVT::v16i8 || VT == MVT::v4i32) && Subtarget.hasSSE41
())) && "Illegal vector insertion") ? static_cast<
void> (0) : __assert_fail ("((VT == MVT::v8i16 && Subtarget.hasSSE2()) || ((VT == MVT::v16i8 || VT == MVT::v4i32) && Subtarget.hasSSE41())) && \"Illegal vector insertion\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 7018, __PRETTY_FUNCTION__))
7017 ((VT == MVT::v16i8 || VT == MVT::v4i32) && Subtarget.hasSSE41())) &&((((VT == MVT::v8i16 && Subtarget.hasSSE2()) || ((VT ==
MVT::v16i8 || VT == MVT::v4i32) && Subtarget.hasSSE41
())) && "Illegal vector insertion") ? static_cast<
void> (0) : __assert_fail ("((VT == MVT::v8i16 && Subtarget.hasSSE2()) || ((VT == MVT::v16i8 || VT == MVT::v4i32) && Subtarget.hasSSE41())) && \"Illegal vector insertion\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 7018, __PRETTY_FUNCTION__))
7018 "Illegal vector insertion")((((VT == MVT::v8i16 && Subtarget.hasSSE2()) || ((VT ==
MVT::v16i8 || VT == MVT::v4i32) && Subtarget.hasSSE41
())) && "Illegal vector insertion") ? static_cast<
void> (0) : __assert_fail ("((VT == MVT::v8i16 && Subtarget.hasSSE2()) || ((VT == MVT::v16i8 || VT == MVT::v4i32) && Subtarget.hasSSE41())) && \"Illegal vector insertion\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 7018, __PRETTY_FUNCTION__))
;
7019
7020 SDLoc dl(Op);
7021 SDValue V;
7022 bool First = true;
7023
7024 for (unsigned i = 0; i < NumElts; ++i) {
7025 bool IsNonZero = (NonZeros & (1 << i)) != 0;
7026 if (!IsNonZero)
7027 continue;
7028
7029 // If the build vector contains zeros or our first insertion is not the
7030 // first index then insert into zero vector to break any register
7031 // dependency else use SCALAR_TO_VECTOR/VZEXT_MOVL.
7032 if (First) {
7033 First = false;
7034 if (NumZero || 0 != i)
7035 V = getZeroVector(VT, Subtarget, DAG, dl);
7036 else {
7037 assert(0 == i && "Expected insertion into zero-index")((0 == i && "Expected insertion into zero-index") ? static_cast
<void> (0) : __assert_fail ("0 == i && \"Expected insertion into zero-index\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 7037, __PRETTY_FUNCTION__))
;
7038 V = DAG.getAnyExtOrTrunc(Op.getOperand(i), dl, MVT::i32);
7039 V = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, V);
7040 V = DAG.getNode(X86ISD::VZEXT_MOVL, dl, MVT::v4i32, V);
7041 V = DAG.getBitcast(VT, V);
7042 continue;
7043 }
7044 }
7045 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V, Op.getOperand(i),
7046 DAG.getIntPtrConstant(i, dl));
7047 }
7048
7049 return V;
7050}
7051
7052/// Custom lower build_vector of v16i8.
7053static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
7054 unsigned NumNonZero, unsigned NumZero,
7055 SelectionDAG &DAG,
7056 const X86Subtarget &Subtarget) {
7057 if (NumNonZero > 8 && !Subtarget.hasSSE41())
7058 return SDValue();
7059
7060 // SSE4.1 - use PINSRB to insert each byte directly.
7061 if (Subtarget.hasSSE41())
7062 return LowerBuildVectorAsInsert(Op, NonZeros, NumNonZero, NumZero, DAG,
7063 Subtarget);
7064
7065 SDLoc dl(Op);
7066 SDValue V;
7067 bool First = true;
7068
7069 // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
7070 for (unsigned i = 0; i < 16; ++i) {
7071 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
7072 if (ThisIsNonZero && First) {
7073 if (NumZero)
7074 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
7075 else
7076 V = DAG.getUNDEF(MVT::v8i16);
7077 First = false;
7078 }
7079
7080 if ((i & 1) != 0) {
7081 // FIXME: Investigate extending to i32 instead of just i16.
7082 // FIXME: Investigate combining the first 4 bytes as a i32 instead.
7083 SDValue ThisElt, LastElt;
7084 bool LastIsNonZero = (NonZeros & (1 << (i - 1))) != 0;
7085 if (LastIsNonZero) {
7086 LastElt =
7087 DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i - 1));
7088 }
7089 if (ThisIsNonZero) {
7090 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
7091 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16, ThisElt,
7092 DAG.getConstant(8, dl, MVT::i8));
7093 if (LastIsNonZero)
7094 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
7095 } else
7096 ThisElt = LastElt;
7097
7098 if (ThisElt) {
7099 if (1 == i) {
7100 V = NumZero ? DAG.getZExtOrTrunc(ThisElt, dl, MVT::i32)
7101 : DAG.getAnyExtOrTrunc(ThisElt, dl, MVT::i32);
7102 V = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, V);
7103 V = DAG.getNode(X86ISD::VZEXT_MOVL, dl, MVT::v4i32, V);
7104 V = DAG.getBitcast(MVT::v8i16, V);
7105 } else {
7106 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
7107 DAG.getIntPtrConstant(i / 2, dl));
7108 }
7109 }
7110 }
7111 }
7112
7113 return DAG.getBitcast(MVT::v16i8, V);
7114}
7115
7116/// Custom lower build_vector of v8i16.
7117static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
7118 unsigned NumNonZero, unsigned NumZero,
7119 SelectionDAG &DAG,
7120 const X86Subtarget &Subtarget) {
7121 if (NumNonZero > 4 && !Subtarget.hasSSE41())
7122 return SDValue();
7123
7124 // Use PINSRW to insert each byte directly.
7125 return LowerBuildVectorAsInsert(Op, NonZeros, NumNonZero, NumZero, DAG,
7126 Subtarget);
7127}
7128
7129/// Custom lower build_vector of v4i32 or v4f32.
7130static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
7131 const X86Subtarget &Subtarget) {
7132 // If this is a splat of a pair of elements, use MOVDDUP (unless the target
7133 // has XOP; in that case defer lowering to potentially use VPERMIL2PS).
7134 // Because we're creating a less complicated build vector here, we may enable
7135 // further folding of the MOVDDUP via shuffle transforms.
7136 if (Subtarget.hasSSE3() && !Subtarget.hasXOP() &&
7137 Op.getOperand(0) == Op.getOperand(2) &&
7138 Op.getOperand(1) == Op.getOperand(3) &&
7139 Op.getOperand(0) != Op.getOperand(1)) {
7140 SDLoc DL(Op);
7141 MVT VT = Op.getSimpleValueType();
7142 MVT EltVT = VT.getVectorElementType();
7143 // Create a new build vector with the first 2 elements followed by undef
7144 // padding, bitcast to v2f64, duplicate, and bitcast back.
7145 SDValue Ops[4] = { Op.getOperand(0), Op.getOperand(1),
7146 DAG.getUNDEF(EltVT), DAG.getUNDEF(EltVT) };
7147 SDValue NewBV = DAG.getBitcast(MVT::v2f64, DAG.getBuildVector(VT, DL, Ops));
7148 SDValue Dup = DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, NewBV);
7149 return DAG.getBitcast(VT, Dup);
7150 }
7151
7152 // Find all zeroable elements.
7153 std::bitset<4> Zeroable, Undefs;
7154 for (int i = 0; i < 4; ++i) {
7155 SDValue Elt = Op.getOperand(i);
7156 Undefs[i] = Elt.isUndef();
7157 Zeroable[i] = (Elt.isUndef() || X86::isZeroNode(Elt));
7158 }
7159 assert(Zeroable.size() - Zeroable.count() > 1 &&((Zeroable.size() - Zeroable.count() > 1 && "We expect at least two non-zero elements!"
) ? static_cast<void> (0) : __assert_fail ("Zeroable.size() - Zeroable.count() > 1 && \"We expect at least two non-zero elements!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 7160, __PRETTY_FUNCTION__))
7160 "We expect at least two non-zero elements!")((Zeroable.size() - Zeroable.count() > 1 && "We expect at least two non-zero elements!"
) ? static_cast<void> (0) : __assert_fail ("Zeroable.size() - Zeroable.count() > 1 && \"We expect at least two non-zero elements!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 7160, __PRETTY_FUNCTION__))
;
7161
7162 // We only know how to deal with build_vector nodes where elements are either
7163 // zeroable or extract_vector_elt with constant index.
7164 SDValue FirstNonZero;
7165 unsigned FirstNonZeroIdx;
7166 for (unsigned i = 0; i < 4; ++i) {
7167 if (Zeroable[i])
7168 continue;
7169 SDValue Elt = Op.getOperand(i);
7170 if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7171 !isa<ConstantSDNode>(Elt.getOperand(1)))
7172 return SDValue();
7173 // Make sure that this node is extracting from a 128-bit vector.
7174 MVT VT = Elt.getOperand(0).getSimpleValueType();
7175 if (!VT.is128BitVector())
7176 return SDValue();
7177 if (!FirstNonZero.getNode()) {
7178 FirstNonZero = Elt;
7179 FirstNonZeroIdx = i;
7180 }
7181 }
7182
7183 assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!")((FirstNonZero.getNode() && "Unexpected build vector of all zeros!"
) ? static_cast<void> (0) : __assert_fail ("FirstNonZero.getNode() && \"Unexpected build vector of all zeros!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 7183, __PRETTY_FUNCTION__))
;
7184 SDValue V1 = FirstNonZero.getOperand(0);
7185 MVT VT = V1.getSimpleValueType();
7186
7187 // See if this build_vector can be lowered as a blend with zero.
7188 SDValue Elt;
7189 unsigned EltMaskIdx, EltIdx;
7190 int Mask[4];
7191 for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
7192 if (Zeroable[EltIdx]) {
7193 // The zero vector will be on the right hand side.
7194 Mask[EltIdx] = EltIdx+4;
7195 continue;
7196 }
7197
7198 Elt = Op->getOperand(EltIdx);
7199 // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
7200 EltMaskIdx = Elt.getConstantOperandVal(1);
7201 if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
7202 break;
7203 Mask[EltIdx] = EltIdx;
7204 }
7205
7206 if (EltIdx == 4) {
7207 // Let the shuffle legalizer deal with blend operations.
7208 SDValue VZeroOrUndef = (Zeroable == Undefs)
7209 ? DAG.getUNDEF(VT)
7210 : getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
7211 if (V1.getSimpleValueType() != VT)
7212 V1 = DAG.getBitcast(VT, V1);
7213 return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZeroOrUndef, Mask);
7214 }
7215
7216 // See if we can lower this build_vector to a INSERTPS.
7217 if (!Subtarget.hasSSE41())
7218 return SDValue();
7219
7220 SDValue V2 = Elt.getOperand(0);
7221 if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
7222 V1 = SDValue();
7223
7224 bool CanFold = true;
7225 for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
7226 if (Zeroable[i])
7227 continue;
7228
7229 SDValue Current = Op->getOperand(i);
7230 SDValue SrcVector = Current->getOperand(0);
7231 if (!V1.getNode())
7232 V1 = SrcVector;
7233 CanFold = (SrcVector == V1) && (Current.getConstantOperandVal(1) == i);
7234 }
7235
7236 if (!CanFold)
7237 return SDValue();
7238
7239 assert(V1.getNode() && "Expected at least two non-zero elements!")((V1.getNode() && "Expected at least two non-zero elements!"
) ? static_cast<void> (0) : __assert_fail ("V1.getNode() && \"Expected at least two non-zero elements!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 7239, __PRETTY_FUNCTION__))
;
7240 if (V1.getSimpleValueType() != MVT::v4f32)
7241 V1 = DAG.getBitcast(MVT::v4f32, V1);
7242 if (V2.getSimpleValueType() != MVT::v4f32)
7243 V2 = DAG.getBitcast(MVT::v4f32, V2);
7244
7245 // Ok, we can emit an INSERTPS instruction.
7246 unsigned ZMask = Zeroable.to_ulong();
7247
7248 unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
7249 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!")(((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!"
) ? static_cast<void> (0) : __assert_fail ("(InsertPSMask & ~0xFFu) == 0 && \"Invalid mask!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 7249, __PRETTY_FUNCTION__))
;
7250 SDLoc DL(Op);
7251 SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7252 DAG.getIntPtrConstant(InsertPSMask, DL));
7253 return DAG.getBitcast(VT, Result);
7254}
7255
7256/// Return a vector logical shift node.
7257static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp, unsigned NumBits,
7258 SelectionDAG &DAG, const TargetLowering &TLI,
7259 const SDLoc &dl) {
7260 assert(VT.is128BitVector() && "Unknown type for VShift")((VT.is128BitVector() && "Unknown type for VShift") ?
static_cast<void> (0) : __assert_fail ("VT.is128BitVector() && \"Unknown type for VShift\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 7260, __PRETTY_FUNCTION__))
;
7261 MVT ShVT = MVT::v16i8;
7262 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
7263 SrcOp = DAG.getBitcast(ShVT, SrcOp);
7264 assert(NumBits % 8 == 0 && "Only support byte sized shifts")((NumBits % 8 == 0 && "Only support byte sized shifts"
) ? static_cast<void> (0) : __assert_fail ("NumBits % 8 == 0 && \"Only support byte sized shifts\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 7264, __PRETTY_FUNCTION__))
;
7265 SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, MVT::i8);
7266 return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
7267}
7268
7269static SDValue LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, const SDLoc &dl,
7270 SelectionDAG &DAG) {
7271
7272 // Check if the scalar load can be widened into a vector load. And if
7273 // the address is "base + cst" see if the cst can be "absorbed" into
7274 // the shuffle mask.
7275 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
7276 SDValue Ptr = LD->getBasePtr();
7277 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
7278 return SDValue();
7279 EVT PVT = LD->getValueType(0);
7280 if (PVT != MVT::i32 && PVT != MVT::f32)
7281 return SDValue();
7282
7283 int FI = -1;
7284 int64_t Offset = 0;
7285 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
7286 FI = FINode->getIndex();
7287 Offset = 0;
7288 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
7289 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
7290 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
7291 Offset = Ptr.getConstantOperandVal(1);
7292 Ptr = Ptr.getOperand(0);
7293 } else {
7294 return SDValue();
7295 }
7296
7297 // FIXME: 256-bit vector instructions don't require a strict alignment,
7298 // improve this code to support it better.
7299 unsigned RequiredAlign = VT.getSizeInBits()/8;
7300 SDValue Chain = LD->getChain();
7301 // Make sure the stack object alignment is at least 16 or 32.
7302 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7303 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
7304 if (MFI.isFixedObjectIndex(FI)) {
7305 // Can't change the alignment. FIXME: It's possible to compute
7306 // the exact stack offset and reference FI + adjust offset instead.
7307 // If someone *really* cares about this. That's the way to implement it.
7308 return SDValue();
7309 } else {
7310 MFI.setObjectAlignment(FI, RequiredAlign);
7311 }
7312 }
7313
7314 // (Offset % 16 or 32) must be multiple of 4. Then address is then
7315 // Ptr + (Offset & ~15).
7316 if (Offset < 0)
7317 return SDValue();
7318 if ((Offset % RequiredAlign) & 3)
7319 return SDValue();
7320 int64_t StartOffset = Offset & ~int64_t(RequiredAlign - 1);
7321 if (StartOffset) {
7322 SDLoc DL(Ptr);
7323 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
7324 DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
7325 }
7326
7327 int EltNo = (Offset - StartOffset) >> 2;
7328 unsigned NumElems = VT.getVectorNumElements();
7329
7330 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
7331 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
7332 LD->getPointerInfo().getWithOffset(StartOffset));
7333
7334 SmallVector<int, 8> Mask(NumElems, EltNo);
7335
7336 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), Mask);
7337 }
7338
7339 return SDValue();
7340}
7341
7342/// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
7343/// elements can be replaced by a single large load which has the same value as
7344/// a build_vector or insert_subvector whose loaded operands are 'Elts'.
7345///
7346/// Example: <load i32 *a, load i32 *a+4, zero, undef> -> zextload a
7347static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
7348 const SDLoc &DL, SelectionDAG &DAG,
7349 const X86Subtarget &Subtarget,
7350 bool isAfterLegalize) {
7351 unsigned NumElems = Elts.size();
7352
7353 int LastLoadedElt = -1;
7354 APInt LoadMask = APInt::getNullValue(NumElems);
7355 APInt ZeroMask = APInt::getNullValue(NumElems);
7356 APInt UndefMask = APInt::getNullValue(NumElems);
7357
7358 // For each element in the initializer, see if we've found a load, zero or an
7359 // undef.
7360 for (unsigned i = 0; i < NumElems; ++i) {
7361 SDValue Elt = peekThroughBitcasts(Elts[i]);
7362 if (!Elt.getNode())
7363 return SDValue();
7364
7365 if (Elt.isUndef())
7366 UndefMask.setBit(i);
7367 else if (X86::isZeroNode(Elt) || ISD::isBuildVectorAllZeros(Elt.getNode()))
7368 ZeroMask.setBit(i);
7369 else if (ISD::isNON_EXTLoad(Elt.getNode())) {
7370 LoadMask.setBit(i);
7371 LastLoadedElt = i;
7372 // Each loaded element must be the correct fractional portion of the
7373 // requested vector load.
7374 if ((NumElems * Elt.getValueSizeInBits()) != VT.getSizeInBits())
7375 return SDValue();
7376 } else
7377 return SDValue();
7378 }
7379 assert((ZeroMask.countPopulation() + UndefMask.countPopulation() +(((ZeroMask.countPopulation() + UndefMask.countPopulation() +
LoadMask.countPopulation()) == NumElems && "Incomplete element masks"
) ? static_cast<void> (0) : __assert_fail ("(ZeroMask.countPopulation() + UndefMask.countPopulation() + LoadMask.countPopulation()) == NumElems && \"Incomplete element masks\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 7381, __PRETTY_FUNCTION__))
7380 LoadMask.countPopulation()) == NumElems &&(((ZeroMask.countPopulation() + UndefMask.countPopulation() +
LoadMask.countPopulation()) == NumElems && "Incomplete element masks"
) ? static_cast<void> (0) : __assert_fail ("(ZeroMask.countPopulation() + UndefMask.countPopulation() + LoadMask.countPopulation()) == NumElems && \"Incomplete element masks\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 7381, __PRETTY_FUNCTION__))
7381 "Incomplete element masks")(((ZeroMask.countPopulation() + UndefMask.countPopulation() +
LoadMask.countPopulation()) == NumElems && "Incomplete element masks"
) ? static_cast<void> (0) : __assert_fail ("(ZeroMask.countPopulation() + UndefMask.countPopulation() + LoadMask.countPopulation()) == NumElems && \"Incomplete element masks\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 7381, __PRETTY_FUNCTION__))
;
7382
7383 // Handle Special Cases - all undef or undef/zero.
7384 if (UndefMask.countPopulation() == NumElems)
7385 return DAG.getUNDEF(VT);
7386
7387 // FIXME: Should we return this as a BUILD_VECTOR instead?
7388 if ((ZeroMask.countPopulation() + UndefMask.countPopulation()) == NumElems)
7389 return VT.isInteger() ? DAG.getConstant(0, DL, VT)
7390 : DAG.getConstantFP(0.0, DL, VT);
7391
7392 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7393 int FirstLoadedElt = LoadMask.countTrailingZeros();
7394 SDValue EltBase = peekThroughBitcasts(Elts[FirstLoadedElt]);
7395 LoadSDNode *LDBase = cast<LoadSDNode>(EltBase);
7396 EVT LDBaseVT = EltBase.getValueType();
7397
7398 // Consecutive loads can contain UNDEFS but not ZERO elements.
7399 // Consecutive loads with UNDEFs and ZEROs elements require a
7400 // an additional shuffle stage to clear the ZERO elements.
7401 bool IsConsecutiveLoad = true;
7402 bool IsConsecutiveLoadWithZeros = true;
7403 for (int i = FirstLoadedElt + 1; i <= LastLoadedElt; ++i) {
7404 if (LoadMask[i]) {
7405 SDValue Elt = peekThroughBitcasts(Elts[i]);
7406 LoadSDNode *LD = cast<LoadSDNode>(Elt);
7407 if (!DAG.areNonVolatileConsecutiveLoads(
7408 LD, LDBase, Elt.getValueType().getStoreSizeInBits() / 8,
7409 i - FirstLoadedElt)) {
7410 IsConsecutiveLoad = false;
7411 IsConsecutiveLoadWithZeros = false;
7412 break;
7413 }
7414 } else if (ZeroMask[i]) {
7415 IsConsecutiveLoad = false;
7416 }
7417 }
7418
7419 SmallVector<LoadSDNode *, 8> Loads;
7420 for (int i = FirstLoadedElt; i <= LastLoadedElt; ++i)
7421 if (LoadMask[i])
7422 Loads.push_back(cast<LoadSDNode>(peekThroughBitcasts(Elts[i])));
7423
7424 auto CreateLoad = [&DAG, &DL, &Loads](EVT VT, LoadSDNode *LDBase) {
7425 auto MMOFlags = LDBase->getMemOperand()->getFlags();
7426 assert(!(MMOFlags & MachineMemOperand::MOVolatile) &&((!(MMOFlags & MachineMemOperand::MOVolatile) && "Cannot merge volatile loads."
) ? static_cast<void> (0) : __assert_fail ("!(MMOFlags & MachineMemOperand::MOVolatile) && \"Cannot merge volatile loads.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 7427, __PRETTY_FUNCTION__))
7427 "Cannot merge volatile loads.")((!(MMOFlags & MachineMemOperand::MOVolatile) && "Cannot merge volatile loads."
) ? static_cast<void> (0) : __assert_fail ("!(MMOFlags & MachineMemOperand::MOVolatile) && \"Cannot merge volatile loads.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 7427, __PRETTY_FUNCTION__))
;
7428 SDValue NewLd =
7429 DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
7430 LDBase->getPointerInfo(), LDBase->getAlignment(), MMOFlags);
7431 for (auto *LD : Loads)
7432 DAG.makeEquivalentMemoryOrdering(LD, NewLd);
7433 return NewLd;
7434 };
7435
7436 // LOAD - all consecutive load/undefs (must start/end with a load).
7437 // If we have found an entire vector of loads and undefs, then return a large
7438 // load of the entire vector width starting at the base pointer.
7439 // If the vector contains zeros, then attempt to shuffle those elements.
7440 if (FirstLoadedElt == 0 && LastLoadedElt == (int)(NumElems - 1) &&
7441 (IsConsecutiveLoad || IsConsecutiveLoadWithZeros)) {
7442 assert(LDBase && "Did not find base load for merging consecutive loads")((LDBase && "Did not find base load for merging consecutive loads"
) ? static_cast<void> (0) : __assert_fail ("LDBase && \"Did not find base load for merging consecutive loads\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 7442, __PRETTY_FUNCTION__))
;
7443 EVT EltVT = LDBase->getValueType(0);
7444 // Ensure that the input vector size for the merged loads matches the
7445 // cumulative size of the input elements.
7446 if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
7447 return SDValue();
7448
7449 if (isAfterLegalize && !TLI.isOperationLegal(ISD::LOAD, VT))
7450 return SDValue();
7451
7452 // Don't create 256-bit non-temporal aligned loads without AVX2 as these
7453 // will lower to regular temporal loads and use the cache.
7454 if (LDBase->isNonTemporal() && LDBase->getAlignment() >= 32 &&
7455 VT.is256BitVector() && !Subtarget.hasInt256())
7456 return SDValue();
7457
7458 if (NumElems == 1)
7459 return DAG.getBitcast(VT, Elts[FirstLoadedElt]);
7460
7461 if (IsConsecutiveLoad)
7462 return CreateLoad(VT, LDBase);
7463
7464 // IsConsecutiveLoadWithZeros - we need to create a shuffle of the loaded
7465 // vector and a zero vector to clear out the zero elements.
7466 if (!isAfterLegalize && VT.isVector() && NumElems == VT.getVectorNumElements()) {
7467 SmallVector<int, 4> ClearMask(NumElems, -1);
7468 for (unsigned i = 0; i < NumElems; ++i) {
7469 if (ZeroMask[i])
7470 ClearMask[i] = i + NumElems;
7471 else if (LoadMask[i])
7472 ClearMask[i] = i;
7473 }
7474 SDValue V = CreateLoad(VT, LDBase);
7475 SDValue Z = VT.isInteger() ? DAG.getConstant(0, DL, VT)
7476 : DAG.getConstantFP(0.0, DL, VT);
7477 return DAG.getVectorShuffle(VT, DL, V, Z, ClearMask);
7478 }
7479 }
7480
7481 unsigned BaseSize = LDBaseVT.getStoreSizeInBits();
7482 int LoadSize = (1 + LastLoadedElt - FirstLoadedElt) * BaseSize;
7483
7484 // If the upper half of a ymm/zmm load is undef then just load the lower half.
7485 if (VT.is256BitVector() || VT.is512BitVector()) {
7486 unsigned HalfNumElems = NumElems / 2;
7487 if (UndefMask.extractBits(HalfNumElems, HalfNumElems).isAllOnesValue()) {
7488 EVT HalfVT =
7489 EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), HalfNumElems);
7490 SDValue HalfLD =
7491 EltsFromConsecutiveLoads(HalfVT, Elts.drop_back(HalfNumElems), DL,
7492 DAG, Subtarget, isAfterLegalize);
7493 if (HalfLD)
7494 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT),
7495 HalfLD, DAG.getIntPtrConstant(0, DL));
7496 }
7497 }
7498
7499 // VZEXT_LOAD - consecutive 32/64-bit load/undefs followed by zeros/undefs.
7500 if (IsConsecutiveLoad && FirstLoadedElt == 0 &&
7501 (LoadSize == 32 || LoadSize == 64) &&
7502 ((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()))) {
7503 MVT VecSVT = VT.isFloatingPoint() ? MVT::getFloatingPointVT(LoadSize)
7504 : MVT::getIntegerVT(LoadSize);
7505 MVT VecVT = MVT::getVectorVT(VecSVT, VT.getSizeInBits() / LoadSize);
7506 if (TLI.isTypeLegal(VecVT)) {
7507 SDVTList Tys = DAG.getVTList(VecVT, MVT::Other);
7508 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
7509 SDValue ResNode =
7510 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, VecSVT,
7511 LDBase->getPointerInfo(),
7512 LDBase->getAlignment(),
7513 MachineMemOperand::MOLoad);
7514 for (auto *LD : Loads)
7515 DAG.makeEquivalentMemoryOrdering(LD, ResNode);
7516 return DAG.getBitcast(VT, ResNode);
7517 }
7518 }
7519
7520 // BROADCAST - match the smallest possible repetition pattern, load that
7521 // scalar/subvector element and then broadcast to the entire vector.
7522 if (ZeroMask.isNullValue() && isPowerOf2_32(NumElems) &&
7523 (BaseSize % 8) == 0 && Subtarget.hasAVX() &&
7524 (VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector())) {
7525 for (unsigned SubElems = 1; SubElems < NumElems; SubElems *= 2) {
7526 unsigned RepeatSize = SubElems * BaseSize;
7527 unsigned ScalarSize = std::min(RepeatSize, 64u);
7528 if (!Subtarget.hasAVX2() && ScalarSize < 32)
7529 continue;
7530
7531 bool Match = true;
7532 SmallVector<SDValue, 8> RepeatedLoads(SubElems, DAG.getUNDEF(LDBaseVT));
7533 for (unsigned i = 0; i != NumElems && Match; ++i) {
7534 if (!LoadMask[i])
7535 continue;
7536 SDValue Elt = peekThroughBitcasts(Elts[i]);
7537 if (RepeatedLoads[i % SubElems].isUndef())
7538 RepeatedLoads[i % SubElems] = Elt;
7539 else
7540 Match &= (RepeatedLoads[i % SubElems] == Elt);
7541 }
7542
7543 // We must have loads at both ends of the repetition.
7544 Match &= !RepeatedLoads.front().isUndef();
7545 Match &= !RepeatedLoads.back().isUndef();
7546 if (!Match)
7547 continue;
7548
7549 EVT RepeatVT =
7550 VT.isInteger() && (RepeatSize != 64 || TLI.isTypeLegal(MVT::i64))
7551 ? EVT::getIntegerVT(*DAG.getContext(), ScalarSize)
7552 : EVT::getFloatingPointVT(ScalarSize);
7553 if (RepeatSize > ScalarSize)
7554 RepeatVT = EVT::getVectorVT(*DAG.getContext(), RepeatVT,
7555 RepeatSize / ScalarSize);
7556 EVT BroadcastVT =
7557 EVT::getVectorVT(*DAG.getContext(), RepeatVT.getScalarType(),
7558 VT.getSizeInBits() / ScalarSize);
7559 if (TLI.isTypeLegal(BroadcastVT)) {
7560 if (SDValue RepeatLoad = EltsFromConsecutiveLoads(
7561 RepeatVT, RepeatedLoads, DL, DAG, Subtarget, isAfterLegalize)) {
7562 unsigned Opcode = RepeatSize > ScalarSize ? X86ISD::SUBV_BROADCAST
7563 : X86ISD::VBROADCAST;
7564 SDValue Broadcast = DAG.getNode(Opcode, DL, BroadcastVT, RepeatLoad);
7565 return DAG.getBitcast(VT, Broadcast);
7566 }
7567 }
7568 }
7569 }
7570
7571 return SDValue();
7572}
7573
7574// Combine a vector ops (shuffles etc.) that is equal to build_vector load1,
7575// load2, load3, load4, <0, 1, 2, 3> into a vector load if the load addresses
7576// are consecutive, non-overlapping, and in the right order.
7577static SDValue combineToConsecutiveLoads(EVT VT, SDNode *N, const SDLoc &DL,
7578 SelectionDAG &DAG,
7579 const X86Subtarget &Subtarget,
7580 bool isAfterLegalize) {
7581 SmallVector<SDValue, 64> Elts;
7582 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
7583 if (SDValue Elt = getShuffleScalarElt(N, i, DAG, 0)) {
7584 Elts.push_back(Elt);
7585 continue;
7586 }
7587 return SDValue();
7588 }
7589 assert(Elts.size() == VT.getVectorNumElements())((Elts.size() == VT.getVectorNumElements()) ? static_cast<
void> (0) : __assert_fail ("Elts.size() == VT.getVectorNumElements()"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 7589, __PRETTY_FUNCTION__))
;
7590 return EltsFromConsecutiveLoads(VT, Elts, DL, DAG, Subtarget,
7591 isAfterLegalize);
7592}
7593
7594static Constant *getConstantVector(MVT VT, const APInt &SplatValue,
7595 unsigned SplatBitSize, LLVMContext &C) {
7596 unsigned ScalarSize = VT.getScalarSizeInBits();
7597 unsigned NumElm = SplatBitSize / ScalarSize;
7598
7599 SmallVector<Constant *, 32> ConstantVec;
7600 for (unsigned i = 0; i < NumElm; i++) {
7601 APInt Val = SplatValue.extractBits(ScalarSize, ScalarSize * i);
7602 Constant *Const;
7603 if (VT.isFloatingPoint()) {
7604 if (ScalarSize == 32) {
7605 Const = ConstantFP::get(C, APFloat(APFloat::IEEEsingle(), Val));
7606 } else {
7607 assert(ScalarSize == 64 && "Unsupported floating point scalar size")((ScalarSize == 64 && "Unsupported floating point scalar size"
) ? static_cast<void> (0) : __assert_fail ("ScalarSize == 64 && \"Unsupported floating point scalar size\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 7607, __PRETTY_FUNCTION__))
;
7608 Const = ConstantFP::get(C, APFloat(APFloat::IEEEdouble(), Val));
7609 }
7610 } else
7611 Const = Constant::getIntegerValue(Type::getIntNTy(C, ScalarSize), Val);
7612 ConstantVec.push_back(Const);
7613 }
7614 return ConstantVector::get(ArrayRef<Constant *>(ConstantVec));
7615}
7616
7617static bool isFoldableUseOfShuffle(SDNode *N) {
7618 for (auto *U : N->uses()) {
7619 unsigned Opc = U->getOpcode();
7620 // VPERMV/VPERMV3 shuffles can never fold their index operands.
7621 if (Opc == X86ISD::VPERMV && U->getOperand(0).getNode() == N)
7622 return false;
7623 if (Opc == X86ISD::VPERMV3 && U->getOperand(1).getNode() == N)
7624 return false;
7625 if (isTargetShuffle(Opc))
7626 return true;
7627 if (Opc == ISD::BITCAST) // Ignore bitcasts
7628 return isFoldableUseOfShuffle(U);
7629 if (N->hasOneUse())
7630 return true;
7631 }
7632 return false;
7633}
7634
7635// Check if the current node of build vector is a zero extended vector.
7636// // If so, return the value extended.
7637// // For example: (0,0,0,a,0,0,0,a,0,0,0,a,0,0,0,a) returns a.
7638// // NumElt - return the number of zero extended identical values.
7639// // EltType - return the type of the value include the zero extend.
7640static SDValue isSplatZeroExtended(const BuildVectorSDNode *Op,
7641 unsigned &NumElt, MVT &EltType) {
7642 SDValue ExtValue = Op->getOperand(0);
7643 unsigned NumElts = Op->getNumOperands();
7644 unsigned Delta = NumElts;
7645
7646 for (unsigned i = 1; i < NumElts; i++) {
7647 if (Op->getOperand(i) == ExtValue) {
7648 Delta = i;
7649 break;
7650 }
7651 if (!(Op->getOperand(i).isUndef() || isNullConstant(Op->getOperand(i))))
7652 return SDValue();
7653 }
7654 if (!isPowerOf2_32(Delta) || Delta == 1)
7655 return SDValue();
7656
7657 for (unsigned i = Delta; i < NumElts; i++) {
7658 if (i % Delta == 0) {
7659 if (Op->getOperand(i) != ExtValue)
7660 return SDValue();
7661 } else if (!(isNullConstant(Op->getOperand(i)) ||
7662 Op->getOperand(i).isUndef()))
7663 return SDValue();
7664 }
7665 unsigned EltSize = Op->getSimpleValueType(0).getScalarSizeInBits();
7666 unsigned ExtVTSize = EltSize * Delta;
7667 EltType = MVT::getIntegerVT(ExtVTSize);
7668 NumElt = NumElts / Delta;
7669 return ExtValue;
7670}
7671
7672/// Attempt to use the vbroadcast instruction to generate a splat value
7673/// from a splat BUILD_VECTOR which uses:
7674/// a. A single scalar load, or a constant.
7675/// b. Repeated pattern of constants (e.g. <0,1,0,1> or <0,1,2,3,0,1,2,3>).
7676///
7677/// The VBROADCAST node is returned when a pattern is found,
7678/// or SDValue() otherwise.
7679static SDValue lowerBuildVectorAsBroadcast(BuildVectorSDNode *BVOp,
7680 const X86Subtarget &Subtarget,
7681 SelectionDAG &DAG) {
7682 // VBROADCAST requires AVX.
7683 // TODO: Splats could be generated for non-AVX CPUs using SSE
7684 // instructions, but there's less potential gain for only 128-bit vectors.
7685 if (!Subtarget.hasAVX())
7686 return SDValue();
7687
7688 MVT VT = BVOp->getSimpleValueType(0);
7689 SDLoc dl(BVOp);
7690
7691 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&(((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector
()) && "Unsupported vector type for broadcast.") ? static_cast
<void> (0) : __assert_fail ("(VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) && \"Unsupported vector type for broadcast.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 7692, __PRETTY_FUNCTION__))
7692 "Unsupported vector type for broadcast.")(((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector
()) && "Unsupported vector type for broadcast.") ? static_cast
<void> (0) : __assert_fail ("(VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) && \"Unsupported vector type for broadcast.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 7692, __PRETTY_FUNCTION__))
;
7693
7694 BitVector UndefElements;
7695 SDValue Ld = BVOp->getSplatValue(&UndefElements);
7696
7697 // Attempt to use VBROADCASTM
7698 // From this paterrn:
7699 // a. t0 = (zext_i64 (bitcast_i8 v2i1 X))
7700 // b. t1 = (build_vector t0 t0)
7701 //
7702 // Create (VBROADCASTM v2i1 X)
7703 if (Subtarget.hasCDI() && (VT.is512BitVector() || Subtarget.hasVLX())) {
7704 MVT EltType = VT.getScalarType();
7705 unsigned NumElts = VT.getVectorNumElements();
7706 SDValue BOperand;
7707 SDValue ZeroExtended = isSplatZeroExtended(BVOp, NumElts, EltType);
7708 if ((ZeroExtended && ZeroExtended.getOpcode() == ISD::BITCAST) ||
7709 (Ld && Ld.getOpcode() == ISD::ZERO_EXTEND &&
7710 Ld.getOperand(0).getOpcode() == ISD::BITCAST)) {
7711 if (ZeroExtended)
7712 BOperand = ZeroExtended.getOperand(0);
7713 else
7714 BOperand = Ld.getOperand(0).getOperand(0);
7715 MVT MaskVT = BOperand.getSimpleValueType();
7716 if ((EltType == MVT::i64 && MaskVT == MVT::v8i1) || // for broadcastmb2q
7717 (EltType == MVT::i32 && MaskVT == MVT::v16i1)) { // for broadcastmw2d
7718 SDValue Brdcst =
7719 DAG.getNode(X86ISD::VBROADCASTM, dl,
7720 MVT::getVectorVT(EltType, NumElts), BOperand);
7721 return DAG.getBitcast(VT, Brdcst);
7722 }
7723 }
7724 }
7725
7726 unsigned NumElts = VT.getVectorNumElements();
7727 unsigned NumUndefElts = UndefElements.count();
7728 if (!Ld || (NumElts - NumUndefElts) <= 1) {
7729 APInt SplatValue, Undef;
7730 unsigned SplatBitSize;
7731 bool HasUndef;
7732 // Check if this is a repeated constant pattern suitable for broadcasting.
7733 if (BVOp->isConstantSplat(SplatValue, Undef, SplatBitSize, HasUndef) &&
7734 SplatBitSize > VT.getScalarSizeInBits() &&
7735 SplatBitSize < VT.getSizeInBits()) {
7736 // Avoid replacing with broadcast when it's a use of a shuffle
7737 // instruction to preserve the present custom lowering of shuffles.
7738 if (isFoldableUseOfShuffle(BVOp))
7739 return SDValue();
7740 // replace BUILD_VECTOR with broadcast of the repeated constants.
7741 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7742 LLVMContext *Ctx = DAG.getContext();
7743 MVT PVT = TLI.getPointerTy(DAG.getDataLayout());
7744 if (Subtarget.hasAVX()) {
7745 if (SplatBitSize <= 64 && Subtarget.hasAVX2() &&
7746 !(SplatBitSize == 64 && Subtarget.is32Bit())) {
7747 // Splatted value can fit in one INTEGER constant in constant pool.
7748 // Load the constant and broadcast it.
7749 MVT CVT = MVT::getIntegerVT(SplatBitSize);
7750 Type *ScalarTy = Type::getIntNTy(*Ctx, SplatBitSize);
7751 Constant *C = Constant::getIntegerValue(ScalarTy, SplatValue);
7752 SDValue CP = DAG.getConstantPool(C, PVT);
7753 unsigned Repeat = VT.getSizeInBits() / SplatBitSize;
7754
7755 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
7756 Ld = DAG.getLoad(
7757 CVT, dl, DAG.getEntryNode(), CP,
7758 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
7759 Alignment);
7760 SDValue Brdcst = DAG.getNode(X86ISD::VBROADCAST, dl,
7761 MVT::getVectorVT(CVT, Repeat), Ld);
7762 return DAG.getBitcast(VT, Brdcst);
7763 } else if (SplatBitSize == 32 || SplatBitSize == 64) {
7764 // Splatted value can fit in one FLOAT constant in constant pool.
7765 // Load the constant and broadcast it.
7766 // AVX have support for 32 and 64 bit broadcast for floats only.
7767 // No 64bit integer in 32bit subtarget.
7768 MVT CVT = MVT::getFloatingPointVT(SplatBitSize);
7769 // Lower the splat via APFloat directly, to avoid any conversion.
7770 Constant *C =
7771 SplatBitSize == 32
7772 ? ConstantFP::get(*Ctx,
7773 APFloat(APFloat::IEEEsingle(), SplatValue))
7774 : ConstantFP::get(*Ctx,
7775 APFloat(APFloat::IEEEdouble(), SplatValue));
7776 SDValue CP = DAG.getConstantPool(C, PVT);
7777 unsigned Repeat = VT.getSizeInBits() / SplatBitSize;
7778
7779 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
7780 Ld = DAG.getLoad(
7781 CVT, dl, DAG.getEntryNode(), CP,
7782 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
7783 Alignment);
7784 SDValue Brdcst = DAG.getNode(X86ISD::VBROADCAST, dl,
7785 MVT::getVectorVT(CVT, Repeat), Ld);
7786 return DAG.getBitcast(VT, Brdcst);
7787 } else if (SplatBitSize > 64) {
7788 // Load the vector of constants and broadcast it.
7789 MVT CVT = VT.getScalarType();
7790 Constant *VecC = getConstantVector(VT, SplatValue, SplatBitSize,
7791 *Ctx);
7792 SDValue VCP = DAG.getConstantPool(VecC, PVT);
7793 unsigned NumElm = SplatBitSize / VT.getScalarSizeInBits();
7794 unsigned Alignment = cast<ConstantPoolSDNode>(VCP)->getAlignment();
7795 Ld = DAG.getLoad(
7796 MVT::getVectorVT(CVT, NumElm), dl, DAG.getEntryNode(), VCP,
7797 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
7798 Alignment);
7799 SDValue Brdcst = DAG.getNode(X86ISD::SUBV_BROADCAST, dl, VT, Ld);
7800 return DAG.getBitcast(VT, Brdcst);
7801 }
7802 }
7803 }
7804
7805 // If we are moving a scalar into a vector (Ld must be set and all elements
7806 // but 1 are undef) and that operation is not obviously supported by
7807 // vmovd/vmovq/vmovss/vmovsd, then keep trying to form a broadcast.
7808 // That's better than general shuffling and may eliminate a load to GPR and
7809 // move from scalar to vector register.
7810 if (!Ld || NumElts - NumUndefElts != 1)
7811 return SDValue();
7812 unsigned ScalarSize = Ld.getValueSizeInBits();
7813 if (!(UndefElements[0] || (ScalarSize != 32 && ScalarSize != 64)))
7814 return SDValue();
7815 }
7816
7817 bool ConstSplatVal =
7818 (Ld.getOpcode() == ISD::Constant || Ld.getOpcode() == ISD::ConstantFP);
7819
7820 // Make sure that all of the users of a non-constant load are from the
7821 // BUILD_VECTOR node.
7822 if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
7823 return SDValue();
7824
7825 unsigned ScalarSize = Ld.getValueSizeInBits();
7826 bool IsGE256 = (VT.getSizeInBits() >= 256);
7827
7828 // When optimizing for size, generate up to 5 extra bytes for a broadcast
7829 // instruction to save 8 or more bytes of constant pool data.
7830 // TODO: If multiple splats are generated to load the same constant,
7831 // it may be detrimental to overall size. There needs to be a way to detect
7832 // that condition to know if this is truly a size win.
7833 bool OptForSize = DAG.getMachineFunction().getFunction().hasOptSize();
7834
7835 // Handle broadcasting a single constant scalar from the constant pool
7836 // into a vector.
7837 // On Sandybridge (no AVX2), it is still better to load a constant vector
7838 // from the constant pool and not to broadcast it from a scalar.
7839 // But override that restriction when optimizing for size.
7840 // TODO: Check if splatting is recommended for other AVX-capable CPUs.
7841 if (ConstSplatVal && (Subtarget.hasAVX2() || OptForSize)) {
7842 EVT CVT = Ld.getValueType();
7843 assert(!CVT.isVector() && "Must not broadcast a vector type")((!CVT.isVector() && "Must not broadcast a vector type"
) ? static_cast<void> (0) : __assert_fail ("!CVT.isVector() && \"Must not broadcast a vector type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 7843, __PRETTY_FUNCTION__))
;
7844
7845 // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
7846 // For size optimization, also splat v2f64 and v2i64, and for size opt
7847 // with AVX2, also splat i8 and i16.
7848 // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
7849 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
7850 (OptForSize && (ScalarSize == 64 || Subtarget.hasAVX2()))) {
7851 const Constant *C = nullptr;
7852 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
7853 C = CI->getConstantIntValue();
7854 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
7855 C = CF->getConstantFPValue();
7856
7857 assert(C && "Invalid constant type")((C && "Invalid constant type") ? static_cast<void
> (0) : __assert_fail ("C && \"Invalid constant type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 7857, __PRETTY_FUNCTION__))
;
7858
7859 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7860 SDValue CP =
7861 DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
7862 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
7863 Ld = DAG.getLoad(
7864 CVT, dl, DAG.getEntryNode(), CP,
7865 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
7866 Alignment);
7867
7868 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
7869 }
7870 }
7871
7872 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
7873
7874 // Handle AVX2 in-register broadcasts.
7875 if (!IsLoad && Subtarget.hasInt256() &&
7876 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
7877 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
7878
7879 // The scalar source must be a normal load.
7880 if (!IsLoad)
7881 return SDValue();
7882
7883 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
7884 (Subtarget.hasVLX() && ScalarSize == 64))
7885 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
7886
7887 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
7888 // double since there is no vbroadcastsd xmm
7889 if (Subtarget.hasInt256() && Ld.getValueType().isInteger()) {
7890 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
7891 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
7892 }
7893
7894 // Unsupported broadcast.
7895 return SDValue();
7896}
7897
7898/// For an EXTRACT_VECTOR_ELT with a constant index return the real
7899/// underlying vector and index.
7900///
7901/// Modifies \p ExtractedFromVec to the real vector and returns the real
7902/// index.
7903static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
7904 SDValue ExtIdx) {
7905 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
7906 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
7907 return Idx;
7908
7909 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
7910 // lowered this:
7911 // (extract_vector_elt (v8f32 %1), Constant<6>)
7912 // to:
7913 // (extract_vector_elt (vector_shuffle<2,u,u,u>
7914 // (extract_subvector (v8f32 %0), Constant<4>),
7915 // undef)
7916 // Constant<0>)
7917 // In this case the vector is the extract_subvector expression and the index
7918 // is 2, as specified by the shuffle.
7919 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
7920 SDValue ShuffleVec = SVOp->getOperand(0);
7921 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
7922 assert(ShuffleVecVT.getVectorElementType() ==((ShuffleVecVT.getVectorElementType() == ExtractedFromVec.getSimpleValueType
().getVectorElementType()) ? static_cast<void> (0) : __assert_fail
("ShuffleVecVT.getVectorElementType() == ExtractedFromVec.getSimpleValueType().getVectorElementType()"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 7923, __PRETTY_FUNCTION__))
7923 ExtractedFromVec.getSimpleValueType().getVectorElementType())((ShuffleVecVT.getVectorElementType() == ExtractedFromVec.getSimpleValueType
().getVectorElementType()) ? static_cast<void> (0) : __assert_fail
("ShuffleVecVT.getVectorElementType() == ExtractedFromVec.getSimpleValueType().getVectorElementType()"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 7923, __PRETTY_FUNCTION__))
;
7924
7925 int ShuffleIdx = SVOp->getMaskElt(Idx);
7926 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
7927 ExtractedFromVec = ShuffleVec;
7928 return ShuffleIdx;
7929 }
7930 return Idx;
7931}
7932
7933static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
7934 MVT VT = Op.getSimpleValueType();
7935
7936 // Skip if insert_vec_elt is not supported.
7937 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7938 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
7939 return SDValue();
7940
7941 SDLoc DL(Op);
7942 unsigned NumElems = Op.getNumOperands();
7943
7944 SDValue VecIn1;
7945 SDValue VecIn2;
7946 SmallVector<unsigned, 4> InsertIndices;
7947 SmallVector<int, 8> Mask(NumElems, -1);
7948
7949 for (unsigned i = 0; i != NumElems; ++i) {
7950 unsigned Opc = Op.getOperand(i).getOpcode();
7951
7952 if (Opc == ISD::UNDEF)
7953 continue;
7954
7955 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
7956 // Quit if more than 1 elements need inserting.
7957 if (InsertIndices.size() > 1)
7958 return SDValue();
7959
7960 InsertIndices.push_back(i);
7961 continue;
7962 }
7963
7964 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
7965 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
7966
7967 // Quit if non-constant index.
7968 if (!isa<ConstantSDNode>(ExtIdx))
7969 return SDValue();
7970 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
7971
7972 // Quit if extracted from vector of different type.
7973 if (ExtractedFromVec.getValueType() != VT)
7974 return SDValue();
7975
7976 if (!VecIn1.getNode())
7977 VecIn1 = ExtractedFromVec;
7978 else if (VecIn1 != ExtractedFromVec) {
7979 if (!VecIn2.getNode())
7980 VecIn2 = ExtractedFromVec;
7981 else if (VecIn2 != ExtractedFromVec)
7982 // Quit if more than 2 vectors to shuffle
7983 return SDValue();
7984 }
7985
7986 if (ExtractedFromVec == VecIn1)
7987 Mask[i] = Idx;
7988 else if (ExtractedFromVec == VecIn2)
7989 Mask[i] = Idx + NumElems;
7990 }
7991
7992 if (!VecIn1.getNode())
7993 return SDValue();
7994
7995 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
7996 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, Mask);
7997
7998 for (unsigned Idx : InsertIndices)
7999 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
8000 DAG.getIntPtrConstant(Idx, DL));
8001
8002 return NV;
8003}
8004
8005static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
8006 assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&((ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
Op.getScalarValueSizeInBits() == 1 && "Can not convert non-constant vector"
) ? static_cast<void> (0) : __assert_fail ("ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) && Op.getScalarValueSizeInBits() == 1 && \"Can not convert non-constant vector\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 8008, __PRETTY_FUNCTION__))
8007 Op.getScalarValueSizeInBits() == 1 &&((ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
Op.getScalarValueSizeInBits() == 1 && "Can not convert non-constant vector"
) ? static_cast<void> (0) : __assert_fail ("ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) && Op.getScalarValueSizeInBits() == 1 && \"Can not convert non-constant vector\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 8008, __PRETTY_FUNCTION__))
8008 "Can not convert non-constant vector")((ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
Op.getScalarValueSizeInBits() == 1 && "Can not convert non-constant vector"
) ? static_cast<void> (0) : __assert_fail ("ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) && Op.getScalarValueSizeInBits() == 1 && \"Can not convert non-constant vector\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 8008, __PRETTY_FUNCTION__))
;
8009 uint64_t Immediate = 0;
8010 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
8011 SDValue In = Op.getOperand(idx);
8012 if (!In.isUndef())
8013 Immediate |= (cast<ConstantSDNode>(In)->getZExtValue() & 0x1) << idx;
8014 }
8015 SDLoc dl(Op);
8016 MVT VT = MVT::getIntegerVT(std::max((int)Op.getValueSizeInBits(), 8));
8017 return DAG.getConstant(Immediate, dl, VT);
8018}
8019// Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
8020static SDValue LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG,
8021 const X86Subtarget &Subtarget) {
8022
8023 MVT VT = Op.getSimpleValueType();
8024 assert((VT.getVectorElementType() == MVT::i1) &&(((VT.getVectorElementType() == MVT::i1) && "Unexpected type in LowerBUILD_VECTORvXi1!"
) ? static_cast<void> (0) : __assert_fail ("(VT.getVectorElementType() == MVT::i1) && \"Unexpected type in LowerBUILD_VECTORvXi1!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 8025, __PRETTY_FUNCTION__))
8025 "Unexpected type in LowerBUILD_VECTORvXi1!")(((VT.getVectorElementType() == MVT::i1) && "Unexpected type in LowerBUILD_VECTORvXi1!"
) ? static_cast<void> (0) : __assert_fail ("(VT.getVectorElementType() == MVT::i1) && \"Unexpected type in LowerBUILD_VECTORvXi1!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 8025, __PRETTY_FUNCTION__))
;
8026
8027 SDLoc dl(Op);
8028 if (ISD::isBuildVectorAllZeros(Op.getNode()))
8029 return Op;
8030
8031 if (ISD::isBuildVectorAllOnes(Op.getNode()))
8032 return Op;
8033
8034 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
8035 if (VT == MVT::v64i1 && !Subtarget.is64Bit()) {
8036 // Split the pieces.
8037 SDValue Lower =
8038 DAG.getBuildVector(MVT::v32i1, dl, Op.getNode()->ops().slice(0, 32));
8039 SDValue Upper =
8040 DAG.getBuildVector(MVT::v32i1, dl, Op.getNode()->ops().slice(32, 32));
8041 // We have to manually lower both halves so getNode doesn't try to
8042 // reassemble the build_vector.
8043 Lower = LowerBUILD_VECTORvXi1(Lower, DAG, Subtarget);
8044 Upper = LowerBUILD_VECTORvXi1(Upper, DAG, Subtarget);
8045 return DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, Lower, Upper);
8046 }
8047 SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
8048 if (Imm.getValueSizeInBits() == VT.getSizeInBits())
8049 return DAG.getBitcast(VT, Imm);
8050 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
8051 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
8052 DAG.getIntPtrConstant(0, dl));
8053 }
8054
8055 // Vector has one or more non-const elements
8056 uint64_t Immediate = 0;
8057 SmallVector<unsigned, 16> NonConstIdx;
8058 bool IsSplat = true;
8059 bool HasConstElts = false;
8060 int SplatIdx = -1;
8061 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
8062 SDValue In = Op.getOperand(idx);
8063 if (In.isUndef())
8064 continue;
8065 if (!isa<ConstantSDNode>(In))
8066 NonConstIdx.push_back(idx);
8067 else {
8068 Immediate |= (cast<ConstantSDNode>(In)->getZExtValue() & 0x1) << idx;
8069 HasConstElts = true;
8070 }
8071 if (SplatIdx < 0)
8072 SplatIdx = idx;
8073 else if (In != Op.getOperand(SplatIdx))
8074 IsSplat = false;
8075 }
8076
8077 // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
8078 if (IsSplat)
8079 return DAG.getSelect(dl, VT, Op.getOperand(SplatIdx),
8080 DAG.getConstant(1, dl, VT),
8081 DAG.getConstant(0, dl, VT));
8082
8083 // insert elements one by one
8084 SDValue DstVec;
8085 SDValue Imm;
8086 if (Immediate) {
8087 MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
8088 Imm = DAG.getConstant(Immediate, dl, ImmVT);
8089 }
8090 else if (HasConstElts)
8091 Imm = DAG.getConstant(0, dl, VT);
8092 else
8093 Imm = DAG.getUNDEF(VT);
8094 if (Imm.getValueSizeInBits() == VT.getSizeInBits())
8095 DstVec = DAG.getBitcast(VT, Imm);
8096 else {
8097 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
8098 DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
8099 DAG.getIntPtrConstant(0, dl));
8100 }
8101
8102 for (unsigned i = 0, e = NonConstIdx.size(); i != e; ++i) {
8103 unsigned InsertIdx = NonConstIdx[i];
8104 DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
8105 Op.getOperand(InsertIdx),
8106 DAG.getIntPtrConstant(InsertIdx, dl));
8107 }
8108 return DstVec;
8109}
8110
8111/// This is a helper function of LowerToHorizontalOp().
8112/// This function checks that the build_vector \p N in input implements a
8113/// 128-bit partial horizontal operation on a 256-bit vector, but that operation
8114/// may not match the layout of an x86 256-bit horizontal instruction.
8115/// In other words, if this returns true, then some extraction/insertion will
8116/// be required to produce a valid horizontal instruction.
8117///
8118/// Parameter \p Opcode defines the kind of horizontal operation to match.
8119/// For example, if \p Opcode is equal to ISD::ADD, then this function
8120/// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
8121/// is equal to ISD::SUB, then this function checks if this is a horizontal
8122/// arithmetic sub.
8123///
8124/// This function only analyzes elements of \p N whose indices are
8125/// in range [BaseIdx, LastIdx).
8126///
8127/// TODO: This function was originally used to match both real and fake partial
8128/// horizontal operations, but the index-matching logic is incorrect for that.
8129/// See the corrected implementation in isHopBuildVector(). Can we reduce this
8130/// code because it is only used for partial h-op matching now?
8131static bool isHorizontalBinOpPart(const BuildVectorSDNode *N, unsigned Opcode,
8132 SelectionDAG &DAG,
8133 unsigned BaseIdx, unsigned LastIdx,
8134 SDValue &V0, SDValue &V1) {
8135 EVT VT = N->getValueType(0);
8136 assert(VT.is256BitVector() && "Only use for matching partial 256-bit h-ops")((VT.is256BitVector() && "Only use for matching partial 256-bit h-ops"
) ? static_cast<void> (0) : __assert_fail ("VT.is256BitVector() && \"Only use for matching partial 256-bit h-ops\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 8136, __PRETTY_FUNCTION__))
;
8137 assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!")((BaseIdx * 2 <= LastIdx && "Invalid Indices in input!"
) ? static_cast<void> (0) : __assert_fail ("BaseIdx * 2 <= LastIdx && \"Invalid Indices in input!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 8137, __PRETTY_FUNCTION__))
;
8138 assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&((VT.isVector() && VT.getVectorNumElements() >= LastIdx
&& "Invalid Vector in input!") ? static_cast<void
> (0) : __assert_fail ("VT.isVector() && VT.getVectorNumElements() >= LastIdx && \"Invalid Vector in input!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 8139, __PRETTY_FUNCTION__))
8139 "Invalid Vector in input!")((VT.isVector() && VT.getVectorNumElements() >= LastIdx
&& "Invalid Vector in input!") ? static_cast<void
> (0) : __assert_fail ("VT.isVector() && VT.getVectorNumElements() >= LastIdx && \"Invalid Vector in input!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 8139, __PRETTY_FUNCTION__))
;
8140
8141 bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
8142 bool CanFold = true;
8143 unsigned ExpectedVExtractIdx = BaseIdx;
8144 unsigned NumElts = LastIdx - BaseIdx;
8145 V0 = DAG.getUNDEF(VT);
8146 V1 = DAG.getUNDEF(VT);
8147
8148 // Check if N implements a horizontal binop.
8149 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
8150 SDValue Op = N->getOperand(i + BaseIdx);
8151
8152 // Skip UNDEFs.
8153 if (Op->isUndef()) {
8154 // Update the expected vector extract index.
8155 if (i * 2 == NumElts)
8156 ExpectedVExtractIdx = BaseIdx;
8157 ExpectedVExtractIdx += 2;
8158 continue;
8159 }
8160
8161 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
8162
8163 if (!CanFold)
8164 break;
8165
8166 SDValue Op0 = Op.getOperand(0);
8167 SDValue Op1 = Op.getOperand(1);
8168
8169 // Try to match the following pattern:
8170 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
8171 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
8172 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
8173 Op0.getOperand(0) == Op1.getOperand(0) &&
8174 isa<ConstantSDNode>(Op0.getOperand(1)) &&
8175 isa<ConstantSDNode>(Op1.getOperand(1)));
8176 if (!CanFold)
8177 break;
8178
8179 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
8180 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
8181
8182 if (i * 2 < NumElts) {
8183 if (V0.isUndef()) {
8184 V0 = Op0.getOperand(0);
8185 if (V0.getValueType() != VT)
8186 return false;
8187 }
8188 } else {
8189 if (V1.isUndef()) {
8190 V1 = Op0.getOperand(0);
8191 if (V1.getValueType() != VT)
8192 return false;
8193 }
8194 if (i * 2 == NumElts)
8195 ExpectedVExtractIdx = BaseIdx;
8196 }
8197
8198 SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
8199 if (I0 == ExpectedVExtractIdx)
8200 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
8201 else if (IsCommutable && I1 == ExpectedVExtractIdx) {
8202 // Try to match the following dag sequence:
8203 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
8204 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
8205 } else
8206 CanFold = false;
8207
8208 ExpectedVExtractIdx += 2;
8209 }
8210
8211 return CanFold;
8212}
8213
8214/// Emit a sequence of two 128-bit horizontal add/sub followed by
8215/// a concat_vector.
8216///
8217/// This is a helper function of LowerToHorizontalOp().
8218/// This function expects two 256-bit vectors called V0 and V1.
8219/// At first, each vector is split into two separate 128-bit vectors.
8220/// Then, the resulting 128-bit vectors are used to implement two
8221/// horizontal binary operations.
8222///
8223/// The kind of horizontal binary operation is defined by \p X86Opcode.
8224///
8225/// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
8226/// the two new horizontal binop.
8227/// When Mode is set, the first horizontal binop dag node would take as input
8228/// the lower 128-bit of V0 and the upper 128-bit of V0. The second
8229/// horizontal binop dag node would take as input the lower 128-bit of V1
8230/// and the upper 128-bit of V1.
8231/// Example:
8232/// HADD V0_LO, V0_HI
8233/// HADD V1_LO, V1_HI
8234///
8235/// Otherwise, the first horizontal binop dag node takes as input the lower
8236/// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
8237/// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
8238/// Example:
8239/// HADD V0_LO, V1_LO
8240/// HADD V0_HI, V1_HI
8241///
8242/// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
8243/// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
8244/// the upper 128-bits of the result.
8245static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
8246 const SDLoc &DL, SelectionDAG &DAG,
8247 unsigned X86Opcode, bool Mode,
8248 bool isUndefLO, bool isUndefHI) {
8249 MVT VT = V0.getSimpleValueType();
8250 assert(VT.is256BitVector() && VT == V1.getSimpleValueType() &&((VT.is256BitVector() && VT == V1.getSimpleValueType(
) && "Invalid nodes in input!") ? static_cast<void
> (0) : __assert_fail ("VT.is256BitVector() && VT == V1.getSimpleValueType() && \"Invalid nodes in input!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 8251, __PRETTY_FUNCTION__))
8251 "Invalid nodes in input!")((VT.is256BitVector() && VT == V1.getSimpleValueType(
) && "Invalid nodes in input!") ? static_cast<void
> (0) : __assert_fail ("VT.is256BitVector() && VT == V1.getSimpleValueType() && \"Invalid nodes in input!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 8251, __PRETTY_FUNCTION__))
;
8252
8253 unsigned NumElts = VT.getVectorNumElements();
8254 SDValue V0_LO = extract128BitVector(V0, 0, DAG, DL);
8255 SDValue V0_HI = extract128BitVector(V0, NumElts/2, DAG, DL);
8256 SDValue V1_LO = extract128BitVector(V1, 0, DAG, DL);
8257 SDValue V1_HI = extract128BitVector(V1, NumElts/2, DAG, DL);
8258 MVT NewVT = V0_LO.getSimpleValueType();
8259
8260 SDValue LO = DAG.getUNDEF(NewVT);
8261 SDValue HI = DAG.getUNDEF(NewVT);
8262
8263 if (Mode) {
8264 // Don't emit a horizontal binop if the result is expected to be UNDEF.
8265 if (!isUndefLO && !V0->isUndef())
8266 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
8267 if (!isUndefHI && !V1->isUndef())
8268 HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
8269 } else {
8270 // Don't emit a horizontal binop if the result is expected to be UNDEF.
8271 if (!isUndefLO && (!V0_LO->isUndef() || !V1_LO->isUndef()))
8272 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
8273
8274 if (!isUndefHI && (!V0_HI->isUndef() || !V1_HI->isUndef()))
8275 HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
8276 }
8277
8278 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
8279}
8280
8281/// Returns true iff \p BV builds a vector with the result equivalent to
8282/// the result of ADDSUB/SUBADD operation.
8283/// If true is returned then the operands of ADDSUB = Opnd0 +- Opnd1
8284/// (SUBADD = Opnd0 -+ Opnd1) operation are written to the parameters
8285/// \p Opnd0 and \p Opnd1.
8286static bool isAddSubOrSubAdd(const BuildVectorSDNode *BV,
8287 const X86Subtarget &Subtarget, SelectionDAG &DAG,
8288 SDValue &Opnd0, SDValue &Opnd1,
8289 unsigned &NumExtracts,
8290 bool &IsSubAdd) {
8291
8292 MVT VT = BV->getSimpleValueType(0);
8293 if (!Subtarget.hasSSE3() || !VT.isFloatingPoint())
8294 return false;
8295
8296 unsigned NumElts = VT.getVectorNumElements();
8297 SDValue InVec0 = DAG.getUNDEF(VT);
8298 SDValue InVec1 = DAG.getUNDEF(VT);
8299
8300 NumExtracts = 0;
8301
8302 // Odd-numbered elements in the input build vector are obtained from
8303 // adding/subtracting two integer/float elements.
8304 // Even-numbered elements in the input build vector are obtained from
8305 // subtracting/adding two integer/float elements.
8306 unsigned Opc[2] = {0, 0};
8307 for (unsigned i = 0, e = NumElts; i != e; ++i) {
8308 SDValue Op = BV->getOperand(i);
8309
8310 // Skip 'undef' values.
8311 unsigned Opcode = Op.getOpcode();
8312 if (Opcode == ISD::UNDEF)
8313 continue;
8314
8315 // Early exit if we found an unexpected opcode.
8316 if (Opcode != ISD::FADD && Opcode != ISD::FSUB)
8317 return false;
8318
8319 SDValue Op0 = Op.getOperand(0);
8320 SDValue Op1 = Op.getOperand(1);
8321
8322 // Try to match the following pattern:
8323 // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
8324 // Early exit if we cannot match that sequence.
8325 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8326 Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8327 !isa<ConstantSDNode>(Op0.getOperand(1)) ||
8328 !isa<ConstantSDNode>(Op1.getOperand(1)) ||
8329 Op0.getOperand(1) != Op1.getOperand(1))
8330 return false;
8331
8332 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
8333 if (I0 != i)
8334 return false;
8335
8336 // We found a valid add/sub node, make sure its the same opcode as previous
8337 // elements for this parity.
8338 if (Opc[i % 2] != 0 && Opc[i % 2] != Opcode)
8339 return false;
8340 Opc[i % 2] = Opcode;
8341
8342 // Update InVec0 and InVec1.
8343 if (InVec0.isUndef()) {
8344 InVec0 = Op0.getOperand(0);
8345 if (InVec0.getSimpleValueType() != VT)
8346 return false;
8347 }
8348 if (InVec1.isUndef()) {
8349 InVec1 = Op1.getOperand(0);
8350 if (InVec1.getSimpleValueType() != VT)
8351 return false;
8352 }
8353
8354 // Make sure that operands in input to each add/sub node always
8355 // come from a same pair of vectors.
8356 if (InVec0 != Op0.getOperand(0)) {
8357 if (Opcode == ISD::FSUB)
8358 return false;
8359
8360 // FADD is commutable. Try to commute the operands
8361 // and then test again.
8362 std::swap(Op0, Op1);
8363 if (InVec0 != Op0.getOperand(0))
8364 return false;
8365 }
8366
8367 if (InVec1 != Op1.getOperand(0))
8368 return false;
8369
8370 // Increment the number of extractions done.
8371 ++NumExtracts;
8372 }
8373
8374 // Ensure we have found an opcode for both parities and that they are
8375 // different. Don't try to fold this build_vector into an ADDSUB/SUBADD if the
8376 // inputs are undef.
8377 if (!Opc[0] || !Opc[1] || Opc[0] == Opc[1] ||
8378 InVec0.isUndef() || InVec1.isUndef())
8379 return false;
8380
8381 IsSubAdd = Opc[0] == ISD::FADD;
8382
8383 Opnd0 = InVec0;
8384 Opnd1 = InVec1;
8385 return true;
8386}
8387
8388/// Returns true if is possible to fold MUL and an idiom that has already been
8389/// recognized as ADDSUB/SUBADD(\p Opnd0, \p Opnd1) into
8390/// FMADDSUB/FMSUBADD(x, y, \p Opnd1). If (and only if) true is returned, the
8391/// operands of FMADDSUB/FMSUBADD are written to parameters \p Opnd0, \p Opnd1, \p Opnd2.
8392///
8393/// Prior to calling this function it should be known that there is some
8394/// SDNode that potentially can be replaced with an X86ISD::ADDSUB operation
8395/// using \p Opnd0 and \p Opnd1 as operands. Also, this method is called
8396/// before replacement of such SDNode with ADDSUB operation. Thus the number
8397/// of \p Opnd0 uses is expected to be equal to 2.
8398/// For example, this function may be called for the following IR:
8399/// %AB = fmul fast <2 x double> %A, %B
8400/// %Sub = fsub fast <2 x double> %AB, %C
8401/// %Add = fadd fast <2 x double> %AB, %C
8402/// %Addsub = shufflevector <2 x double> %Sub, <2 x double> %Add,
8403/// <2 x i32> <i32 0, i32 3>
8404/// There is a def for %Addsub here, which potentially can be replaced by
8405/// X86ISD::ADDSUB operation:
8406/// %Addsub = X86ISD::ADDSUB %AB, %C
8407/// and such ADDSUB can further be replaced with FMADDSUB:
8408/// %Addsub = FMADDSUB %A, %B, %C.
8409///
8410/// The main reason why this method is called before the replacement of the
8411/// recognized ADDSUB idiom with ADDSUB operation is that such replacement
8412/// is illegal sometimes. E.g. 512-bit ADDSUB is not available, while 512-bit
8413/// FMADDSUB is.
8414static bool isFMAddSubOrFMSubAdd(const X86Subtarget &Subtarget,
8415 SelectionDAG &DAG,
8416 SDValue &Opnd0, SDValue &Opnd1, SDValue &Opnd2,
8417 unsigned ExpectedUses) {
8418 if (Opnd0.getOpcode() != ISD::FMUL ||
8419 !Opnd0->hasNUsesOfValue(ExpectedUses, 0) || !Subtarget.hasAnyFMA())
8420 return false;
8421
8422 // FIXME: These checks must match the similar ones in
8423 // DAGCombiner::visitFADDForFMACombine. It would be good to have one
8424 // function that would answer if it is Ok to fuse MUL + ADD to FMADD
8425 // or MUL + ADDSUB to FMADDSUB.
8426 const TargetOptions &Options = DAG.getTarget().Options;
8427 bool AllowFusion =
8428 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
8429 if (!AllowFusion)
8430 return false;
8431
8432 Opnd2 = Opnd1;
8433 Opnd1 = Opnd0.getOperand(1);
8434 Opnd0 = Opnd0.getOperand(0);
8435
8436 return true;
8437}
8438
8439/// Try to fold a build_vector that performs an 'addsub' or 'fmaddsub' or
8440/// 'fsubadd' operation accordingly to X86ISD::ADDSUB or X86ISD::FMADDSUB or
8441/// X86ISD::FMSUBADD node.
8442static SDValue lowerToAddSubOrFMAddSub(const BuildVectorSDNode *BV,
8443 const X86Subtarget &Subtarget,
8444 SelectionDAG &DAG) {
8445 SDValue Opnd0, Opnd1;
8446 unsigned NumExtracts;
8447 bool IsSubAdd;
8448 if (!isAddSubOrSubAdd(BV, Subtarget, DAG, Opnd0, Opnd1, NumExtracts,
8449 IsSubAdd))
8450 return SDValue();
8451
8452 MVT VT = BV->getSimpleValueType(0);
8453 SDLoc DL(BV);
8454
8455 // Try to generate X86ISD::FMADDSUB node here.
8456 SDValue Opnd2;
8457 if (isFMAddSubOrFMSubAdd(Subtarget, DAG, Opnd0, Opnd1, Opnd2, NumExtracts)) {
8458 unsigned Opc = IsSubAdd ? X86ISD::FMSUBADD : X86ISD::FMADDSUB;
8459 return DAG.getNode(Opc, DL, VT, Opnd0, Opnd1, Opnd2);
8460 }
8461
8462 // We only support ADDSUB.
8463 if (IsSubAdd)
8464 return SDValue();
8465
8466 // Do not generate X86ISD::ADDSUB node for 512-bit types even though
8467 // the ADDSUB idiom has been successfully recognized. There are no known
8468 // X86 targets with 512-bit ADDSUB instructions!
8469 // 512-bit ADDSUB idiom recognition was needed only as part of FMADDSUB idiom
8470 // recognition.
8471 if (VT.is512BitVector())
8472 return SDValue();
8473
8474 return DAG.getNode(X86ISD::ADDSUB, DL, VT, Opnd0, Opnd1);
8475}
8476
8477static bool isHopBuildVector(const BuildVectorSDNode *BV, SelectionDAG &DAG,
8478 unsigned &HOpcode, SDValue &V0, SDValue &V1) {
8479 // Initialize outputs to known values.
8480 MVT VT = BV->getSimpleValueType(0);
8481 HOpcode = ISD::DELETED_NODE;
8482 V0 = DAG.getUNDEF(VT);
8483 V1 = DAG.getUNDEF(VT);
8484
8485 // x86 256-bit horizontal ops are defined in a non-obvious way. Each 128-bit
8486 // half of the result is calculated independently from the 128-bit halves of
8487 // the inputs, so that makes the index-checking logic below more complicated.
8488 unsigned NumElts = VT.getVectorNumElements();
8489 unsigned GenericOpcode = ISD::DELETED_NODE;
8490 unsigned Num128BitChunks = VT.is256BitVector() ? 2 : 1;
8491 unsigned NumEltsIn128Bits = NumElts / Num128BitChunks;
8492 unsigned NumEltsIn64Bits = NumEltsIn128Bits / 2;
8493 for (unsigned i = 0; i != Num128BitChunks; ++i) {
8494 for (unsigned j = 0; j != NumEltsIn128Bits; ++j) {
8495 // Ignore undef elements.
8496 SDValue Op = BV->getOperand(i * NumEltsIn128Bits + j);
8497 if (Op.isUndef())
8498 continue;
8499
8500 // If there's an opcode mismatch, we're done.
8501 if (HOpcode != ISD::DELETED_NODE && Op.getOpcode() != GenericOpcode)
8502 return false;
8503
8504 // Initialize horizontal opcode.
8505 if (HOpcode == ISD::DELETED_NODE) {
8506 GenericOpcode = Op.getOpcode();
8507 switch (GenericOpcode) {
8508 case ISD::ADD: HOpcode = X86ISD::HADD; break;
8509 case ISD::SUB: HOpcode = X86ISD::HSUB; break;
8510 case ISD::FADD: HOpcode = X86ISD::FHADD; break;
8511 case ISD::FSUB: HOpcode = X86ISD::FHSUB; break;
8512 default: return false;
8513 }
8514 }
8515
8516 SDValue Op0 = Op.getOperand(0);
8517 SDValue Op1 = Op.getOperand(1);
8518 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8519 Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8520 Op0.getOperand(0) != Op1.getOperand(0) ||
8521 !isa<ConstantSDNode>(Op0.getOperand(1)) ||
8522 !isa<ConstantSDNode>(Op1.getOperand(1)) || !Op.hasOneUse())
8523 return false;
8524
8525 // The source vector is chosen based on which 64-bit half of the
8526 // destination vector is being calculated.
8527 if (j < NumEltsIn64Bits) {
8528 if (V0.isUndef())
8529 V0 = Op0.getOperand(0);
8530 } else {
8531 if (V1.isUndef())
8532 V1 = Op0.getOperand(0);
8533 }
8534
8535 SDValue SourceVec = (j < NumEltsIn64Bits) ? V0 : V1;
8536 if (SourceVec != Op0.getOperand(0))
8537 return false;
8538
8539 // op (extract_vector_elt A, I), (extract_vector_elt A, I+1)
8540 unsigned ExtIndex0 = Op0.getConstantOperandVal(1);
8541 unsigned ExtIndex1 = Op1.getConstantOperandVal(1);
8542 unsigned ExpectedIndex = i * NumEltsIn128Bits +
8543 (j % NumEltsIn64Bits) * 2;
8544 if (ExpectedIndex == ExtIndex0 && ExtIndex1 == ExtIndex0 + 1)
8545 continue;
8546
8547 // If this is not a commutative op, this does not match.
8548 if (GenericOpcode != ISD::ADD && GenericOpcode != ISD::FADD)
8549 return false;
8550
8551 // Addition is commutative, so try swapping the extract indexes.
8552 // op (extract_vector_elt A, I+1), (extract_vector_elt A, I)
8553 if (ExpectedIndex == ExtIndex1 && ExtIndex0 == ExtIndex1 + 1)
8554 continue;
8555
8556 // Extract indexes do not match horizontal requirement.
8557 return false;
8558 }
8559 }
8560 // We matched. Opcode and operands are returned by reference as arguments.
8561 return true;
8562}
8563
8564static SDValue getHopForBuildVector(const BuildVectorSDNode *BV,
8565 SelectionDAG &DAG, unsigned HOpcode,
8566 SDValue V0, SDValue V1) {
8567 // If either input vector is not the same size as the build vector,
8568 // extract/insert the low bits to the correct size.
8569 // This is free (examples: zmm --> xmm, xmm --> ymm).
8570 MVT VT = BV->getSimpleValueType(0);
8571 unsigned Width = VT.getSizeInBits();
8572 if (V0.getValueSizeInBits() > Width)
8573 V0 = extractSubVector(V0, 0, DAG, SDLoc(BV), Width);
8574 else if (V0.getValueSizeInBits() < Width)
8575 V0 = insertSubVector(DAG.getUNDEF(VT), V0, 0, DAG, SDLoc(BV), Width);
8576
8577 if (V1.getValueSizeInBits() > Width)
8578 V1 = extractSubVector(V1, 0, DAG, SDLoc(BV), Width);
8579 else if (V1.getValueSizeInBits() < Width)
8580 V1 = insertSubVector(DAG.getUNDEF(VT), V1, 0, DAG, SDLoc(BV), Width);
8581
8582 unsigned NumElts = VT.getVectorNumElements();
8583 APInt DemandedElts = APInt::getAllOnesValue(NumElts);
8584 for (unsigned i = 0; i != NumElts; ++i)
8585 if (BV->getOperand(i).isUndef())
8586 DemandedElts.clearBit(i);
8587
8588 // If we don't need the upper xmm, then perform as a xmm hop.
8589 unsigned HalfNumElts = NumElts / 2;
8590 if (VT.is256BitVector() && DemandedElts.lshr(HalfNumElts) == 0) {
8591 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(), HalfNumElts);
8592 V0 = extractSubVector(V0, 0, DAG, SDLoc(BV), 128);
8593 V1 = extractSubVector(V1, 0, DAG, SDLoc(BV), 128);
8594 SDValue Half = DAG.getNode(HOpcode, SDLoc(BV), HalfVT, V0, V1);
8595 return insertSubVector(DAG.getUNDEF(VT), Half, 0, DAG, SDLoc(BV), 256);
8596 }
8597
8598 return DAG.getNode(HOpcode, SDLoc(BV), VT, V0, V1);
8599}
8600
8601/// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
8602static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
8603 const X86Subtarget &Subtarget,
8604 SelectionDAG &DAG) {
8605 // We need at least 2 non-undef elements to make this worthwhile by default.
8606 unsigned NumNonUndefs = 0;
8607 for (const SDValue &V : BV->op_values())
8608 if (!V.isUndef())
8609 ++NumNonUndefs;
8610
8611 if (NumNonUndefs < 2)
8612 return SDValue();
8613
8614 // There are 4 sets of horizontal math operations distinguished by type:
8615 // int/FP at 128-bit/256-bit. Each type was introduced with a different
8616 // subtarget feature. Try to match those "native" patterns first.
8617 MVT VT = BV->getSimpleValueType(0);
8618 if (((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget.hasSSE3()) ||
8619 ((VT == MVT::v8i16 || VT == MVT::v4i32) && Subtarget.hasSSSE3()) ||
8620 ((VT == MVT::v8f32 || VT == MVT::v4f64) && Subtarget.hasAVX()) ||
8621 ((VT == MVT::v16i16 || VT == MVT::v8i32) && Subtarget.hasAVX2())) {
8622 unsigned HOpcode;
8623 SDValue V0, V1;
8624 if (isHopBuildVector(BV, DAG, HOpcode, V0, V1))
8625 return getHopForBuildVector(BV, DAG, HOpcode, V0, V1);
8626 }
8627
8628 // Try harder to match 256-bit ops by using extract/concat.
8629 if (!Subtarget.hasAVX() || !VT.is256BitVector())
8630 return SDValue();
8631
8632 // Count the number of UNDEF operands in the build_vector in input.
8633 unsigned NumElts = VT.getVectorNumElements();
8634 unsigned Half = NumElts / 2;
8635 unsigned NumUndefsLO = 0;
8636 unsigned NumUndefsHI = 0;
8637 for (unsigned i = 0, e = Half; i != e; ++i)
8638 if (BV->getOperand(i)->isUndef())
8639 NumUndefsLO++;
8640
8641 for (unsigned i = Half, e = NumElts; i != e; ++i)
8642 if (BV->getOperand(i)->isUndef())
8643 NumUndefsHI++;
8644
8645 SDLoc DL(BV);
8646 SDValue InVec0, InVec1;
8647 if (VT == MVT::v8i32 || VT == MVT::v16i16) {
8648 SDValue InVec2, InVec3;
8649 unsigned X86Opcode;
8650 bool CanFold = true;
8651
8652 if (isHorizontalBinOpPart(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
8653 isHorizontalBinOpPart(BV, ISD::ADD, DAG, Half, NumElts, InVec2,
8654 InVec3) &&
8655 ((InVec0.isUndef() || InVec2.isUndef()) || InVec0 == InVec2) &&
8656 ((InVec1.isUndef() || InVec3.isUndef()) || InVec1 == InVec3))
8657 X86Opcode = X86ISD::HADD;
8658 else if (isHorizontalBinOpPart(BV, ISD::SUB, DAG, 0, Half, InVec0,
8659 InVec1) &&
8660 isHorizontalBinOpPart(BV, ISD::SUB, DAG, Half, NumElts, InVec2,
8661 InVec3) &&
8662 ((InVec0.isUndef() || InVec2.isUndef()) || InVec0 == InVec2) &&
8663 ((InVec1.isUndef() || InVec3.isUndef()) || InVec1 == InVec3))
8664 X86Opcode = X86ISD::HSUB;
8665 else
8666 CanFold = false;
8667
8668 if (CanFold) {
8669 // Do not try to expand this build_vector into a pair of horizontal
8670 // add/sub if we can emit a pair of scalar add/sub.
8671 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
8672 return SDValue();
8673
8674 // Convert this build_vector into a pair of horizontal binops followed by
8675 // a concat vector. We must adjust the outputs from the partial horizontal
8676 // matching calls above to account for undefined vector halves.
8677 SDValue V0 = InVec0.isUndef() ? InVec2 : InVec0;
8678 SDValue V1 = InVec1.isUndef() ? InVec3 : InVec1;
8679 assert((!V0.isUndef() || !V1.isUndef()) && "Horizontal-op of undefs?")(((!V0.isUndef() || !V1.isUndef()) && "Horizontal-op of undefs?"
) ? static_cast<void> (0) : __assert_fail ("(!V0.isUndef() || !V1.isUndef()) && \"Horizontal-op of undefs?\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 8679, __PRETTY_FUNCTION__))
;
8680 bool isUndefLO = NumUndefsLO == Half;
8681 bool isUndefHI = NumUndefsHI == Half;
8682 return ExpandHorizontalBinOp(V0, V1, DL, DAG, X86Opcode, false, isUndefLO,
8683 isUndefHI);
8684 }
8685 }
8686
8687 if (VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
8688 VT == MVT::v16i16) {
8689 unsigned X86Opcode;
8690 if (isHorizontalBinOpPart(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
8691 X86Opcode = X86ISD::HADD;
8692 else if (isHorizontalBinOpPart(BV, ISD::SUB, DAG, 0, NumElts, InVec0,
8693 InVec1))
8694 X86Opcode = X86ISD::HSUB;
8695 else if (isHorizontalBinOpPart(BV, ISD::FADD, DAG, 0, NumElts, InVec0,
8696 InVec1))
8697 X86Opcode = X86ISD::FHADD;
8698 else if (isHorizontalBinOpPart(BV, ISD::FSUB, DAG, 0, NumElts, InVec0,
8699 InVec1))
8700 X86Opcode = X86ISD::FHSUB;
8701 else
8702 return SDValue();
8703
8704 // Don't try to expand this build_vector into a pair of horizontal add/sub
8705 // if we can simply emit a pair of scalar add/sub.
8706 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
8707 return SDValue();
8708
8709 // Convert this build_vector into two horizontal add/sub followed by
8710 // a concat vector.
8711 bool isUndefLO = NumUndefsLO == Half;
8712 bool isUndefHI = NumUndefsHI == Half;
8713 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
8714 isUndefLO, isUndefHI);
8715 }
8716
8717 return SDValue();
8718}
8719
8720/// If a BUILD_VECTOR's source elements all apply the same bit operation and
8721/// one of their operands is constant, lower to a pair of BUILD_VECTOR and
8722/// just apply the bit to the vectors.
8723/// NOTE: Its not in our interest to start make a general purpose vectorizer
8724/// from this, but enough scalar bit operations are created from the later
8725/// legalization + scalarization stages to need basic support.
8726static SDValue lowerBuildVectorToBitOp(BuildVectorSDNode *Op,
8727 SelectionDAG &DAG) {
8728 SDLoc DL(Op);
8729 MVT VT = Op->getSimpleValueType(0);
8730 unsigned NumElems = VT.getVectorNumElements();
8731 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8732
8733 // Check that all elements have the same opcode.
8734 // TODO: Should we allow UNDEFS and if so how many?
8735 unsigned Opcode = Op->getOperand(0).getOpcode();
8736 for (unsigned i = 1; i < NumElems; ++i)
8737 if (Opcode != Op->getOperand(i).getOpcode())
8738 return SDValue();
8739
8740 // TODO: We may be able to add support for other Ops (ADD/SUB + shifts).
8741 bool IsShift = false;
8742 switch (Opcode) {
8743 default:
8744 return SDValue();
8745 case ISD::SHL:
8746 case ISD::SRL:
8747 case ISD::SRA:
8748 IsShift = true;
8749 break;
8750 case ISD::AND:
8751 case ISD::XOR:
8752 case ISD::OR:
8753 // Don't do this if the buildvector is a splat - we'd replace one
8754 // constant with an entire vector.
8755 if (Op->getSplatValue())
8756 return SDValue();
8757 if (!TLI.isOperationLegalOrPromote(Opcode, VT))
8758 return SDValue();
8759 break;
8760 }
8761
8762 SmallVector<SDValue, 4> LHSElts, RHSElts;
8763 for (SDValue Elt : Op->ops()) {
8764 SDValue LHS = Elt.getOperand(0);
8765 SDValue RHS = Elt.getOperand(1);
8766
8767 // We expect the canonicalized RHS operand to be the constant.
8768 if (!isa<ConstantSDNode>(RHS))
8769 return SDValue();
8770
8771 // Extend shift amounts.
8772 if (RHS.getValueSizeInBits() != VT.getScalarSizeInBits()) {
8773 if (!IsShift)
8774 return SDValue();
8775 RHS = DAG.getZExtOrTrunc(RHS, DL, VT.getScalarType());
8776 }
8777
8778 LHSElts.push_back(LHS);
8779 RHSElts.push_back(RHS);
8780 }
8781
8782 // Limit to shifts by uniform immediates.
8783 // TODO: Only accept vXi8/vXi64 special cases?
8784 // TODO: Permit non-uniform XOP/AVX2/MULLO cases?
8785 if (IsShift && any_of(RHSElts, [&](SDValue V) { return RHSElts[0] != V; }))
8786 return SDValue();
8787
8788 SDValue LHS = DAG.getBuildVector(VT, DL, LHSElts);
8789 SDValue RHS = DAG.getBuildVector(VT, DL, RHSElts);
8790 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
8791}
8792
8793/// Create a vector constant without a load. SSE/AVX provide the bare minimum
8794/// functionality to do this, so it's all zeros, all ones, or some derivation
8795/// that is cheap to calculate.
8796static SDValue materializeVectorConstant(SDValue Op, SelectionDAG &DAG,
8797 const X86Subtarget &Subtarget) {
8798 SDLoc DL(Op);
8799 MVT VT = Op.getSimpleValueType();
8800
8801 // Vectors containing all zeros can be matched by pxor and xorps.
8802 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
8803 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
8804 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
8805 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
8806 return Op;
8807
8808 return getZeroVector(VT, Subtarget, DAG, DL);
8809 }
8810
8811 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
8812 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
8813 // vpcmpeqd on 256-bit vectors.
8814 if (Subtarget.hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
8815 if (VT == MVT::v4i32 || VT == MVT::v16i32 ||
8816 (VT == MVT::v8i32 && Subtarget.hasInt256()))
8817 return Op;
8818
8819 return getOnesVector(VT, DAG, DL);
8820 }
8821
8822 return SDValue();
8823}
8824
8825/// Look for opportunities to create a VPERMV/VPERMILPV/PSHUFB variable permute
8826/// from a vector of source values and a vector of extraction indices.
8827/// The vectors might be manipulated to match the type of the permute op.
8828static SDValue createVariablePermute(MVT VT, SDValue SrcVec, SDValue IndicesVec,
8829 SDLoc &DL, SelectionDAG &DAG,
8830 const X86Subtarget &Subtarget) {
8831 MVT ShuffleVT = VT;
8832 EVT IndicesVT = EVT(VT).changeVectorElementTypeToInteger();
8833 unsigned NumElts = VT.getVectorNumElements();
8834 unsigned SizeInBits = VT.getSizeInBits();
8835
8836 // Adjust IndicesVec to match VT size.
8837 assert(IndicesVec.getValueType().getVectorNumElements() >= NumElts &&((IndicesVec.getValueType().getVectorNumElements() >= NumElts
&& "Illegal variable permute mask size") ? static_cast
<void> (0) : __assert_fail ("IndicesVec.getValueType().getVectorNumElements() >= NumElts && \"Illegal variable permute mask size\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 8838, __PRETTY_FUNCTION__))
8838 "Illegal variable permute mask size")((IndicesVec.getValueType().getVectorNumElements() >= NumElts
&& "Illegal variable permute mask size") ? static_cast
<void> (0) : __assert_fail ("IndicesVec.getValueType().getVectorNumElements() >= NumElts && \"Illegal variable permute mask size\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 8838, __PRETTY_FUNCTION__))
;
8839 if (IndicesVec.getValueType().getVectorNumElements() > NumElts)
8840 IndicesVec = extractSubVector(IndicesVec, 0, DAG, SDLoc(IndicesVec),
8841 NumElts * VT.getScalarSizeInBits());
8842 IndicesVec = DAG.getZExtOrTrunc(IndicesVec, SDLoc(IndicesVec), IndicesVT);
8843
8844 // Handle SrcVec that don't match VT type.
8845 if (SrcVec.getValueSizeInBits() != SizeInBits) {
8846 if ((SrcVec.getValueSizeInBits() % SizeInBits) == 0) {
8847 // Handle larger SrcVec by treating it as a larger permute.
8848 unsigned Scale = SrcVec.getValueSizeInBits() / SizeInBits;
8849 VT = MVT::getVectorVT(VT.getScalarType(), Scale * NumElts);
8850 IndicesVT = EVT(VT).changeVectorElementTypeToInteger();
8851 IndicesVec = widenSubVector(IndicesVT.getSimpleVT(), IndicesVec, false,
8852 Subtarget, DAG, SDLoc(IndicesVec));
8853 return extractSubVector(
8854 createVariablePermute(VT, SrcVec, IndicesVec, DL, DAG, Subtarget), 0,
8855 DAG, DL, SizeInBits);
8856 } else if (SrcVec.getValueSizeInBits() < SizeInBits) {
8857 // Widen smaller SrcVec to match VT.
8858 SrcVec = widenSubVector(VT, SrcVec, false, Subtarget, DAG, SDLoc(SrcVec));
8859 } else
8860 return SDValue();
8861 }
8862
8863 auto ScaleIndices = [&DAG](SDValue Idx, uint64_t Scale) {
8864 assert(isPowerOf2_64(Scale) && "Illegal variable permute shuffle scale")((isPowerOf2_64(Scale) && "Illegal variable permute shuffle scale"
) ? static_cast<void> (0) : __assert_fail ("isPowerOf2_64(Scale) && \"Illegal variable permute shuffle scale\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 8864, __PRETTY_FUNCTION__))
;
8865 EVT SrcVT = Idx.getValueType();
8866 unsigned NumDstBits = SrcVT.getScalarSizeInBits() / Scale;
8867 uint64_t IndexScale = 0;
8868 uint64_t IndexOffset = 0;
8869
8870 // If we're scaling a smaller permute op, then we need to repeat the
8871 // indices, scaling and offsetting them as well.
8872 // e.g. v4i32 -> v16i8 (Scale = 4)
8873 // IndexScale = v4i32 Splat(4 << 24 | 4 << 16 | 4 << 8 | 4)
8874 // IndexOffset = v4i32 Splat(3 << 24 | 2 << 16 | 1 << 8 | 0)
8875 for (uint64_t i = 0; i != Scale; ++i) {
8876 IndexScale |= Scale << (i * NumDstBits);
8877 IndexOffset |= i << (i * NumDstBits);
8878 }
8879
8880 Idx = DAG.getNode(ISD::MUL, SDLoc(Idx), SrcVT, Idx,
8881 DAG.getConstant(IndexScale, SDLoc(Idx), SrcVT));
8882 Idx = DAG.getNode(ISD::ADD, SDLoc(Idx), SrcVT, Idx,
8883 DAG.getConstant(IndexOffset, SDLoc(Idx), SrcVT));
8884 return Idx;
8885 };
8886
8887 unsigned Opcode = 0;
8888 switch (VT.SimpleTy) {
8889 default:
8890 break;
8891 case MVT::v16i8:
8892 if (Subtarget.hasSSSE3())
8893 Opcode = X86ISD::PSHUFB;
8894 break;
8895 case MVT::v8i16:
8896 if (Subtarget.hasVLX() && Subtarget.hasBWI())
8897 Opcode = X86ISD::VPERMV;
8898 else if (Subtarget.hasSSSE3()) {
8899 Opcode = X86ISD::PSHUFB;
8900 ShuffleVT = MVT::v16i8;
8901 }
8902 break;
8903 case MVT::v4f32:
8904 case MVT::v4i32:
8905 if (Subtarget.hasAVX()) {
8906 Opcode = X86ISD::VPERMILPV;
8907 ShuffleVT = MVT::v4f32;
8908 } else if (Subtarget.hasSSSE3()) {
8909 Opcode = X86ISD::PSHUFB;
8910 ShuffleVT = MVT::v16i8;
8911 }
8912 break;
8913 case MVT::v2f64:
8914 case MVT::v2i64:
8915 if (Subtarget.hasAVX()) {
8916 // VPERMILPD selects using bit#1 of the index vector, so scale IndicesVec.
8917 IndicesVec = DAG.getNode(ISD::ADD, DL, IndicesVT, IndicesVec, IndicesVec);
8918 Opcode = X86ISD::VPERMILPV;
8919 ShuffleVT = MVT::v2f64;
8920 } else if (Subtarget.hasSSE41()) {
8921 // SSE41 can compare v2i64 - select between indices 0 and 1.
8922 return DAG.getSelectCC(
8923 DL, IndicesVec,
8924 getZeroVector(IndicesVT.getSimpleVT(), Subtarget, DAG, DL),
8925 DAG.getVectorShuffle(VT, DL, SrcVec, SrcVec, {0, 0}),
8926 DAG.getVectorShuffle(VT, DL, SrcVec, SrcVec, {1, 1}),
8927 ISD::CondCode::SETEQ);
8928 }
8929 break;
8930 case MVT::v32i8:
8931 if (Subtarget.hasVLX() && Subtarget.hasVBMI())
8932 Opcode = X86ISD::VPERMV;
8933 else if (Subtarget.hasXOP()) {
8934 SDValue LoSrc = extract128BitVector(SrcVec, 0, DAG, DL);
8935 SDValue HiSrc = extract128BitVector(SrcVec, 16, DAG, DL);
8936 SDValue LoIdx = extract128BitVector(IndicesVec, 0, DAG, DL);
8937 SDValue HiIdx = extract128BitVector(IndicesVec, 16, DAG, DL);
8938 return DAG.getNode(
8939 ISD::CONCAT_VECTORS, DL, VT,
8940 DAG.getNode(X86ISD::VPPERM, DL, MVT::v16i8, LoSrc, HiSrc, LoIdx),
8941 DAG.getNode(X86ISD::VPPERM, DL, MVT::v16i8, LoSrc, HiSrc, HiIdx));
8942 } else if (Subtarget.hasAVX()) {
8943 SDValue Lo = extract128BitVector(SrcVec, 0, DAG, DL);
8944 SDValue Hi = extract128BitVector(SrcVec, 16, DAG, DL);
8945 SDValue LoLo = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Lo);
8946 SDValue HiHi = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Hi, Hi);
8947 auto PSHUFBBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
8948 ArrayRef<SDValue> Ops) {
8949 // Permute Lo and Hi and then select based on index range.
8950 // This works as SHUFB uses bits[3:0] to permute elements and we don't
8951 // care about the bit[7] as its just an index vector.
8952 SDValue Idx = Ops[2];
8953 EVT VT = Idx.getValueType();
8954 return DAG.getSelectCC(DL, Idx, DAG.getConstant(15, DL, VT),
8955 DAG.getNode(X86ISD::PSHUFB, DL, VT, Ops[1], Idx),
8956 DAG.getNode(X86ISD::PSHUFB, DL, VT, Ops[0], Idx),
8957 ISD::CondCode::SETGT);
8958 };
8959 SDValue Ops[] = {LoLo, HiHi, IndicesVec};
8960 return SplitOpsAndApply(DAG, Subtarget, DL, MVT::v32i8, Ops,
8961 PSHUFBBuilder);
8962 }
8963 break;
8964 case MVT::v16i16:
8965 if (Subtarget.hasVLX() && Subtarget.hasBWI())
8966 Opcode = X86ISD::VPERMV;
8967 else if (Subtarget.hasAVX()) {
8968 // Scale to v32i8 and perform as v32i8.
8969 IndicesVec = ScaleIndices(IndicesVec, 2);
8970 return DAG.getBitcast(
8971 VT, createVariablePermute(
8972 MVT::v32i8, DAG.getBitcast(MVT::v32i8, SrcVec),
8973 DAG.getBitcast(MVT::v32i8, IndicesVec), DL, DAG, Subtarget));
8974 }
8975 break;
8976 case MVT::v8f32:
8977 case MVT::v8i32:
8978 if (Subtarget.hasAVX2())
8979 Opcode = X86ISD::VPERMV;
8980 else if (Subtarget.hasAVX()) {
8981 SrcVec = DAG.getBitcast(MVT::v8f32, SrcVec);
8982 SDValue LoLo = DAG.getVectorShuffle(MVT::v8f32, DL, SrcVec, SrcVec,
8983 {0, 1, 2, 3, 0, 1, 2, 3});
8984 SDValue HiHi = DAG.getVectorShuffle(MVT::v8f32, DL, SrcVec, SrcVec,
8985 {4, 5, 6, 7, 4, 5, 6, 7});
8986 if (Subtarget.hasXOP())
8987 return DAG.getBitcast(VT, DAG.getNode(X86ISD::VPERMIL2, DL, MVT::v8f32,
8988 LoLo, HiHi, IndicesVec,
8989 DAG.getConstant(0, DL, MVT::i8)));
8990 // Permute Lo and Hi and then select based on index range.
8991 // This works as VPERMILPS only uses index bits[0:1] to permute elements.
8992 SDValue Res = DAG.getSelectCC(
8993 DL, IndicesVec, DAG.getConstant(3, DL, MVT::v8i32),
8994 DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v8f32, HiHi, IndicesVec),
8995 DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v8f32, LoLo, IndicesVec),
8996 ISD::CondCode::SETGT);
8997 return DAG.getBitcast(VT, Res);
8998 }
8999 break;
9000 case MVT::v4i64:
9001 case MVT::v4f64:
9002 if (Subtarget.hasAVX512()) {
9003 if (!Subtarget.hasVLX()) {
9004 MVT WidenSrcVT = MVT::getVectorVT(VT.getScalarType(), 8);
9005 SrcVec = widenSubVector(WidenSrcVT, SrcVec, false, Subtarget, DAG,
9006 SDLoc(SrcVec));
9007 IndicesVec = widenSubVector(MVT::v8i64, IndicesVec, false, Subtarget,
9008 DAG, SDLoc(IndicesVec));
9009 SDValue Res = createVariablePermute(WidenSrcVT, SrcVec, IndicesVec, DL,
9010 DAG, Subtarget);
9011 return extract256BitVector(Res, 0, DAG, DL);
9012 }
9013 Opcode = X86ISD::VPERMV;
9014 } else if (Subtarget.hasAVX()) {
9015 SrcVec = DAG.getBitcast(MVT::v4f64, SrcVec);
9016 SDValue LoLo =
9017 DAG.getVectorShuffle(MVT::v4f64, DL, SrcVec, SrcVec, {0, 1, 0, 1});
9018 SDValue HiHi =
9019 DAG.getVectorShuffle(MVT::v4f64, DL, SrcVec, SrcVec, {2, 3, 2, 3});
9020 // VPERMIL2PD selects with bit#1 of the index vector, so scale IndicesVec.
9021 IndicesVec = DAG.getNode(ISD::ADD, DL, IndicesVT, IndicesVec, IndicesVec);
9022 if (Subtarget.hasXOP())
9023 return DAG.getBitcast(VT, DAG.getNode(X86ISD::VPERMIL2, DL, MVT::v4f64,
9024 LoLo, HiHi, IndicesVec,
9025 DAG.getConstant(0, DL, MVT::i8)));
9026 // Permute Lo and Hi and then select based on index range.
9027 // This works as VPERMILPD only uses index bit[1] to permute elements.
9028 SDValue Res = DAG.getSelectCC(
9029 DL, IndicesVec, DAG.getConstant(2, DL, MVT::v4i64),
9030 DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v4f64, HiHi, IndicesVec),
9031 DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v4f64, LoLo, IndicesVec),
9032 ISD::CondCode::SETGT);
9033 return DAG.getBitcast(VT, Res);
9034 }
9035 break;
9036 case MVT::v64i8:
9037 if (Subtarget.hasVBMI())
9038 Opcode = X86ISD::VPERMV;
9039 break;
9040 case MVT::v32i16:
9041 if (Subtarget.hasBWI())
9042 Opcode = X86ISD::VPERMV;
9043 break;
9044 case MVT::v16f32:
9045 case MVT::v16i32:
9046 case MVT::v8f64:
9047 case MVT::v8i64:
9048 if (Subtarget.hasAVX512())
9049 Opcode = X86ISD::VPERMV;
9050 break;
9051 }
9052 if (!Opcode)
9053 return SDValue();
9054
9055 assert((VT.getSizeInBits() == ShuffleVT.getSizeInBits()) &&(((VT.getSizeInBits() == ShuffleVT.getSizeInBits()) &&
(VT.getScalarSizeInBits() % ShuffleVT.getScalarSizeInBits())
== 0 && "Illegal variable permute shuffle type") ? static_cast
<void> (0) : __assert_fail ("(VT.getSizeInBits() == ShuffleVT.getSizeInBits()) && (VT.getScalarSizeInBits() % ShuffleVT.getScalarSizeInBits()) == 0 && \"Illegal variable permute shuffle type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 9057, __PRETTY_FUNCTION__))
9056 (VT.getScalarSizeInBits() % ShuffleVT.getScalarSizeInBits()) == 0 &&(((VT.getSizeInBits() == ShuffleVT.getSizeInBits()) &&
(VT.getScalarSizeInBits() % ShuffleVT.getScalarSizeInBits())
== 0 && "Illegal variable permute shuffle type") ? static_cast
<void> (0) : __assert_fail ("(VT.getSizeInBits() == ShuffleVT.getSizeInBits()) && (VT.getScalarSizeInBits() % ShuffleVT.getScalarSizeInBits()) == 0 && \"Illegal variable permute shuffle type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 9057, __PRETTY_FUNCTION__))
9057 "Illegal variable permute shuffle type")(((VT.getSizeInBits() == ShuffleVT.getSizeInBits()) &&
(VT.getScalarSizeInBits() % ShuffleVT.getScalarSizeInBits())
== 0 && "Illegal variable permute shuffle type") ? static_cast
<void> (0) : __assert_fail ("(VT.getSizeInBits() == ShuffleVT.getSizeInBits()) && (VT.getScalarSizeInBits() % ShuffleVT.getScalarSizeInBits()) == 0 && \"Illegal variable permute shuffle type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 9057, __PRETTY_FUNCTION__))
;
9058
9059 uint64_t Scale = VT.getScalarSizeInBits() / ShuffleVT.getScalarSizeInBits();
9060 if (Scale > 1)
9061 IndicesVec = ScaleIndices(IndicesVec, Scale);
9062
9063 EVT ShuffleIdxVT = EVT(ShuffleVT).changeVectorElementTypeToInteger();
9064 IndicesVec = DAG.getBitcast(ShuffleIdxVT, IndicesVec);
9065
9066 SrcVec = DAG.getBitcast(ShuffleVT, SrcVec);
9067 SDValue Res = Opcode == X86ISD::VPERMV
9068 ? DAG.getNode(Opcode, DL, ShuffleVT, IndicesVec, SrcVec)
9069 : DAG.getNode(Opcode, DL, ShuffleVT, SrcVec, IndicesVec);
9070 return DAG.getBitcast(VT, Res);
9071}
9072
9073// Tries to lower a BUILD_VECTOR composed of extract-extract chains that can be
9074// reasoned to be a permutation of a vector by indices in a non-constant vector.
9075// (build_vector (extract_elt V, (extract_elt I, 0)),
9076// (extract_elt V, (extract_elt I, 1)),
9077// ...
9078// ->
9079// (vpermv I, V)
9080//
9081// TODO: Handle undefs
9082// TODO: Utilize pshufb and zero mask blending to support more efficient
9083// construction of vectors with constant-0 elements.
9084static SDValue
9085LowerBUILD_VECTORAsVariablePermute(SDValue V, SelectionDAG &DAG,
9086 const X86Subtarget &Subtarget) {
9087 SDValue SrcVec, IndicesVec;
9088 // Check for a match of the permute source vector and permute index elements.
9089 // This is done by checking that the i-th build_vector operand is of the form:
9090 // (extract_elt SrcVec, (extract_elt IndicesVec, i)).
9091 for (unsigned Idx = 0, E = V.getNumOperands(); Idx != E; ++Idx) {
9092 SDValue Op = V.getOperand(Idx);
9093 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9094 return SDValue();
9095
9096 // If this is the first extract encountered in V, set the source vector,
9097 // otherwise verify the extract is from the previously defined source
9098 // vector.
9099 if (!SrcVec)
9100 SrcVec = Op.getOperand(0);
9101 else if (SrcVec != Op.getOperand(0))
9102 return SDValue();
9103 SDValue ExtractedIndex = Op->getOperand(1);
9104 // Peek through extends.
9105 if (ExtractedIndex.getOpcode() == ISD::ZERO_EXTEND ||
9106 ExtractedIndex.getOpcode() == ISD::SIGN_EXTEND)
9107 ExtractedIndex = ExtractedIndex.getOperand(0);
9108 if (ExtractedIndex.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9109 return SDValue();
9110
9111 // If this is the first extract from the index vector candidate, set the
9112 // indices vector, otherwise verify the extract is from the previously
9113 // defined indices vector.
9114 if (!IndicesVec)
9115 IndicesVec = ExtractedIndex.getOperand(0);
9116 else if (IndicesVec != ExtractedIndex.getOperand(0))
9117 return SDValue();
9118
9119 auto *PermIdx = dyn_cast<ConstantSDNode>(ExtractedIndex.getOperand(1));
9120 if (!PermIdx || PermIdx->getZExtValue() != Idx)
9121 return SDValue();
9122 }
9123
9124 SDLoc DL(V);
9125 MVT VT = V.getSimpleValueType();
9126 return createVariablePermute(VT, SrcVec, IndicesVec, DL, DAG, Subtarget);
9127}
9128
9129SDValue
9130X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
9131 SDLoc dl(Op);
9132
9133 MVT VT = Op.getSimpleValueType();
9134 MVT EltVT = VT.getVectorElementType();
9135 unsigned NumElems = Op.getNumOperands();
9136
9137 // Generate vectors for predicate vectors.
9138 if (VT.getVectorElementType() == MVT::i1 && Subtarget.hasAVX512())
9139 return LowerBUILD_VECTORvXi1(Op, DAG, Subtarget);
9140
9141 if (SDValue VectorConstant = materializeVectorConstant(Op, DAG, Subtarget))
9142 return VectorConstant;
9143
9144 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
9145 if (SDValue AddSub = lowerToAddSubOrFMAddSub(BV, Subtarget, DAG))
9146 return AddSub;
9147 if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
9148 return HorizontalOp;
9149 if (SDValue Broadcast = lowerBuildVectorAsBroadcast(BV, Subtarget, DAG))
9150 return Broadcast;
9151 if (SDValue BitOp = lowerBuildVectorToBitOp(BV, DAG))
9152 return BitOp;
9153
9154 unsigned EVTBits = EltVT.getSizeInBits();
9155
9156 unsigned NumZero = 0;
9157 unsigned NumNonZero = 0;
9158 uint64_t NonZeros = 0;
9159 bool IsAllConstants = true;
9160 SmallSet<SDValue, 8> Values;
9161 unsigned NumConstants = NumElems;
9162 for (unsigned i = 0; i < NumElems; ++i) {
9163 SDValue Elt = Op.getOperand(i);
9164 if (Elt.isUndef())
9165 continue;
9166 Values.insert(Elt);
9167 if (!isa<ConstantSDNode>(Elt) && !isa<ConstantFPSDNode>(Elt)) {
9168 IsAllConstants = false;
9169 NumConstants--;
9170 }
9171 if (X86::isZeroNode(Elt))
9172 NumZero++;
9173 else {
9174 assert(i < sizeof(NonZeros) * 8)((i < sizeof(NonZeros) * 8) ? static_cast<void> (0) :
__assert_fail ("i < sizeof(NonZeros) * 8", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 9174, __PRETTY_FUNCTION__))
; // Make sure the shift is within range.
9175 NonZeros |= ((uint64_t)1 << i);
9176 NumNonZero++;
9177 }
9178 }
9179
9180 // All undef vector. Return an UNDEF. All zero vectors were handled above.
9181 if (NumNonZero == 0)
9182 return DAG.getUNDEF(VT);
9183
9184 // If we are inserting one variable into a vector of non-zero constants, try
9185 // to avoid loading each constant element as a scalar. Load the constants as a
9186 // vector and then insert the variable scalar element. If insertion is not
9187 // supported, fall back to a shuffle to get the scalar blended with the
9188 // constants. Insertion into a zero vector is handled as a special-case
9189 // somewhere below here.
9190 if (NumConstants == NumElems - 1 && NumNonZero != 1 &&
9191 (isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT) ||
9192 isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))) {
9193 // Create an all-constant vector. The variable element in the old
9194 // build vector is replaced by undef in the constant vector. Save the
9195 // variable scalar element and its index for use in the insertelement.
9196 LLVMContext &Context = *DAG.getContext();
9197 Type *EltType = Op.getValueType().getScalarType().getTypeForEVT(Context);
9198 SmallVector<Constant *, 16> ConstVecOps(NumElems, UndefValue::get(EltType));
9199 SDValue VarElt;
9200 SDValue InsIndex;
9201 for (unsigned i = 0; i != NumElems; ++i) {
9202 SDValue Elt = Op.getOperand(i);
9203 if (auto *C = dyn_cast<ConstantSDNode>(Elt))
9204 ConstVecOps[i] = ConstantInt::get(Context, C->getAPIntValue());
9205 else if (auto *C = dyn_cast<ConstantFPSDNode>(Elt))
9206 ConstVecOps[i] = ConstantFP::get(Context, C->getValueAPF());
9207 else if (!Elt.isUndef()) {
9208 assert(!VarElt.getNode() && !InsIndex.getNode() &&((!VarElt.getNode() && !InsIndex.getNode() &&
"Expected one variable element in this vector") ? static_cast
<void> (0) : __assert_fail ("!VarElt.getNode() && !InsIndex.getNode() && \"Expected one variable element in this vector\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 9209, __PRETTY_FUNCTION__))
9209 "Expected one variable element in this vector")((!VarElt.getNode() && !InsIndex.getNode() &&
"Expected one variable element in this vector") ? static_cast
<void> (0) : __assert_fail ("!VarElt.getNode() && !InsIndex.getNode() && \"Expected one variable element in this vector\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 9209, __PRETTY_FUNCTION__))
;
9210 VarElt = Elt;
9211 InsIndex = DAG.getConstant(i, dl, getVectorIdxTy(DAG.getDataLayout()));
9212 }
9213 }
9214 Constant *CV = ConstantVector::get(ConstVecOps);
9215 SDValue DAGConstVec = DAG.getConstantPool(CV, VT);
9216
9217 // The constants we just created may not be legal (eg, floating point). We
9218 // must lower the vector right here because we can not guarantee that we'll
9219 // legalize it before loading it. This is also why we could not just create
9220 // a new build vector here. If the build vector contains illegal constants,
9221 // it could get split back up into a series of insert elements.
9222 // TODO: Improve this by using shorter loads with broadcast/VZEXT_LOAD.
9223 SDValue LegalDAGConstVec = LowerConstantPool(DAGConstVec, DAG);
9224 MachineFunction &MF = DAG.getMachineFunction();
9225 MachinePointerInfo MPI = MachinePointerInfo::getConstantPool(MF);
9226 SDValue Ld = DAG.getLoad(VT, dl, DAG.getEntryNode(), LegalDAGConstVec, MPI);
9227 unsigned InsertC = cast<ConstantSDNode>(InsIndex)->getZExtValue();
9228 unsigned NumEltsInLow128Bits = 128 / VT.getScalarSizeInBits();
9229 if (InsertC < NumEltsInLow128Bits)
9230 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ld, VarElt, InsIndex);
9231
9232 // There's no good way to insert into the high elements of a >128-bit
9233 // vector, so use shuffles to avoid an extract/insert sequence.
9234 assert(VT.getSizeInBits() > 128 && "Invalid insertion index?")((VT.getSizeInBits() > 128 && "Invalid insertion index?"
) ? static_cast<void> (0) : __assert_fail ("VT.getSizeInBits() > 128 && \"Invalid insertion index?\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 9234, __PRETTY_FUNCTION__))
;
9235 assert(Subtarget.hasAVX() && "Must have AVX with >16-byte vector")((Subtarget.hasAVX() && "Must have AVX with >16-byte vector"
) ? static_cast<void> (0) : __assert_fail ("Subtarget.hasAVX() && \"Must have AVX with >16-byte vector\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 9235, __PRETTY_FUNCTION__))
;
9236 SmallVector<int, 8> ShuffleMask;
9237 unsigned NumElts = VT.getVectorNumElements();
9238 for (unsigned i = 0; i != NumElts; ++i)
9239 ShuffleMask.push_back(i == InsertC ? NumElts : i);
9240 SDValue S2V = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, VarElt);
9241 return DAG.getVectorShuffle(VT, dl, Ld, S2V, ShuffleMask);
9242 }
9243
9244 // Special case for single non-zero, non-undef, element.
9245 if (NumNonZero == 1) {
9246 unsigned Idx = countTrailingZeros(NonZeros);
9247 SDValue Item = Op.getOperand(Idx);
9248
9249 // If we have a constant or non-constant insertion into the low element of
9250 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
9251 // the rest of the elements. This will be matched as movd/movq/movss/movsd
9252 // depending on what the source datatype is.
9253 if (Idx == 0) {
9254 if (NumZero == 0)
9255 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
9256
9257 if (EltVT == MVT::i32 || EltVT == MVT::f32 || EltVT == MVT::f64 ||
9258 (EltVT == MVT::i64 && Subtarget.is64Bit())) {
9259 assert((VT.is128BitVector() || VT.is256BitVector() ||(((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector
()) && "Expected an SSE value type!") ? static_cast<
void> (0) : __assert_fail ("(VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) && \"Expected an SSE value type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 9261, __PRETTY_FUNCTION__))
9260 VT.is512BitVector()) &&(((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector
()) && "Expected an SSE value type!") ? static_cast<
void> (0) : __assert_fail ("(VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) && \"Expected an SSE value type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 9261, __PRETTY_FUNCTION__))
9261 "Expected an SSE value type!")(((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector
()) && "Expected an SSE value type!") ? static_cast<
void> (0) : __assert_fail ("(VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) && \"Expected an SSE value type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 9261, __PRETTY_FUNCTION__))
;
9262 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
9263 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
9264 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
9265 }
9266
9267 // We can't directly insert an i8 or i16 into a vector, so zero extend
9268 // it to i32 first.
9269 if (EltVT == MVT::i16 || EltVT == MVT::i8) {
9270 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
9271 if (VT.getSizeInBits() >= 256) {
9272 MVT ShufVT = MVT::getVectorVT(MVT::i32, VT.getSizeInBits()/32);
9273 if (Subtarget.hasAVX()) {
9274 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, ShufVT, Item);
9275 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
9276 } else {
9277 // Without AVX, we need to extend to a 128-bit vector and then
9278 // insert into the 256-bit vector.
9279 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
9280 SDValue ZeroVec = getZeroVector(ShufVT, Subtarget, DAG, dl);
9281 Item = insert128BitVector(ZeroVec, Item, 0, DAG, dl);
9282 }
9283 } else {
9284 assert(VT.is128BitVector() && "Expected an SSE value type!")((VT.is128BitVector() && "Expected an SSE value type!"
) ? static_cast<void> (0) : __assert_fail ("VT.is128BitVector() && \"Expected an SSE value type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 9284, __PRETTY_FUNCTION__))
;
9285 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
9286 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
9287 }
9288 return DAG.getBitcast(VT, Item);
9289 }
9290 }
9291
9292 // Is it a vector logical left shift?
9293 if (NumElems == 2 && Idx == 1 &&
9294 X86::isZeroNode(Op.getOperand(0)) &&
9295 !X86::isZeroNode(Op.getOperand(1))) {
9296 unsigned NumBits = VT.getSizeInBits();
9297 return getVShift(true, VT,
9298 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9299 VT, Op.getOperand(1)),
9300 NumBits/2, DAG, *this, dl);
9301 }
9302
9303 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
9304 return SDValue();
9305
9306 // Otherwise, if this is a vector with i32 or f32 elements, and the element
9307 // is a non-constant being inserted into an element other than the low one,
9308 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
9309 // movd/movss) to move this into the low element, then shuffle it into
9310 // place.
9311 if (EVTBits == 32) {
9312 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
9313 return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
9314 }
9315 }
9316
9317 // Splat is obviously ok. Let legalizer expand it to a shuffle.
9318 if (Values.size() == 1) {
9319 if (EVTBits == 32) {
9320 // Instead of a shuffle like this:
9321 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
9322 // Check if it's possible to issue this instead.
9323 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
9324 unsigned Idx = countTrailingZeros(NonZeros);
9325 SDValue Item = Op.getOperand(Idx);
9326 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
9327 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
9328 }
9329 return SDValue();
9330 }
9331
9332 // A vector full of immediates; various special cases are already
9333 // handled, so this is best done with a single constant-pool load.
9334 if (IsAllConstants)
9335 return SDValue();
9336
9337 if (SDValue V = LowerBUILD_VECTORAsVariablePermute(Op, DAG, Subtarget))
9338 return V;
9339
9340 // See if we can use a vector load to get all of the elements.
9341 {
9342 SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElems);
9343 if (SDValue LD =
9344 EltsFromConsecutiveLoads(VT, Ops, dl, DAG, Subtarget, false))
9345 return LD;
9346 }
9347
9348 // If this is a splat of pairs of 32-bit elements, we can use a narrower
9349 // build_vector and broadcast it.
9350 // TODO: We could probably generalize this more.
9351 if (Subtarget.hasAVX2() && EVTBits == 32 && Values.size() == 2) {
9352 SDValue Ops[4] = { Op.getOperand(0), Op.getOperand(1),
9353 DAG.getUNDEF(EltVT), DAG.getUNDEF(EltVT) };
9354 auto CanSplat = [](SDValue Op, unsigned NumElems, ArrayRef<SDValue> Ops) {
9355 // Make sure all the even/odd operands match.
9356 for (unsigned i = 2; i != NumElems; ++i)
9357 if (Ops[i % 2] != Op.getOperand(i))
9358 return false;
9359 return true;
9360 };
9361 if (CanSplat(Op, NumElems, Ops)) {
9362 MVT WideEltVT = VT.isFloatingPoint() ? MVT::f64 : MVT::i64;
9363 MVT NarrowVT = MVT::getVectorVT(EltVT, 4);
9364 // Create a new build vector and cast to v2i64/v2f64.
9365 SDValue NewBV = DAG.getBitcast(MVT::getVectorVT(WideEltVT, 2),
9366 DAG.getBuildVector(NarrowVT, dl, Ops));
9367 // Broadcast from v2i64/v2f64 and cast to final VT.
9368 MVT BcastVT = MVT::getVectorVT(WideEltVT, NumElems/2);
9369 return DAG.getBitcast(VT, DAG.getNode(X86ISD::VBROADCAST, dl, BcastVT,
9370 NewBV));
9371 }
9372 }
9373
9374 // For AVX-length vectors, build the individual 128-bit pieces and use
9375 // shuffles to put them in place.
9376 if (VT.getSizeInBits() > 128) {
9377 MVT HVT = MVT::getVectorVT(EltVT, NumElems/2);
9378
9379 // Build both the lower and upper subvector.
9380 SDValue Lower =
9381 DAG.getBuildVector(HVT, dl, Op->ops().slice(0, NumElems / 2));
9382 SDValue Upper = DAG.getBuildVector(
9383 HVT, dl, Op->ops().slice(NumElems / 2, NumElems /2));
9384
9385 // Recreate the wider vector with the lower and upper part.
9386 return concatSubVectors(Lower, Upper, VT, NumElems, DAG, dl,
9387 VT.getSizeInBits() / 2);
9388 }
9389
9390 // Let legalizer expand 2-wide build_vectors.
9391 if (EVTBits == 64) {
9392 if (NumNonZero == 1) {
9393 // One half is zero or undef.
9394 unsigned Idx = countTrailingZeros(NonZeros);
9395 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
9396 Op.getOperand(Idx));
9397 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
9398 }
9399 return SDValue();
9400 }
9401
9402 // If element VT is < 32 bits, convert it to inserts into a zero vector.
9403 if (EVTBits == 8 && NumElems == 16)
9404 if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros, NumNonZero, NumZero,
9405 DAG, Subtarget))
9406 return V;
9407
9408 if (EVTBits == 16 && NumElems == 8)
9409 if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros, NumNonZero, NumZero,
9410 DAG, Subtarget))
9411 return V;
9412
9413 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
9414 if (EVTBits == 32 && NumElems == 4)
9415 if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget))
9416 return V;
9417
9418 // If element VT is == 32 bits, turn it into a number of shuffles.
9419 if (NumElems == 4 && NumZero > 0) {
9420 SmallVector<SDValue, 8> Ops(NumElems);
9421 for (unsigned i = 0; i < 4; ++i) {
9422 bool isZero = !(NonZeros & (1ULL << i));
9423 if (isZero)
9424 Ops[i] = getZeroVector(VT, Subtarget, DAG, dl);
9425 else
9426 Ops[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
9427 }
9428
9429 for (unsigned i = 0; i < 2; ++i) {
9430 switch ((NonZeros >> (i*2)) & 0x3) {
9431 default: llvm_unreachable("Unexpected NonZero count")::llvm::llvm_unreachable_internal("Unexpected NonZero count",
"/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 9431)
;
9432 case 0:
9433 Ops[i] = Ops[i*2]; // Must be a zero vector.
9434 break;
9435 case 1:
9436 Ops[i] = getMOVL(DAG, dl, VT, Ops[i*2+1], Ops[i*2]);
9437 break;
9438 case 2:
9439 Ops[i] = getMOVL(DAG, dl, VT, Ops[i*2], Ops[i*2+1]);
9440 break;
9441 case 3:
9442 Ops[i] = getUnpackl(DAG, dl, VT, Ops[i*2], Ops[i*2+1]);
9443 break;
9444 }
9445 }
9446
9447 bool Reverse1 = (NonZeros & 0x3) == 2;
9448 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
9449 int MaskVec[] = {
9450 Reverse1 ? 1 : 0,
9451 Reverse1 ? 0 : 1,
9452 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
9453 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
9454 };
9455 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], MaskVec);
9456 }
9457
9458 assert(Values.size() > 1 && "Expected non-undef and non-splat vector")((Values.size() > 1 && "Expected non-undef and non-splat vector"
) ? static_cast<void> (0) : __assert_fail ("Values.size() > 1 && \"Expected non-undef and non-splat vector\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 9458, __PRETTY_FUNCTION__))
;
9459
9460 // Check for a build vector from mostly shuffle plus few inserting.
9461 if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
9462 return Sh;
9463
9464 // For SSE 4.1, use insertps to put the high elements into the low element.
9465 if (Subtarget.hasSSE41()) {
9466 SDValue Result;
9467 if (!Op.getOperand(0).isUndef())
9468 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
9469 else
9470 Result = DAG.getUNDEF(VT);
9471
9472 for (unsigned i = 1; i < NumElems; ++i) {
9473 if (Op.getOperand(i).isUndef()) continue;
9474 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
9475 Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
9476 }
9477 return Result;
9478 }
9479
9480 // Otherwise, expand into a number of unpckl*, start by extending each of
9481 // our (non-undef) elements to the full vector width with the element in the
9482 // bottom slot of the vector (which generates no code for SSE).
9483 SmallVector<SDValue, 8> Ops(NumElems);
9484 for (unsigned i = 0; i < NumElems; ++i) {
9485 if (!Op.getOperand(i).isUndef())
9486 Ops[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
9487 else
9488 Ops[i] = DAG.getUNDEF(VT);
9489 }
9490
9491 // Next, we iteratively mix elements, e.g. for v4f32:
9492 // Step 1: unpcklps 0, 1 ==> X: <?, ?, 1, 0>
9493 // : unpcklps 2, 3 ==> Y: <?, ?, 3, 2>
9494 // Step 2: unpcklpd X, Y ==> <3, 2, 1, 0>
9495 for (unsigned Scale = 1; Scale < NumElems; Scale *= 2) {
9496 // Generate scaled UNPCKL shuffle mask.
9497 SmallVector<int, 16> Mask;
9498 for(unsigned i = 0; i != Scale; ++i)
9499 Mask.push_back(i);
9500 for (unsigned i = 0; i != Scale; ++i)
9501 Mask.push_back(NumElems+i);
9502 Mask.append(NumElems - Mask.size(), SM_SentinelUndef);
9503
9504 for (unsigned i = 0, e = NumElems / (2 * Scale); i != e; ++i)
9505 Ops[i] = DAG.getVectorShuffle(VT, dl, Ops[2*i], Ops[(2*i)+1], Mask);
9506 }
9507 return Ops[0];
9508}
9509
9510// 256-bit AVX can use the vinsertf128 instruction
9511// to create 256-bit vectors from two other 128-bit ones.
9512// TODO: Detect subvector broadcast here instead of DAG combine?
9513static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG,
9514 const X86Subtarget &Subtarget) {
9515 SDLoc dl(Op);
9516 MVT ResVT = Op.getSimpleValueType();
9517
9518 assert((ResVT.is256BitVector() ||(((ResVT.is256BitVector() || ResVT.is512BitVector()) &&
"Value type must be 256-/512-bit wide") ? static_cast<void
> (0) : __assert_fail ("(ResVT.is256BitVector() || ResVT.is512BitVector()) && \"Value type must be 256-/512-bit wide\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 9519, __PRETTY_FUNCTION__))
9519 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide")(((ResVT.is256BitVector() || ResVT.is512BitVector()) &&
"Value type must be 256-/512-bit wide") ? static_cast<void
> (0) : __assert_fail ("(ResVT.is256BitVector() || ResVT.is512BitVector()) && \"Value type must be 256-/512-bit wide\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 9519, __PRETTY_FUNCTION__))
;
9520
9521 unsigned NumOperands = Op.getNumOperands();
9522 unsigned NumZero = 0;
9523 unsigned NumNonZero = 0;
9524 unsigned NonZeros = 0;
9525 for (unsigned i = 0; i != NumOperands; ++i) {
9526 SDValue SubVec = Op.getOperand(i);
9527 if (SubVec.isUndef())
9528 continue;
9529 if (ISD::isBuildVectorAllZeros(SubVec.getNode()))
9530 ++NumZero;
9531 else {
9532 assert(i < sizeof(NonZeros) * CHAR_BIT)((i < sizeof(NonZeros) * 8) ? static_cast<void> (0) :
__assert_fail ("i < sizeof(NonZeros) * CHAR_BIT", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 9532, __PRETTY_FUNCTION__))
; // Ensure the shift is in range.
9533 NonZeros |= 1 << i;
9534 ++NumNonZero;
9535 }
9536 }
9537
9538 // If we have more than 2 non-zeros, build each half separately.
9539 if (NumNonZero > 2) {
9540 MVT HalfVT = MVT::getVectorVT(ResVT.getVectorElementType(),
9541 ResVT.getVectorNumElements()/2);
9542 ArrayRef<SDUse> Ops = Op->ops();
9543 SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT,
9544 Ops.slice(0, NumOperands/2));
9545 SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT,
9546 Ops.slice(NumOperands/2));
9547 return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
9548 }
9549
9550 // Otherwise, build it up through insert_subvectors.
9551 SDValue Vec = NumZero ? getZeroVector(ResVT, Subtarget, DAG, dl)
9552 : DAG.getUNDEF(ResVT);
9553
9554 MVT SubVT = Op.getOperand(0).getSimpleValueType();
9555 unsigned NumSubElems = SubVT.getVectorNumElements();
9556 for (unsigned i = 0; i != NumOperands; ++i) {
9557 if ((NonZeros & (1 << i)) == 0)
9558 continue;
9559
9560 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Vec,
9561 Op.getOperand(i),
9562 DAG.getIntPtrConstant(i * NumSubElems, dl));
9563 }
9564
9565 return Vec;
9566}
9567
9568// Return true if all the operands of the given CONCAT_VECTORS node are zeros
9569// except for the first one. (CONCAT_VECTORS Op, 0, 0,...,0)
9570static bool isExpandWithZeros(const SDValue &Op) {
9571 assert(Op.getOpcode() == ISD::CONCAT_VECTORS &&((Op.getOpcode() == ISD::CONCAT_VECTORS && "Expand with zeros only possible in CONCAT_VECTORS nodes!"
) ? static_cast<void> (0) : __assert_fail ("Op.getOpcode() == ISD::CONCAT_VECTORS && \"Expand with zeros only possible in CONCAT_VECTORS nodes!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 9572, __PRETTY_FUNCTION__))
9572 "Expand with zeros only possible in CONCAT_VECTORS nodes!")((Op.getOpcode() == ISD::CONCAT_VECTORS && "Expand with zeros only possible in CONCAT_VECTORS nodes!"
) ? static_cast<void> (0) : __assert_fail ("Op.getOpcode() == ISD::CONCAT_VECTORS && \"Expand with zeros only possible in CONCAT_VECTORS nodes!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 9572, __PRETTY_FUNCTION__))
;
9573
9574 for (unsigned i = 1; i < Op.getNumOperands(); i++)
9575 if (!ISD::isBuildVectorAllZeros(Op.getOperand(i).getNode()))
9576 return false;
9577
9578 return true;
9579}
9580
9581// Returns true if the given node is a type promotion (by concatenating i1
9582// zeros) of the result of a node that already zeros all upper bits of
9583// k-register.
9584static SDValue isTypePromotionOfi1ZeroUpBits(SDValue Op) {
9585 unsigned Opc = Op.getOpcode();
9586
9587 assert(Opc == ISD::CONCAT_VECTORS &&((Opc == ISD::CONCAT_VECTORS && Op.getSimpleValueType
().getVectorElementType() == MVT::i1 && "Unexpected node to check for type promotion!"
) ? static_cast<void> (0) : __assert_fail ("Opc == ISD::CONCAT_VECTORS && Op.getSimpleValueType().getVectorElementType() == MVT::i1 && \"Unexpected node to check for type promotion!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 9589, __PRETTY_FUNCTION__))
9588 Op.getSimpleValueType().getVectorElementType() == MVT::i1 &&((Opc == ISD::CONCAT_VECTORS && Op.getSimpleValueType
().getVectorElementType() == MVT::i1 && "Unexpected node to check for type promotion!"
) ? static_cast<void> (0) : __assert_fail ("Opc == ISD::CONCAT_VECTORS && Op.getSimpleValueType().getVectorElementType() == MVT::i1 && \"Unexpected node to check for type promotion!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 9589, __PRETTY_FUNCTION__))
9589 "Unexpected node to check for type promotion!")((Opc == ISD::CONCAT_VECTORS && Op.getSimpleValueType
().getVectorElementType() == MVT::i1 && "Unexpected node to check for type promotion!"
) ? static_cast<void> (0) : __assert_fail ("Opc == ISD::CONCAT_VECTORS && Op.getSimpleValueType().getVectorElementType() == MVT::i1 && \"Unexpected node to check for type promotion!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 9589, __PRETTY_FUNCTION__))
;
9590
9591 // As long as we are concatenating zeros to the upper part of a previous node
9592 // result, climb up the tree until a node with different opcode is
9593 // encountered
9594 while (Opc == ISD::INSERT_SUBVECTOR || Opc == ISD::CONCAT_VECTORS) {
9595 if (Opc == ISD::INSERT_SUBVECTOR) {
9596 if (ISD::isBuildVectorAllZeros(Op.getOperand(0).getNode()) &&
9597 Op.getConstantOperandVal(2) == 0)
9598 Op = Op.getOperand(1);
9599 else
9600 return SDValue();
9601 } else { // Opc == ISD::CONCAT_VECTORS
9602 if (isExpandWithZeros(Op))
9603 Op = Op.getOperand(0);
9604 else
9605 return SDValue();
9606 }
9607 Opc = Op.getOpcode();
9608 }
9609
9610 // Check if the first inserted node zeroes the upper bits, or an 'and' result
9611 // of a node that zeros the upper bits (its masked version).
9612 if (isMaskedZeroUpperBitsvXi1(Op.getOpcode()) ||
9613 (Op.getOpcode() == ISD::AND &&
9614 (isMaskedZeroUpperBitsvXi1(Op.getOperand(0).getOpcode()) ||
9615 isMaskedZeroUpperBitsvXi1(Op.getOperand(1).getOpcode())))) {
9616 return Op;
9617 }
9618
9619 return SDValue();
9620}
9621
9622// TODO: Merge this with LowerAVXCONCAT_VECTORS?
9623static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
9624 const X86Subtarget &Subtarget,
9625 SelectionDAG & DAG) {
9626 SDLoc dl(Op);
9627 MVT ResVT = Op.getSimpleValueType();
9628 unsigned NumOperands = Op.getNumOperands();
9629
9630 assert(NumOperands > 1 && isPowerOf2_32(NumOperands) &&((NumOperands > 1 && isPowerOf2_32(NumOperands) &&
"Unexpected number of operands in CONCAT_VECTORS") ? static_cast
<void> (0) : __assert_fail ("NumOperands > 1 && isPowerOf2_32(NumOperands) && \"Unexpected number of operands in CONCAT_VECTORS\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 9631, __PRETTY_FUNCTION__))
9631 "Unexpected number of operands in CONCAT_VECTORS")((NumOperands > 1 && isPowerOf2_32(NumOperands) &&
"Unexpected number of operands in CONCAT_VECTORS") ? static_cast
<void> (0) : __assert_fail ("NumOperands > 1 && isPowerOf2_32(NumOperands) && \"Unexpected number of operands in CONCAT_VECTORS\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 9631, __PRETTY_FUNCTION__))
;
9632
9633 // If this node promotes - by concatenating zeroes - the type of the result
9634 // of a node with instruction that zeroes all upper (irrelevant) bits of the
9635 // output register, mark it as legal and catch the pattern in instruction
9636 // selection to avoid emitting extra instructions (for zeroing upper bits).
9637 if (SDValue Promoted = isTypePromotionOfi1ZeroUpBits(Op))
9638 return widenSubVector(ResVT, Promoted, true, Subtarget, DAG, dl);
9639
9640 unsigned NumZero = 0;
9641 unsigned NumNonZero = 0;
9642 uint64_t NonZeros = 0;
9643 for (unsigned i = 0; i != NumOperands; ++i) {
9644 SDValue SubVec = Op.getOperand(i);
9645 if (SubVec.isUndef())
9646 continue;
9647 if (ISD::isBuildVectorAllZeros(SubVec.getNode()))
9648 ++NumZero;
9649 else {
9650 assert(i < sizeof(NonZeros) * CHAR_BIT)((i < sizeof(NonZeros) * 8) ? static_cast<void> (0) :
__assert_fail ("i < sizeof(NonZeros) * CHAR_BIT", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 9650, __PRETTY_FUNCTION__))
; // Ensure the shift is in range.
9651 NonZeros |= (uint64_t)1 << i;
9652 ++NumNonZero;
9653 }
9654 }
9655
9656
9657 // If there are zero or one non-zeros we can handle this very simply.
9658 if (NumNonZero <= 1) {
9659 SDValue Vec = NumZero ? getZeroVector(ResVT, Subtarget, DAG, dl)
9660 : DAG.getUNDEF(ResVT);
9661 if (!NumNonZero)
9662 return Vec;
9663 unsigned Idx = countTrailingZeros(NonZeros);
9664 SDValue SubVec = Op.getOperand(Idx);
9665 unsigned SubVecNumElts = SubVec.getSimpleValueType().getVectorNumElements();
9666 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Vec, SubVec,
9667 DAG.getIntPtrConstant(Idx * SubVecNumElts, dl));
9668 }
9669
9670 if (NumOperands > 2) {
9671 MVT HalfVT = MVT::getVectorVT(ResVT.getVectorElementType(),
9672 ResVT.getVectorNumElements()/2);
9673 ArrayRef<SDUse> Ops = Op->ops();
9674 SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT,
9675 Ops.slice(0, NumOperands/2));
9676 SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT,
9677 Ops.slice(NumOperands/2));
9678 return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
9679 }
9680
9681 assert(NumNonZero == 2 && "Simple cases not handled?")((NumNonZero == 2 && "Simple cases not handled?") ? static_cast
<void> (0) : __assert_fail ("NumNonZero == 2 && \"Simple cases not handled?\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 9681, __PRETTY_FUNCTION__))
;
9682
9683 if (ResVT.getVectorNumElements() >= 16)
9684 return Op; // The operation is legal with KUNPCK
9685
9686 SDValue Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT,
9687 DAG.getUNDEF(ResVT), Op.getOperand(0),
9688 DAG.getIntPtrConstant(0, dl));
9689 unsigned NumElems = ResVT.getVectorNumElements();
9690 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Vec, Op.getOperand(1),
9691 DAG.getIntPtrConstant(NumElems/2, dl));
9692}
9693
9694static SDValue LowerCONCAT_VECTORS(SDValue Op,
9695 const X86Subtarget &Subtarget,
9696 SelectionDAG &DAG) {
9697 MVT VT = Op.getSimpleValueType();
9698 if (VT.getVectorElementType() == MVT::i1)
9699 return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
9700
9701 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||(((VT.is256BitVector() && Op.getNumOperands() == 2) ||
(VT.is512BitVector() && (Op.getNumOperands() == 2 ||
Op.getNumOperands() == 4))) ? static_cast<void> (0) : __assert_fail
("(VT.is256BitVector() && Op.getNumOperands() == 2) || (VT.is512BitVector() && (Op.getNumOperands() == 2 || Op.getNumOperands() == 4))"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 9703, __PRETTY_FUNCTION__))
9702 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||(((VT.is256BitVector() && Op.getNumOperands() == 2) ||
(VT.is512BitVector() && (Op.getNumOperands() == 2 ||
Op.getNumOperands() == 4))) ? static_cast<void> (0) : __assert_fail
("(VT.is256BitVector() && Op.getNumOperands() == 2) || (VT.is512BitVector() && (Op.getNumOperands() == 2 || Op.getNumOperands() == 4))"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 9703, __PRETTY_FUNCTION__))
9703 Op.getNumOperands() == 4)))(((VT.is256BitVector() && Op.getNumOperands() == 2) ||
(VT.is512BitVector() && (Op.getNumOperands() == 2 ||
Op.getNumOperands() == 4))) ? static_cast<void> (0) : __assert_fail
("(VT.is256BitVector() && Op.getNumOperands() == 2) || (VT.is512BitVector() && (Op.getNumOperands() == 2 || Op.getNumOperands() == 4))"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 9703, __PRETTY_FUNCTION__))
;
9704
9705 // AVX can use the vinsertf128 instruction to create 256-bit vectors
9706 // from two other 128-bit ones.
9707
9708 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
9709 return LowerAVXCONCAT_VECTORS(Op, DAG, Subtarget);
9710}
9711
9712//===----------------------------------------------------------------------===//
9713// Vector shuffle lowering
9714//
9715// This is an experimental code path for lowering vector shuffles on x86. It is
9716// designed to handle arbitrary vector shuffles and blends, gracefully
9717// degrading performance as necessary. It works hard to recognize idiomatic
9718// shuffles and lower them to optimal instruction patterns without leaving
9719// a framework that allows reasonably efficient handling of all vector shuffle
9720// patterns.
9721//===----------------------------------------------------------------------===//
9722
9723/// Tiny helper function to identify a no-op mask.
9724///
9725/// This is a somewhat boring predicate function. It checks whether the mask
9726/// array input, which is assumed to be a single-input shuffle mask of the kind
9727/// used by the X86 shuffle instructions (not a fully general
9728/// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
9729/// in-place shuffle are 'no-op's.
9730static bool isNoopShuffleMask(ArrayRef<int> Mask) {
9731 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
9732 assert(Mask[i] >= -1 && "Out of bound mask element!")((Mask[i] >= -1 && "Out of bound mask element!") ?
static_cast<void> (0) : __assert_fail ("Mask[i] >= -1 && \"Out of bound mask element!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 9732, __PRETTY_FUNCTION__))
;
9733 if (Mask[i] >= 0 && Mask[i] != i)
9734 return false;
9735 }
9736 return true;
9737}
9738
9739/// Test whether there are elements crossing 128-bit lanes in this
9740/// shuffle mask.
9741///
9742/// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
9743/// and we routinely test for these.
9744static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
9745 int LaneSize = 128 / VT.getScalarSizeInBits();
9746 int Size = Mask.size();
9747 for (int i = 0; i < Size; ++i)
9748 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9749 return true;
9750 return false;
9751}
9752
9753/// Test whether a shuffle mask is equivalent within each sub-lane.
9754///
9755/// This checks a shuffle mask to see if it is performing the same
9756/// lane-relative shuffle in each sub-lane. This trivially implies
9757/// that it is also not lane-crossing. It may however involve a blend from the
9758/// same lane of a second vector.
9759///
9760/// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
9761/// non-trivial to compute in the face of undef lanes. The representation is
9762/// suitable for use with existing 128-bit shuffles as entries from the second
9763/// vector have been remapped to [LaneSize, 2*LaneSize).
9764static bool isRepeatedShuffleMask(unsigned LaneSizeInBits, MVT VT,
9765 ArrayRef<int> Mask,
9766 SmallVectorImpl<int> &RepeatedMask) {
9767 auto LaneSize = LaneSizeInBits / VT.getScalarSizeInBits();
9768 RepeatedMask.assign(LaneSize, -1);
9769 int Size = Mask.size();
9770 for (int i = 0; i < Size; ++i) {
9771 assert(Mask[i] == SM_SentinelUndef || Mask[i] >= 0)((Mask[i] == SM_SentinelUndef || Mask[i] >= 0) ? static_cast
<void> (0) : __assert_fail ("Mask[i] == SM_SentinelUndef || Mask[i] >= 0"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 9771, __PRETTY_FUNCTION__))
;
9772 if (Mask[i] < 0)
9773 continue;
9774 if ((Mask[i] % Size) / LaneSize != i / LaneSize)
9775 // This entry crosses lanes, so there is no way to model this shuffle.
9776 return false;
9777
9778 // Ok, handle the in-lane shuffles by detecting if and when they repeat.
9779 // Adjust second vector indices to start at LaneSize instead of Size.
9780 int LocalM = Mask[i] < Size ? Mask[i] % LaneSize
9781 : Mask[i] % LaneSize + LaneSize;
9782 if (RepeatedMask[i % LaneSize] < 0)
9783 // This is the first non-undef entry in this slot of a 128-bit lane.
9784 RepeatedMask[i % LaneSize] = LocalM;
9785 else if (RepeatedMask[i % LaneSize] != LocalM)
9786 // Found a mismatch with the repeated mask.
9787 return false;
9788 }
9789 return true;
9790}
9791
9792/// Test whether a shuffle mask is equivalent within each 128-bit lane.
9793static bool
9794is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
9795 SmallVectorImpl<int> &RepeatedMask) {
9796 return isRepeatedShuffleMask(128, VT, Mask, RepeatedMask);
9797}
9798
9799static bool
9800is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask) {
9801 SmallVector<int, 32> RepeatedMask;
9802 return isRepeatedShuffleMask(128, VT, Mask, RepeatedMask);
9803}
9804
9805/// Test whether a shuffle mask is equivalent within each 256-bit lane.
9806static bool
9807is256BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
9808 SmallVectorImpl<int> &RepeatedMask) {
9809 return isRepeatedShuffleMask(256, VT, Mask, RepeatedMask);
9810}
9811
9812/// Test whether a target shuffle mask is equivalent within each sub-lane.
9813/// Unlike isRepeatedShuffleMask we must respect SM_SentinelZero.
9814static bool isRepeatedTargetShuffleMask(unsigned LaneSizeInBits, MVT VT,
9815 ArrayRef<int> Mask,
9816 SmallVectorImpl<int> &RepeatedMask) {
9817 int LaneSize = LaneSizeInBits / VT.getScalarSizeInBits();
9818 RepeatedMask.assign(LaneSize, SM_SentinelUndef);
9819 int Size = Mask.size();
9820 for (int i = 0; i < Size; ++i) {
9821 assert(isUndefOrZero(Mask[i]) || (Mask[i] >= 0))((isUndefOrZero(Mask[i]) || (Mask[i] >= 0)) ? static_cast<
void> (0) : __assert_fail ("isUndefOrZero(Mask[i]) || (Mask[i] >= 0)"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 9821, __PRETTY_FUNCTION__))
;
9822 if (Mask[i] == SM_SentinelUndef)
9823 continue;
9824 if (Mask[i] == SM_SentinelZero) {
9825 if (!isUndefOrZero(RepeatedMask[i % LaneSize]))
9826 return false;
9827 RepeatedMask[i % LaneSize] = SM_SentinelZero;
9828 continue;
9829 }
9830 if ((Mask[i] % Size) / LaneSize != i / LaneSize)
9831 // This entry crosses lanes, so there is no way to model this shuffle.
9832 return false;
9833
9834 // Ok, handle the in-lane shuffles by detecting if and when they repeat.
9835 // Adjust second vector indices to start at LaneSize instead of Size.
9836 int LocalM =
9837 Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + LaneSize;
9838 if (RepeatedMask[i % LaneSize] == SM_SentinelUndef)
9839 // This is the first non-undef entry in this slot of a 128-bit lane.
9840 RepeatedMask[i % LaneSize] = LocalM;
9841 else if (RepeatedMask[i % LaneSize] != LocalM)
9842 // Found a mismatch with the repeated mask.
9843 return false;
9844 }
9845 return true;
9846}
9847
9848/// Checks whether a shuffle mask is equivalent to an explicit list of
9849/// arguments.
9850///
9851/// This is a fast way to test a shuffle mask against a fixed pattern:
9852///
9853/// if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
9854///
9855/// It returns true if the mask is exactly as wide as the argument list, and
9856/// each element of the mask is either -1 (signifying undef) or the value given
9857/// in the argument.
9858static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
9859 ArrayRef<int> ExpectedMask) {
9860 if (Mask.size() != ExpectedMask.size())
9861 return false;
9862
9863 int Size = Mask.size();
9864
9865 // If the values are build vectors, we can look through them to find
9866 // equivalent inputs that make the shuffles equivalent.
9867 auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
9868 auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
9869
9870 for (int i = 0; i < Size; ++i) {
9871 assert(Mask[i] >= -1 && "Out of bound mask element!")((Mask[i] >= -1 && "Out of bound mask element!") ?
static_cast<void> (0) : __assert_fail ("Mask[i] >= -1 && \"Out of bound mask element!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 9871, __PRETTY_FUNCTION__))
;
9872 if (Mask[i] >= 0 && Mask[i] != ExpectedMask[i]) {
9873 auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
9874 auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
9875 if (!MaskBV || !ExpectedBV ||
9876 MaskBV->getOperand(Mask[i] % Size) !=
9877 ExpectedBV->getOperand(ExpectedMask[i] % Size))
9878 return false;
9879 }
9880 }
9881
9882 return true;
9883}
9884
9885/// Checks whether a target shuffle mask is equivalent to an explicit pattern.
9886///
9887/// The masks must be exactly the same width.
9888///
9889/// If an element in Mask matches SM_SentinelUndef (-1) then the corresponding
9890/// value in ExpectedMask is always accepted. Otherwise the indices must match.
9891///
9892/// SM_SentinelZero is accepted as a valid negative index but must match in both.
9893static bool isTargetShuffleEquivalent(ArrayRef<int> Mask,
9894 ArrayRef<int> ExpectedMask) {
9895 int Size = Mask.size();
9896 if (Size != (int)ExpectedMask.size())
9897 return false;
9898
9899 for (int i = 0; i < Size; ++i)
9900 if (Mask[i] == SM_SentinelUndef)
9901 continue;
9902 else if (Mask[i] < 0 && Mask[i] != SM_SentinelZero)
9903 return false;
9904 else if (Mask[i] != ExpectedMask[i])
9905 return false;
9906
9907 return true;
9908}
9909
9910// Merges a general DAG shuffle mask and zeroable bit mask into a target shuffle
9911// mask.
9912static SmallVector<int, 64> createTargetShuffleMask(ArrayRef<int> Mask,
9913 const APInt &Zeroable) {
9914 int NumElts = Mask.size();
9915 assert(NumElts == (int)Zeroable.getBitWidth() && "Mismatch mask sizes")((NumElts == (int)Zeroable.getBitWidth() && "Mismatch mask sizes"
) ? static_cast<void> (0) : __assert_fail ("NumElts == (int)Zeroable.getBitWidth() && \"Mismatch mask sizes\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 9915, __PRETTY_FUNCTION__))
;
9916
9917 SmallVector<int, 64> TargetMask(NumElts, SM_SentinelUndef);
9918 for (int i = 0; i != NumElts; ++i) {
9919 int M = Mask[i];
9920 if (M == SM_SentinelUndef)
9921 continue;
9922 assert(0 <= M && M < (2 * NumElts) && "Out of range shuffle index")((0 <= M && M < (2 * NumElts) && "Out of range shuffle index"
) ? static_cast<void> (0) : __assert_fail ("0 <= M && M < (2 * NumElts) && \"Out of range shuffle index\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 9922, __PRETTY_FUNCTION__))
;
9923 TargetMask[i] = (Zeroable[i] ? SM_SentinelZero : M);
9924 }
9925 return TargetMask;
9926}
9927
9928// Attempt to create a shuffle mask from a VSELECT condition mask.
9929static bool createShuffleMaskFromVSELECT(SmallVectorImpl<int> &Mask,
9930 SDValue Cond) {
9931 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
9932 return false;
9933
9934 unsigned Size = Cond.getValueType().getVectorNumElements();
9935 Mask.resize(Size, SM_SentinelUndef);
9936
9937 for (int i = 0; i != (int)Size; ++i) {
9938 SDValue CondElt = Cond.getOperand(i);
9939 Mask[i] = i;
9940 // Arbitrarily choose from the 2nd operand if the select condition element
9941 // is undef.
9942 // TODO: Can we do better by matching patterns such as even/odd?
9943 if (CondElt.isUndef() || isNullConstant(CondElt))
9944 Mask[i] += Size;
9945 }
9946
9947 return true;
9948}
9949
9950// Check if the shuffle mask is suitable for the AVX vpunpcklwd or vpunpckhwd
9951// instructions.
9952static bool isUnpackWdShuffleMask(ArrayRef<int> Mask, MVT VT) {
9953 if (VT != MVT::v8i32 && VT != MVT::v8f32)
9954 return false;
9955
9956 SmallVector<int, 8> Unpcklwd;
9957 createUnpackShuffleMask(MVT::v8i16, Unpcklwd, /* Lo = */ true,
9958 /* Unary = */ false);
9959 SmallVector<int, 8> Unpckhwd;
9960 createUnpackShuffleMask(MVT::v8i16, Unpckhwd, /* Lo = */ false,
9961 /* Unary = */ false);
9962 bool IsUnpackwdMask = (isTargetShuffleEquivalent(Mask, Unpcklwd) ||
9963 isTargetShuffleEquivalent(Mask, Unpckhwd));
9964 return IsUnpackwdMask;
9965}
9966
9967static bool is128BitUnpackShuffleMask(ArrayRef<int> Mask) {
9968 // Create 128-bit vector type based on mask size.
9969 MVT EltVT = MVT::getIntegerVT(128 / Mask.size());
9970 MVT VT = MVT::getVectorVT(EltVT, Mask.size());
9971
9972 // We can't assume a canonical shuffle mask, so try the commuted version too.
9973 SmallVector<int, 4> CommutedMask(Mask.begin(), Mask.end());
9974 ShuffleVectorSDNode::commuteMask(CommutedMask);
9975
9976 // Match any of unary/binary or low/high.
9977 for (unsigned i = 0; i != 4; ++i) {
9978 SmallVector<int, 16> UnpackMask;
9979 createUnpackShuffleMask(VT, UnpackMask, (i >> 1) % 2, i % 2);
9980 if (isTargetShuffleEquivalent(Mask, UnpackMask) ||
9981 isTargetShuffleEquivalent(CommutedMask, UnpackMask))
9982 return true;
9983 }
9984 return false;
9985}
9986
9987/// Return true if a shuffle mask chooses elements identically in its top and
9988/// bottom halves. For example, any splat mask has the same top and bottom
9989/// halves. If an element is undefined in only one half of the mask, the halves
9990/// are not considered identical.
9991static bool hasIdenticalHalvesShuffleMask(ArrayRef<int> Mask) {
9992 assert(Mask.size() % 2 == 0 && "Expecting even number of elements in mask")((Mask.size() % 2 == 0 && "Expecting even number of elements in mask"
) ? static_cast<void> (0) : __assert_fail ("Mask.size() % 2 == 0 && \"Expecting even number of elements in mask\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 9992, __PRETTY_FUNCTION__))
;
9993 unsigned HalfSize = Mask.size() / 2;
9994 for (unsigned i = 0; i != HalfSize; ++i) {
9995 if (Mask[i] != Mask[i + HalfSize])
9996 return false;
9997 }
9998 return true;
9999}
10000
10001/// Get a 4-lane 8-bit shuffle immediate for a mask.
10002///
10003/// This helper function produces an 8-bit shuffle immediate corresponding to
10004/// the ubiquitous shuffle encoding scheme used in x86 instructions for
10005/// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
10006/// example.
10007///
10008/// NB: We rely heavily on "undef" masks preserving the input lane.
10009static unsigned getV4X86ShuffleImm(ArrayRef<int> Mask) {
10010 assert(Mask.size() == 4 && "Only 4-lane shuffle masks")((Mask.size() == 4 && "Only 4-lane shuffle masks") ? static_cast
<void> (0) : __assert_fail ("Mask.size() == 4 && \"Only 4-lane shuffle masks\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 10010, __PRETTY_FUNCTION__))
;
10011 assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!")((Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!"
) ? static_cast<void> (0) : __assert_fail ("Mask[0] >= -1 && Mask[0] < 4 && \"Out of bound mask element!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 10011, __PRETTY_FUNCTION__))
;
10012 assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!")((Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!"
) ? static_cast<void> (0) : __assert_fail ("Mask[1] >= -1 && Mask[1] < 4 && \"Out of bound mask element!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 10012, __PRETTY_FUNCTION__))
;
10013 assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!")((Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!"
) ? static_cast<void> (0) : __assert_fail ("Mask[2] >= -1 && Mask[2] < 4 && \"Out of bound mask element!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 10013, __PRETTY_FUNCTION__))
;
10014 assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!")((Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!"
) ? static_cast<void> (0) : __assert_fail ("Mask[3] >= -1 && Mask[3] < 4 && \"Out of bound mask element!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 10014, __PRETTY_FUNCTION__))
;
10015
10016 unsigned Imm = 0;
10017 Imm |= (Mask[0] < 0 ? 0 : Mask[0]) << 0;
10018 Imm |= (Mask[1] < 0 ? 1 : Mask[1]) << 2;
10019 Imm |= (Mask[2] < 0 ? 2 : Mask[2]) << 4;
10020 Imm |= (Mask[3] < 0 ? 3 : Mask[3]) << 6;
10021 return Imm;
10022}
10023
10024static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, const SDLoc &DL,
10025 SelectionDAG &DAG) {
10026 return DAG.getConstant(getV4X86ShuffleImm(Mask), DL, MVT::i8);
10027}
10028
10029/// Compute whether each element of a shuffle is zeroable.
10030///
10031/// A "zeroable" vector shuffle element is one which can be lowered to zero.
10032/// Either it is an undef element in the shuffle mask, the element of the input
10033/// referenced is undef, or the element of the input referenced is known to be
10034/// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
10035/// as many lanes with this technique as possible to simplify the remaining
10036/// shuffle.
10037static APInt computeZeroableShuffleElements(ArrayRef<int> Mask,
10038 SDValue V1, SDValue V2) {
10039 APInt Zeroable(Mask.size(), 0);
10040 V1 = peekThroughBitcasts(V1);
10041 V2 = peekThroughBitcasts(V2);
10042
10043 bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
10044 bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
10045
10046 int VectorSizeInBits = V1.getValueSizeInBits();
10047 int ScalarSizeInBits = VectorSizeInBits / Mask.size();
10048 assert(!(VectorSizeInBits % ScalarSizeInBits) && "Illegal shuffle mask size")((!(VectorSizeInBits % ScalarSizeInBits) && "Illegal shuffle mask size"
) ? static_cast<void> (0) : __assert_fail ("!(VectorSizeInBits % ScalarSizeInBits) && \"Illegal shuffle mask size\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 10048, __PRETTY_FUNCTION__))
;
10049
10050 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
10051 int M = Mask[i];
10052 // Handle the easy cases.
10053 if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
10054 Zeroable.setBit(i);
10055 continue;
10056 }
10057
10058 // Determine shuffle input and normalize the mask.
10059 SDValue V = M < Size ? V1 : V2;
10060 M %= Size;
10061
10062 // Currently we can only search BUILD_VECTOR for UNDEF/ZERO elements.
10063 if (V.getOpcode() != ISD::BUILD_VECTOR)
10064 continue;
10065
10066 // If the BUILD_VECTOR has fewer elements then the bitcasted portion of
10067 // the (larger) source element must be UNDEF/ZERO.
10068 if ((Size % V.getNumOperands()) == 0) {
10069 int Scale = Size / V->getNumOperands();
10070 SDValue Op = V.getOperand(M / Scale);
10071 if (Op.isUndef() || X86::isZeroNode(Op))
10072 Zeroable.setBit(i);
10073 else if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op)) {
10074 APInt Val = Cst->getAPIntValue();
10075 Val.lshrInPlace((M % Scale) * ScalarSizeInBits);
10076 Val = Val.getLoBits(ScalarSizeInBits);
10077 if (Val == 0)
10078 Zeroable.setBit(i);
10079 } else if (ConstantFPSDNode *Cst = dyn_cast<ConstantFPSDNode>(Op)) {
10080 APInt Val = Cst->getValueAPF().bitcastToAPInt();
10081 Val.lshrInPlace((M % Scale) * ScalarSizeInBits);
10082 Val = Val.getLoBits(ScalarSizeInBits);
10083 if (Val == 0)
10084 Zeroable.setBit(i);
10085 }
10086 continue;
10087 }
10088
10089 // If the BUILD_VECTOR has more elements then all the (smaller) source
10090 // elements must be UNDEF or ZERO.
10091 if ((V.getNumOperands() % Size) == 0) {
10092 int Scale = V->getNumOperands() / Size;
10093 bool AllZeroable = true;
10094 for (int j = 0; j < Scale; ++j) {
10095 SDValue Op = V.getOperand((M * Scale) + j);
10096 AllZeroable &= (Op.isUndef() || X86::isZeroNode(Op));
10097 }
10098 if (AllZeroable)
10099 Zeroable.setBit(i);
10100 continue;
10101 }
10102 }
10103
10104 return Zeroable;
10105}
10106
10107// The Shuffle result is as follow:
10108// 0*a[0]0*a[1]...0*a[n] , n >=0 where a[] elements in a ascending order.
10109// Each Zeroable's element correspond to a particular Mask's element.
10110// As described in computeZeroableShuffleElements function.
10111//
10112// The function looks for a sub-mask that the nonzero elements are in
10113// increasing order. If such sub-mask exist. The function returns true.
10114static bool isNonZeroElementsInOrder(const APInt &Zeroable,
10115 ArrayRef<int> Mask, const EVT &VectorType,
10116 bool &IsZeroSideLeft) {
10117 int NextElement = -1;
10118 // Check if the Mask's nonzero elements are in increasing order.
10119 for (int i = 0, e = Mask.size(); i < e; i++) {
10120 // Checks if the mask's zeros elements are built from only zeros.
10121 assert(Mask[i] >= -1 && "Out of bound mask element!")((Mask[i] >= -1 && "Out of bound mask element!") ?
static_cast<void> (0) : __assert_fail ("Mask[i] >= -1 && \"Out of bound mask element!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 10121, __PRETTY_FUNCTION__))
;
10122 if (Mask[i] < 0)
10123 return false;
10124 if (Zeroable[i])
10125 continue;
10126 // Find the lowest non zero element
10127 if (NextElement < 0) {
10128 NextElement = Mask[i] != 0 ? VectorType.getVectorNumElements() : 0;
10129 IsZeroSideLeft = NextElement != 0;
10130 }
10131 // Exit if the mask's non zero elements are not in increasing order.
10132 if (NextElement != Mask[i])
10133 return false;
10134 NextElement++;
10135 }
10136 return true;
10137}
10138
10139/// Try to lower a shuffle with a single PSHUFB of V1 or V2.
10140static SDValue lowerShuffleWithPSHUFB(const SDLoc &DL, MVT VT,
10141 ArrayRef<int> Mask, SDValue V1,
10142 SDValue V2, const APInt &Zeroable,
10143 const X86Subtarget &Subtarget,
10144 SelectionDAG &DAG) {
10145 int Size = Mask.size();
10146 int LaneSize = 128 / VT.getScalarSizeInBits();
10147 const int NumBytes = VT.getSizeInBits() / 8;
10148 const int NumEltBytes = VT.getScalarSizeInBits() / 8;
10149
10150 assert((Subtarget.hasSSSE3() && VT.is128BitVector()) ||(((Subtarget.hasSSSE3() && VT.is128BitVector()) || (Subtarget
.hasAVX2() && VT.is256BitVector()) || (Subtarget.hasBWI
() && VT.is512BitVector())) ? static_cast<void>
(0) : __assert_fail ("(Subtarget.hasSSSE3() && VT.is128BitVector()) || (Subtarget.hasAVX2() && VT.is256BitVector()) || (Subtarget.hasBWI() && VT.is512BitVector())"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 10152, __PRETTY_FUNCTION__))
10151 (Subtarget.hasAVX2() && VT.is256BitVector()) ||(((Subtarget.hasSSSE3() && VT.is128BitVector()) || (Subtarget
.hasAVX2() && VT.is256BitVector()) || (Subtarget.hasBWI
() && VT.is512BitVector())) ? static_cast<void>
(0) : __assert_fail ("(Subtarget.hasSSSE3() && VT.is128BitVector()) || (Subtarget.hasAVX2() && VT.is256BitVector()) || (Subtarget.hasBWI() && VT.is512BitVector())"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 10152, __PRETTY_FUNCTION__))
10152 (Subtarget.hasBWI() && VT.is512BitVector()))(((Subtarget.hasSSSE3() && VT.is128BitVector()) || (Subtarget
.hasAVX2() && VT.is256BitVector()) || (Subtarget.hasBWI
() && VT.is512BitVector())) ? static_cast<void>
(0) : __assert_fail ("(Subtarget.hasSSSE3() && VT.is128BitVector()) || (Subtarget.hasAVX2() && VT.is256BitVector()) || (Subtarget.hasBWI() && VT.is512BitVector())"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 10152, __PRETTY_FUNCTION__))
;
10153
10154 SmallVector<SDValue, 64> PSHUFBMask(NumBytes);
10155 // Sign bit set in i8 mask means zero element.
10156 SDValue ZeroMask = DAG.getConstant(0x80, DL, MVT::i8);
10157
10158 SDValue V;
10159 for (int i = 0; i < NumBytes; ++i) {
10160 int M = Mask[i / NumEltBytes];
10161 if (M < 0) {
10162 PSHUFBMask[i] = DAG.getUNDEF(MVT::i8);
10163 continue;
10164 }
10165 if (Zeroable[i / NumEltBytes]) {
10166 PSHUFBMask[i] = ZeroMask;
10167 continue;
10168 }
10169
10170 // We can only use a single input of V1 or V2.
10171 SDValue SrcV = (M >= Size ? V2 : V1);
10172 if (V && V != SrcV)
10173 return SDValue();
10174 V = SrcV;
10175 M %= Size;
10176
10177 // PSHUFB can't cross lanes, ensure this doesn't happen.
10178 if ((M / LaneSize) != ((i / NumEltBytes) / LaneSize))
10179 return SDValue();
10180
10181 M = M % LaneSize;
10182 M = M * NumEltBytes + (i % NumEltBytes);
10183 PSHUFBMask[i] = DAG.getConstant(M, DL, MVT::i8);
10184 }
10185 assert(V && "Failed to find a source input")((V && "Failed to find a source input") ? static_cast
<void> (0) : __assert_fail ("V && \"Failed to find a source input\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 10185, __PRETTY_FUNCTION__))
;
10186
10187 MVT I8VT = MVT::getVectorVT(MVT::i8, NumBytes);
10188 return DAG.getBitcast(
10189 VT, DAG.getNode(X86ISD::PSHUFB, DL, I8VT, DAG.getBitcast(I8VT, V),
10190 DAG.getBuildVector(I8VT, DL, PSHUFBMask)));
10191}
10192
10193static SDValue getMaskNode(SDValue Mask, MVT MaskVT,
10194 const X86Subtarget &Subtarget, SelectionDAG &DAG,
10195 const SDLoc &dl);
10196
10197// X86 has dedicated shuffle that can be lowered to VEXPAND
10198static SDValue lowerShuffleToEXPAND(const SDLoc &DL, MVT VT,
10199 const APInt &Zeroable,
10200 ArrayRef<int> Mask, SDValue &V1,
10201 SDValue &V2, SelectionDAG &DAG,
10202 const X86Subtarget &Subtarget) {
10203 bool IsLeftZeroSide = true;
10204 if (!isNonZeroElementsInOrder(Zeroable, Mask, V1.getValueType(),
10205 IsLeftZeroSide))
10206 return SDValue();
10207 unsigned VEXPANDMask = (~Zeroable).getZExtValue();
10208 MVT IntegerType =
10209 MVT::getIntegerVT(std::max((int)VT.getVectorNumElements(), 8));
10210 SDValue MaskNode = DAG.getConstant(VEXPANDMask, DL, IntegerType);
10211 unsigned NumElts = VT.getVectorNumElements();
10212 assert((NumElts == 4 || NumElts == 8 || NumElts == 16) &&(((NumElts == 4 || NumElts == 8 || NumElts == 16) && "Unexpected number of vector elements"
) ? static_cast<void> (0) : __assert_fail ("(NumElts == 4 || NumElts == 8 || NumElts == 16) && \"Unexpected number of vector elements\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 10213, __PRETTY_FUNCTION__))
10213 "Unexpected number of vector elements")(((NumElts == 4 || NumElts == 8 || NumElts == 16) && "Unexpected number of vector elements"
) ? static_cast<void> (0) : __assert_fail ("(NumElts == 4 || NumElts == 8 || NumElts == 16) && \"Unexpected number of vector elements\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 10213, __PRETTY_FUNCTION__))
;
10214 SDValue VMask = getMaskNode(MaskNode, MVT::getVectorVT(MVT::i1, NumElts),
10215 Subtarget, DAG, DL);
10216 SDValue ZeroVector = getZeroVector(VT, Subtarget, DAG, DL);
10217 SDValue ExpandedVector = IsLeftZeroSide ? V2 : V1;
10218 return DAG.getNode(X86ISD::EXPAND, DL, VT, ExpandedVector, ZeroVector, VMask);
10219}
10220
10221static bool matchVectorShuffleWithUNPCK(MVT VT, SDValue &V1, SDValue &V2,
10222 unsigned &UnpackOpcode, bool IsUnary,
10223 ArrayRef<int> TargetMask,
10224 const SDLoc &DL, SelectionDAG &DAG,
10225 const X86Subtarget &Subtarget) {
10226 int NumElts = VT.getVectorNumElements();
10227
10228 bool Undef1 = true, Undef2 = true, Zero1 = true, Zero2 = true;
10229 for (int i = 0; i != NumElts; i += 2) {
10230 int M1 = TargetMask[i + 0];
10231 int M2 = TargetMask[i + 1];
10232 Undef1 &= (SM_SentinelUndef == M1);
10233 Undef2 &= (SM_SentinelUndef == M2);
10234 Zero1 &= isUndefOrZero(M1);
10235 Zero2 &= isUndefOrZero(M2);
10236 }
10237 assert(!((Undef1 || Zero1) && (Undef2 || Zero2)) &&((!((Undef1 || Zero1) && (Undef2 || Zero2)) &&
"Zeroable shuffle detected") ? static_cast<void> (0) :
__assert_fail ("!((Undef1 || Zero1) && (Undef2 || Zero2)) && \"Zeroable shuffle detected\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 10238, __PRETTY_FUNCTION__))
10238 "Zeroable shuffle detected")((!((Undef1 || Zero1) && (Undef2 || Zero2)) &&
"Zeroable shuffle detected") ? static_cast<void> (0) :
__assert_fail ("!((Undef1 || Zero1) && (Undef2 || Zero2)) && \"Zeroable shuffle detected\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 10238, __PRETTY_FUNCTION__))
;
10239
10240 // Attempt to match the target mask against the unpack lo/hi mask patterns.
10241 SmallVector<int, 64> Unpckl, Unpckh;
10242 createUnpackShuffleMask(VT, Unpckl, /* Lo = */ true, IsUnary);
10243 if (isTargetShuffleEquivalent(TargetMask, Unpckl)) {
10244 UnpackOpcode = X86ISD::UNPCKL;
10245 V2 = (Undef2 ? DAG.getUNDEF(VT) : (IsUnary ? V1 : V2));
10246 V1 = (Undef1 ? DAG.getUNDEF(VT) : V1);
10247 return true;
10248 }
10249
10250 createUnpackShuffleMask(VT, Unpckh, /* Lo = */ false, IsUnary);
10251 if (isTargetShuffleEquivalent(TargetMask, Unpckh)) {
10252 UnpackOpcode = X86ISD::UNPCKH;
10253 V2 = (Undef2 ? DAG.getUNDEF(VT) : (IsUnary ? V1 : V2));
10254 V1 = (Undef1 ? DAG.getUNDEF(VT) : V1);
10255 return true;
10256 }
10257
10258 // If an unary shuffle, attempt to match as an unpack lo/hi with zero.
10259 if (IsUnary && (Zero1 || Zero2)) {
10260 // Don't bother if we can blend instead.
10261 if ((Subtarget.hasSSE41() || VT == MVT::v2i64 || VT == MVT::v2f64) &&
10262 isSequentialOrUndefOrZeroInRange(TargetMask, 0, NumElts, 0))
10263 return false;
10264
10265 bool MatchLo = true, MatchHi = true;
10266 for (int i = 0; (i != NumElts) && (MatchLo || MatchHi); ++i) {
10267 int M = TargetMask[i];
10268
10269 // Ignore if the input is known to be zero or the index is undef.
10270 if ((((i & 1) == 0) && Zero1) || (((i & 1) == 1) && Zero2) ||
10271 (M == SM_SentinelUndef))
10272 continue;
10273
10274 MatchLo &= (M == Unpckl[i]);
10275 MatchHi &= (M == Unpckh[i]);
10276 }
10277
10278 if (MatchLo || MatchHi) {
10279 UnpackOpcode = MatchLo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
10280 V2 = Zero2 ? getZeroVector(VT, Subtarget, DAG, DL) : V1;
10281 V1 = Zero1 ? getZeroVector(VT, Subtarget, DAG, DL) : V1;
10282 return true;
10283 }
10284 }
10285
10286 // If a binary shuffle, commute and try again.
10287 if (!IsUnary) {
10288 ShuffleVectorSDNode::commuteMask(Unpckl);
10289 if (isTargetShuffleEquivalent(TargetMask, Unpckl)) {
10290 UnpackOpcode = X86ISD::UNPCKL;
10291 std::swap(V1, V2);
10292 return true;
10293 }
10294
10295 ShuffleVectorSDNode::commuteMask(Unpckh);
10296 if (isTargetShuffleEquivalent(TargetMask, Unpckh)) {
10297 UnpackOpcode = X86ISD::UNPCKH;
10298 std::swap(V1, V2);
10299 return true;
10300 }
10301 }
10302
10303 return false;
10304}
10305
10306// X86 has dedicated unpack instructions that can handle specific blend
10307// operations: UNPCKH and UNPCKL.
10308static SDValue lowerShuffleWithUNPCK(const SDLoc &DL, MVT VT,
10309 ArrayRef<int> Mask, SDValue V1, SDValue V2,
10310 SelectionDAG &DAG) {
10311 SmallVector<int, 8> Unpckl;
10312 createUnpackShuffleMask(VT, Unpckl, /* Lo = */ true, /* Unary = */ false);
10313 if (isShuffleEquivalent(V1, V2, Mask, Unpckl))
10314 return DAG.getNode(X86ISD::UNPCKL, DL, VT, V1, V2);
10315
10316 SmallVector<int, 8> Unpckh;
10317 createUnpackShuffleMask(VT, Unpckh, /* Lo = */ false, /* Unary = */ false);
10318 if (isShuffleEquivalent(V1, V2, Mask, Unpckh))
10319 return DAG.getNode(X86ISD::UNPCKH, DL, VT, V1, V2);
10320
10321 // Commute and try again.
10322 ShuffleVectorSDNode::commuteMask(Unpckl);
10323 if (isShuffleEquivalent(V1, V2, Mask, Unpckl))
10324 return DAG.getNode(X86ISD::UNPCKL, DL, VT, V2, V1);
10325
10326 ShuffleVectorSDNode::commuteMask(Unpckh);
10327 if (isShuffleEquivalent(V1, V2, Mask, Unpckh))
10328 return DAG.getNode(X86ISD::UNPCKH, DL, VT, V2, V1);
10329
10330 return SDValue();
10331}
10332
10333static bool matchVectorShuffleAsVPMOV(ArrayRef<int> Mask, bool SwappedOps,
10334 int Delta) {
10335 int Size = (int)Mask.size();
10336 int Split = Size / Delta;
10337 int TruncatedVectorStart = SwappedOps ? Size : 0;
10338
10339 // Match for mask starting with e.g.: <8, 10, 12, 14,... or <0, 2, 4, 6,...
10340 if (!isSequentialOrUndefInRange(Mask, 0, Split, TruncatedVectorStart, Delta))
10341 return false;
10342
10343 // The rest of the mask should not refer to the truncated vector's elements.
10344 if (isAnyInRange(Mask.slice(Split, Size - Split), TruncatedVectorStart,
10345 TruncatedVectorStart + Size))
10346 return false;
10347
10348 return true;
10349}
10350
10351// Try to lower trunc+vector_shuffle to a vpmovdb or a vpmovdw instruction.
10352//
10353// An example is the following:
10354//
10355// t0: ch = EntryToken
10356// t2: v4i64,ch = CopyFromReg t0, Register:v4i64 %0
10357// t25: v4i32 = truncate t2
10358// t41: v8i16 = bitcast t25
10359// t21: v8i16 = BUILD_VECTOR undef:i16, undef:i16, undef:i16, undef:i16,
10360// Constant:i16<0>, Constant:i16<0>, Constant:i16<0>, Constant:i16<0>
10361// t51: v8i16 = vector_shuffle<0,2,4,6,12,13,14,15> t41, t21
10362// t18: v2i64 = bitcast t51
10363//
10364// Without avx512vl, this is lowered to:
10365//
10366// vpmovqd %zmm0, %ymm0
10367// vpshufb {{.*#+}} xmm0 =
10368// xmm0[0,1,4,5,8,9,12,13],zero,zero,zero,zero,zero,zero,zero,zero
10369//
10370// But when avx512vl is available, one can just use a single vpmovdw
10371// instruction.
10372static SDValue lowerShuffleWithVPMOV(const SDLoc &DL, ArrayRef<int> Mask,
10373 MVT VT, SDValue V1, SDValue V2,
10374 SelectionDAG &DAG,
10375 const X86Subtarget &Subtarget) {
10376 if (VT != MVT::v16i8 && VT != MVT::v8i16)
10377 return SDValue();
10378
10379 if (Mask.size() != VT.getVectorNumElements())
10380 return SDValue();
10381
10382 bool SwappedOps = false;
10383
10384 if (!ISD::isBuildVectorAllZeros(V2.getNode())) {
10385 if (!ISD::isBuildVectorAllZeros(V1.getNode()))
10386 return SDValue();
10387
10388 std::swap(V1, V2);
10389 SwappedOps = true;
10390 }
10391
10392 // Look for:
10393 //
10394 // bitcast (truncate <8 x i32> %vec to <8 x i16>) to <16 x i8>
10395 // bitcast (truncate <4 x i64> %vec to <4 x i32>) to <8 x i16>
10396 //
10397 // and similar ones.
10398 if (V1.getOpcode() != ISD::BITCAST)
10399 return SDValue();
10400 if (V1.getOperand(0).getOpcode() != ISD::TRUNCATE)
10401 return SDValue();
10402
10403 SDValue Src = V1.getOperand(0).getOperand(0);
10404 MVT SrcVT = Src.getSimpleValueType();
10405
10406 // The vptrunc** instructions truncating 128 bit and 256 bit vectors
10407 // are only available with avx512vl.
10408 if (!SrcVT.is512BitVector() && !Subtarget.hasVLX())
10409 return SDValue();
10410
10411 // Down Convert Word to Byte is only available with avx512bw. The case with
10412 // 256-bit output doesn't contain a shuffle and is therefore not handled here.
10413 if (SrcVT.getVectorElementType() == MVT::i16 && VT == MVT::v16i8 &&
10414 !Subtarget.hasBWI())
10415 return SDValue();
10416
10417 // The first half/quarter of the mask should refer to every second/fourth
10418 // element of the vector truncated and bitcasted.
10419 if (!matchVectorShuffleAsVPMOV(Mask, SwappedOps, 2) &&
10420 !matchVectorShuffleAsVPMOV(Mask, SwappedOps, 4))
10421 return SDValue();
10422
10423 return DAG.getNode(X86ISD::VTRUNC, DL, VT, Src);
10424}
10425
10426// X86 has dedicated pack instructions that can handle specific truncation
10427// operations: PACKSS and PACKUS.
10428static bool matchVectorShuffleWithPACK(MVT VT, MVT &SrcVT, SDValue &V1,
10429 SDValue &V2, unsigned &PackOpcode,
10430 ArrayRef<int> TargetMask,
10431 SelectionDAG &DAG,
10432 const X86Subtarget &Subtarget) {
10433 unsigned NumElts = VT.getVectorNumElements();
10434 unsigned BitSize = VT.getScalarSizeInBits();
10435 MVT PackSVT = MVT::getIntegerVT(BitSize * 2);
10436 MVT PackVT = MVT::getVectorVT(PackSVT, NumElts / 2);
10437
10438 auto MatchPACK = [&](SDValue N1, SDValue N2) {
10439 SDValue VV1 = DAG.getBitcast(PackVT, N1);
10440 SDValue VV2 = DAG.getBitcast(PackVT, N2);
10441 if (Subtarget.hasSSE41() || PackSVT == MVT::i16) {
10442 APInt ZeroMask = APInt::getHighBitsSet(BitSize * 2, BitSize);
10443 if ((N1.isUndef() || DAG.MaskedValueIsZero(VV1, ZeroMask)) &&
10444 (N2.isUndef() || DAG.MaskedValueIsZero(VV2, ZeroMask))) {
10445 V1 = VV1;
10446 V2 = VV2;
10447 SrcVT = PackVT;
10448 PackOpcode = X86ISD::PACKUS;
10449 return true;
10450 }
10451 }
10452 if ((N1.isUndef() || DAG.ComputeNumSignBits(VV1) > BitSize) &&
10453 (N2.isUndef() || DAG.ComputeNumSignBits(VV2) > BitSize)) {
10454 V1 = VV1;
10455 V2 = VV2;
10456 SrcVT = PackVT;
10457 PackOpcode = X86ISD::PACKSS;
10458 return true;
10459 }
10460 return false;
10461 };
10462
10463 // Try binary shuffle.
10464 SmallVector<int, 32> BinaryMask;
10465 createPackShuffleMask(VT, BinaryMask, false);
10466 if (isTargetShuffleEquivalent(TargetMask, BinaryMask))
10467 if (MatchPACK(V1, V2))
10468 return true;
10469
10470 // Try unary shuffle.
10471 SmallVector<int, 32> UnaryMask;
10472 createPackShuffleMask(VT, UnaryMask, true);
10473 if (isTargetShuffleEquivalent(TargetMask, UnaryMask))
10474 if (MatchPACK(V1, V1))
10475 return true;
10476
10477 return false;
10478}
10479
10480static SDValue lowerShuffleWithPACK(const SDLoc &DL, MVT VT, ArrayRef<int> Mask,
10481 SDValue V1, SDValue V2, SelectionDAG &DAG,
10482 const X86Subtarget &Subtarget) {
10483 MVT PackVT;
10484 unsigned PackOpcode;
10485 if (matchVectorShuffleWithPACK(VT, PackVT, V1, V2, PackOpcode, Mask, DAG,
10486 Subtarget))
10487 return DAG.getNode(PackOpcode, DL, VT, DAG.getBitcast(PackVT, V1),
10488 DAG.getBitcast(PackVT, V2));
10489
10490 return SDValue();
10491}
10492
10493/// Try to emit a bitmask instruction for a shuffle.
10494///
10495/// This handles cases where we can model a blend exactly as a bitmask due to
10496/// one of the inputs being zeroable.
10497static SDValue lowerShuffleAsBitMask(const SDLoc &DL, MVT VT, SDValue V1,
10498 SDValue V2, ArrayRef<int> Mask,
10499 const APInt &Zeroable,
10500 const X86Subtarget &Subtarget,
10501 SelectionDAG &DAG) {
10502 MVT MaskVT = VT;
10503 MVT EltVT = VT.getVectorElementType();
10504 SDValue Zero, AllOnes;
10505 // Use f64 if i64 isn't legal.
10506 if (EltVT == MVT::i64 && !Subtarget.is64Bit()) {
10507 EltVT = MVT::f64;
10508 MaskVT = MVT::getVectorVT(EltVT, Mask.size());
10509 }
10510
10511 MVT LogicVT = VT;
10512 if (EltVT == MVT::f32 || EltVT == MVT::f64) {
10513 Zero = DAG.getConstantFP(0.0, DL, EltVT);
10514 AllOnes = DAG.getConstantFP(
10515 APFloat::getAllOnesValue(EltVT.getSizeInBits(), true), DL, EltVT);
10516 LogicVT =
10517 MVT::getVectorVT(EltVT == MVT::f64 ? MVT::i64 : MVT::i32, Mask.size());
10518 } else {
10519 Zero = DAG.getConstant(0, DL, EltVT);
10520 AllOnes = DAG.getAllOnesConstant(DL, EltVT);
10521 }
10522
10523 SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
10524 SDValue V;
10525 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
10526 if (Zeroable[i])
10527 continue;
10528 if (Mask[i] % Size != i)
10529 return SDValue(); // Not a blend.
10530 if (!V)
10531 V = Mask[i] < Size ? V1 : V2;
10532 else if (V != (Mask[i] < Size ? V1 : V2))
10533 return SDValue(); // Can only let one input through the mask.
10534
10535 VMaskOps[i] = AllOnes;
10536 }
10537 if (!V)
10538 return SDValue(); // No non-zeroable elements!
10539
10540 SDValue VMask = DAG.getBuildVector(MaskVT, DL, VMaskOps);
10541 VMask = DAG.getBitcast(LogicVT, VMask);
10542 V = DAG.getBitcast(LogicVT, V);
10543 SDValue And = DAG.getNode(ISD::AND, DL, LogicVT, V, VMask);
10544 return DAG.getBitcast(VT, And);
10545}
10546
10547/// Try to emit a blend instruction for a shuffle using bit math.
10548///
10549/// This is used as a fallback approach when first class blend instructions are
10550/// unavailable. Currently it is only suitable for integer vectors, but could
10551/// be generalized for floating point vectors if desirable.
10552static SDValue lowerShuffleAsBitBlend(const SDLoc &DL, MVT VT, SDValue V1,
10553 SDValue V2, ArrayRef<int> Mask,
10554 SelectionDAG &DAG) {
10555 assert(VT.isInteger() && "Only supports integer vector types!")((VT.isInteger() && "Only supports integer vector types!"
) ? static_cast<void> (0) : __assert_fail ("VT.isInteger() && \"Only supports integer vector types!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 10555, __PRETTY_FUNCTION__))
;
10556 MVT EltVT = VT.getVectorElementType();
10557 SDValue Zero = DAG.getConstant(0, DL, EltVT);
10558 SDValue AllOnes = DAG.getAllOnesConstant(DL, EltVT);
10559 SmallVector<SDValue, 16> MaskOps;
10560 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
10561 if (Mask[i] >= 0 && Mask[i] != i && Mask[i] != i + Size)
10562 return SDValue(); // Shuffled input!
10563 MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
10564 }
10565
10566 SDValue V1Mask = DAG.getBuildVector(VT, DL, MaskOps);
10567 V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
10568 V2 = DAG.getNode(X86ISD::ANDNP, DL, VT, V1Mask, V2);
10569 return DAG.getNode(ISD::OR, DL, VT, V1, V2);
10570}
10571
10572static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
10573 SDValue PreservedSrc,
10574 const X86Subtarget &Subtarget,
10575 SelectionDAG &DAG);
10576
10577static bool matchVectorShuffleAsBlend(SDValue V1, SDValue V2,
10578 MutableArrayRef<int> TargetMask,
10579 bool &ForceV1Zero, bool &ForceV2Zero,
10580 uint64_t &BlendMask) {
10581 bool V1IsZeroOrUndef =
10582 V1.isUndef() || ISD::isBuildVectorAllZeros(V1.getNode());
10583 bool V2IsZeroOrUndef =
10584 V2.isUndef() || ISD::isBuildVectorAllZeros(V2.getNode());
10585
10586 BlendMask = 0;
10587 ForceV1Zero = false, ForceV2Zero = false;
10588 assert(TargetMask.size() <= 64 && "Shuffle mask too big for blend mask")((TargetMask.size() <= 64 && "Shuffle mask too big for blend mask"
) ? static_cast<void> (0) : __assert_fail ("TargetMask.size() <= 64 && \"Shuffle mask too big for blend mask\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 10588, __PRETTY_FUNCTION__))
;
10589
10590 // Attempt to generate the binary blend mask. If an input is zero then
10591 // we can use any lane.
10592 // TODO: generalize the zero matching to any scalar like isShuffleEquivalent.
10593 for (int i = 0, Size = TargetMask.size(); i < Size; ++i) {
10594 int M = TargetMask[i];
10595 if (M == SM_SentinelUndef)
10596 continue;
10597 if (M == i)
10598 continue;
10599 if (M == i + Size) {
10600 BlendMask |= 1ull << i;
10601 continue;
10602 }
10603 if (M == SM_SentinelZero) {
10604 if (V1IsZeroOrUndef) {
10605 ForceV1Zero = true;
10606 TargetMask[i] = i;
10607 continue;
10608 }
10609 if (V2IsZeroOrUndef) {
10610 ForceV2Zero = true;
10611 BlendMask |= 1ull << i;
10612 TargetMask[i] = i + Size;
10613 continue;
10614 }
10615 }
10616 return false;
10617 }
10618 return true;
10619}
10620
10621static uint64_t scaleVectorShuffleBlendMask(uint64_t BlendMask, int Size,
10622 int Scale) {
10623 uint64_t ScaledMask = 0;
10624 for (int i = 0; i != Size; ++i)
10625 if (BlendMask & (1ull << i))
10626 ScaledMask |= ((1ull << Scale) - 1) << (i * Scale);
10627 return ScaledMask;
10628}
10629
10630/// Try to emit a blend instruction for a shuffle.
10631///
10632/// This doesn't do any checks for the availability of instructions for blending
10633/// these values. It relies on the availability of the X86ISD::BLENDI pattern to
10634/// be matched in the backend with the type given. What it does check for is
10635/// that the shuffle mask is a blend, or convertible into a blend with zero.
10636static SDValue lowerShuffleAsBlend(const SDLoc &DL, MVT VT, SDValue V1,
10637 SDValue V2, ArrayRef<int> Original,
10638 const APInt &Zeroable,
10639 const X86Subtarget &Subtarget,
10640 SelectionDAG &DAG) {
10641 SmallVector<int, 64> Mask = createTargetShuffleMask(Original, Zeroable);
10642
10643 uint64_t BlendMask = 0;
10644 bool ForceV1Zero = false, ForceV2Zero = false;
10645 if (!matchVectorShuffleAsBlend(V1, V2, Mask, ForceV1Zero, ForceV2Zero,
10646 BlendMask))
10647 return SDValue();
10648
10649 // Create a REAL zero vector - ISD::isBuildVectorAllZeros allows UNDEFs.
10650 if (ForceV1Zero)
10651 V1 = getZeroVector(VT, Subtarget, DAG, DL);
10652 if (ForceV2Zero)
10653 V2 = getZeroVector(VT, Subtarget, DAG, DL);
10654
10655 switch (VT.SimpleTy) {
10656 case MVT::v4i64:
10657 case MVT::v8i32:
10658 assert(Subtarget.hasAVX2() && "256-bit integer blends require AVX2!")((Subtarget.hasAVX2() && "256-bit integer blends require AVX2!"
) ? static_cast<void> (0) : __assert_fail ("Subtarget.hasAVX2() && \"256-bit integer blends require AVX2!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 10658, __PRETTY_FUNCTION__))
;
10659 LLVM_FALLTHROUGH[[clang::fallthrough]];
10660 case MVT::v4f64:
10661 case MVT::v8f32:
10662 assert(Subtarget.hasAVX() && "256-bit float blends require AVX!")((Subtarget.hasAVX() && "256-bit float blends require AVX!"
) ? static_cast<void> (0) : __assert_fail ("Subtarget.hasAVX() && \"256-bit float blends require AVX!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 10662, __PRETTY_FUNCTION__))
;
10663 LLVM_FALLTHROUGH[[clang::fallthrough]];
10664 case MVT::v2f64:
10665 case MVT::v2i64:
10666 case MVT::v4f32:
10667 case MVT::v4i32:
10668 case MVT::v8i16:
10669 assert(Subtarget.hasSSE41() && "128-bit blends require SSE41!")((Subtarget.hasSSE41() && "128-bit blends require SSE41!"
) ? static_cast<void> (0) : __assert_fail ("Subtarget.hasSSE41() && \"128-bit blends require SSE41!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 10669, __PRETTY_FUNCTION__))
;
10670 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
10671 DAG.getConstant(BlendMask, DL, MVT::i8));
10672 case MVT::v16i16: {
10673 assert(Subtarget.hasAVX2() && "v16i16 blends require AVX2!")((Subtarget.hasAVX2() && "v16i16 blends require AVX2!"
) ? static_cast<void> (0) : __assert_fail ("Subtarget.hasAVX2() && \"v16i16 blends require AVX2!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 10673, __PRETTY_FUNCTION__))
;
10674 SmallVector<int, 8> RepeatedMask;
10675 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10676 // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
10677 assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!")((RepeatedMask.size() == 8 && "Repeated mask size doesn't match!"
) ? static_cast<void> (0) : __assert_fail ("RepeatedMask.size() == 8 && \"Repeated mask size doesn't match!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 10677, __PRETTY_FUNCTION__))
;
10678 BlendMask = 0;
10679 for (int i = 0; i < 8; ++i)
10680 if (RepeatedMask[i] >= 8)
10681 BlendMask |= 1ull << i;
10682 return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
10683 DAG.getConstant(BlendMask, DL, MVT::i8));
10684 }
10685 // Use PBLENDW for lower/upper lanes and then blend lanes.
10686 // TODO - we should allow 2 PBLENDW here and leave shuffle combine to
10687 // merge to VSELECT where useful.
10688 uint64_t LoMask = BlendMask & 0xFF;
10689 uint64_t HiMask = (BlendMask >> 8) & 0xFF;
10690 if (LoMask == 0 || LoMask == 255 || HiMask == 0 || HiMask == 255) {
10691 SDValue Lo = DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
10692 DAG.getConstant(LoMask, DL, MVT::i8));
10693 SDValue Hi = DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
10694 DAG.getConstant(HiMask, DL, MVT::i8));
10695 return DAG.getVectorShuffle(
10696 MVT::v16i16, DL, Lo, Hi,
10697 {0, 1, 2, 3, 4, 5, 6, 7, 24, 25, 26, 27, 28, 29, 30, 31});
10698 }
10699 LLVM_FALLTHROUGH[[clang::fallthrough]];
10700 }
10701 case MVT::v32i8:
10702 assert(Subtarget.hasAVX2() && "256-bit byte-blends require AVX2!")((Subtarget.hasAVX2() && "256-bit byte-blends require AVX2!"
) ? static_cast<void> (0) : __assert_fail ("Subtarget.hasAVX2() && \"256-bit byte-blends require AVX2!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 10702, __PRETTY_FUNCTION__))
;
10703 LLVM_FALLTHROUGH[[clang::fallthrough]];
10704 case MVT::v16i8: {
10705 assert(Subtarget.hasSSE41() && "128-bit byte-blends require SSE41!")((Subtarget.hasSSE41() && "128-bit byte-blends require SSE41!"
) ? static_cast<void> (0) : __assert_fail ("Subtarget.hasSSE41() && \"128-bit byte-blends require SSE41!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 10705, __PRETTY_FUNCTION__))
;
10706
10707 // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
10708 if (SDValue Masked = lowerShuffleAsBitMask(DL, VT, V1, V2, Mask, Zeroable,
10709 Subtarget, DAG))
10710 return Masked;
10711
10712 if (Subtarget.hasBWI() && Subtarget.hasVLX()) {
10713 MVT IntegerType =
10714 MVT::getIntegerVT(std::max((int)VT.getVectorNumElements(), 8));
10715 SDValue MaskNode = DAG.getConstant(BlendMask, DL, IntegerType);
10716 return getVectorMaskingNode(V2, MaskNode, V1, Subtarget, DAG);
10717 }
10718
10719 // Scale the blend by the number of bytes per element.
10720 int Scale = VT.getScalarSizeInBits() / 8;
10721
10722 // This form of blend is always done on bytes. Compute the byte vector
10723 // type.
10724 MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
10725
10726 // x86 allows load folding with blendvb from the 2nd source operand. But
10727 // we are still using LLVM select here (see comment below), so that's V1.
10728 // If V2 can be load-folded and V1 cannot be load-folded, then commute to
10729 // allow that load-folding possibility.
10730 if (!ISD::isNormalLoad(V1.getNode()) && ISD::isNormalLoad(V2.getNode())) {
10731 ShuffleVectorSDNode::commuteMask(Mask);
10732 std::swap(V1, V2);
10733 }
10734
10735 // Compute the VSELECT mask. Note that VSELECT is really confusing in the
10736 // mix of LLVM's code generator and the x86 backend. We tell the code
10737 // generator that boolean values in the elements of an x86 vector register
10738 // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
10739 // mapping a select to operand #1, and 'false' mapping to operand #2. The
10740 // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
10741 // of the element (the remaining are ignored) and 0 in that high bit would
10742 // mean operand #1 while 1 in the high bit would mean operand #2. So while
10743 // the LLVM model for boolean values in vector elements gets the relevant
10744 // bit set, it is set backwards and over constrained relative to x86's
10745 // actual model.
10746 SmallVector<SDValue, 32> VSELECTMask;
10747 for (int i = 0, Size = Mask.size(); i < Size; ++i)
10748 for (int j = 0; j < Scale; ++j)
10749 VSELECTMask.push_back(
10750 Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
10751 : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
10752 MVT::i8));
10753
10754 V1 = DAG.getBitcast(BlendVT, V1);
10755 V2 = DAG.getBitcast(BlendVT, V2);
10756 return DAG.getBitcast(
10757 VT,
10758 DAG.getSelect(DL, BlendVT, DAG.getBuildVector(BlendVT, DL, VSELECTMask),
10759 V1, V2));
10760 }
10761 case MVT::v16f32:
10762 case MVT::v8f64:
10763 case MVT::v8i64:
10764 case MVT::v16i32:
10765 case MVT::v32i16:
10766 case MVT::v64i8: {
10767 // Attempt to lower to a bitmask if we can. Only if not optimizing for size.
10768 bool OptForSize = DAG.getMachineFunction().getFunction().hasOptSize();
10769 if (!OptForSize) {
10770 if (SDValue Masked = lowerShuffleAsBitMask(DL, VT, V1, V2, Mask, Zeroable,
10771 Subtarget, DAG))
10772 return Masked;
10773 }
10774
10775 // Otherwise load an immediate into a GPR, cast to k-register, and use a
10776 // masked move.
10777 MVT IntegerType =
10778 MVT::getIntegerVT(std::max((int)VT.getVectorNumElements(), 8));
10779 SDValue MaskNode = DAG.getConstant(BlendMask, DL, IntegerType);
10780 return getVectorMaskingNode(V2, MaskNode, V1, Subtarget, DAG);
10781 }
10782 default:
10783 llvm_unreachable("Not a supported integer vector type!")::llvm::llvm_unreachable_internal("Not a supported integer vector type!"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 10783)
;
10784 }
10785}
10786
10787/// Try to lower as a blend of elements from two inputs followed by
10788/// a single-input permutation.
10789///
10790/// This matches the pattern where we can blend elements from two inputs and
10791/// then reduce the shuffle to a single-input permutation.
10792static SDValue lowerShuffleAsBlendAndPermute(const SDLoc &DL, MVT VT,
10793 SDValue V1, SDValue V2,
10794 ArrayRef<int> Mask,
10795 SelectionDAG &DAG,
10796 bool ImmBlends = false) {
10797 // We build up the blend mask while checking whether a blend is a viable way
10798 // to reduce the shuffle.
10799 SmallVector<int, 32> BlendMask(Mask.size(), -1);
10800 SmallVector<int, 32> PermuteMask(Mask.size(), -1);
10801
10802 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
10803 if (Mask[i] < 0)
10804 continue;
10805
10806 assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.")((Mask[i] < Size * 2 && "Shuffle input is out of bounds."
) ? static_cast<void> (0) : __assert_fail ("Mask[i] < Size * 2 && \"Shuffle input is out of bounds.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 10806, __PRETTY_FUNCTION__))
;
10807
10808 if (BlendMask[Mask[i] % Size] < 0)
10809 BlendMask[Mask[i] % Size] = Mask[i];
10810 else if (BlendMask[Mask[i] % Size] != Mask[i])
10811 return SDValue(); // Can't blend in the needed input!
10812
10813 PermuteMask[i] = Mask[i] % Size;
10814 }
10815
10816 // If only immediate blends, then bail if the blend mask can't be widened to
10817 // i16.
10818 unsigned EltSize = VT.getScalarSizeInBits();
10819 if (ImmBlends && EltSize == 8 && !canWidenShuffleElements(BlendMask))
10820 return SDValue();
10821
10822 SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
10823 return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
10824}
10825
10826/// Try to lower as an unpack of elements from two inputs followed by
10827/// a single-input permutation.
10828///
10829/// This matches the pattern where we can unpack elements from two inputs and
10830/// then reduce the shuffle to a single-input (wider) permutation.
10831static SDValue lowerShuffleAsUNPCKAndPermute(const SDLoc &DL, MVT VT,
10832 SDValue V1, SDValue V2,
10833 ArrayRef<int> Mask,
10834 SelectionDAG &DAG) {
10835 int NumElts = Mask.size();
10836 int NumLanes = VT.getSizeInBits() / 128;
10837 int NumLaneElts = NumElts / NumLanes;
10838 int NumHalfLaneElts = NumLaneElts / 2;
10839
10840 bool MatchLo = true, MatchHi = true;
10841 SDValue Ops[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT)};
10842
10843 // Determine UNPCKL/UNPCKH type and operand order.
10844 for (int Lane = 0; Lane != NumElts; Lane += NumLaneElts) {
10845 for (int Elt = 0; Elt != NumLaneElts; ++Elt) {
10846 int M = Mask[Lane + Elt];
10847 if (M < 0)
10848 continue;
10849
10850 SDValue &Op = Ops[Elt & 1];
10851 if (M < NumElts && (Op.isUndef() || Op == V1))
10852 Op = V1;
10853 else if (NumElts <= M && (Op.isUndef() || Op == V2))
10854 Op = V2;
10855 else
10856 return SDValue();
10857
10858 int Lo = Lane, Mid = Lane + NumHalfLaneElts, Hi = Lane + NumLaneElts;
10859 MatchLo &= isUndefOrInRange(M, Lo, Mid) ||
10860 isUndefOrInRange(M, NumElts + Lo, NumElts + Mid);
10861 MatchHi &= isUndefOrInRange(M, Mid, Hi) ||
10862 isUndefOrInRange(M, NumElts + Mid, NumElts + Hi);
10863 if (!MatchLo && !MatchHi)
10864 return SDValue();
10865 }
10866 }
10867 assert((MatchLo ^ MatchHi) && "Failed to match UNPCKLO/UNPCKHI")(((MatchLo ^ MatchHi) && "Failed to match UNPCKLO/UNPCKHI"
) ? static_cast<void> (0) : __assert_fail ("(MatchLo ^ MatchHi) && \"Failed to match UNPCKLO/UNPCKHI\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 10867, __PRETTY_FUNCTION__))
;
10868
10869 // Now check that each pair of elts come from the same unpack pair
10870 // and set the permute mask based on each pair.
10871 // TODO - Investigate cases where we permute individual elements.
10872 SmallVector<int, 32> PermuteMask(NumElts, -1);
10873 for (int Lane = 0; Lane != NumElts; Lane += NumLaneElts) {
10874 for (int Elt = 0; Elt != NumLaneElts; Elt += 2) {
10875 int M0 = Mask[Lane + Elt + 0];
10876 int M1 = Mask[Lane + Elt + 1];
10877 if (0 <= M0 && 0 <= M1 &&
10878 (M0 % NumHalfLaneElts) != (M1 % NumHalfLaneElts))
10879 return SDValue();
10880 if (0 <= M0)
10881 PermuteMask[Lane + Elt + 0] = Lane + (2 * (M0 % NumHalfLaneElts));
10882 if (0 <= M1)
10883 PermuteMask[Lane + Elt + 1] = Lane + (2 * (M1 % NumHalfLaneElts)) + 1;
10884 }
10885 }
10886
10887 unsigned UnpckOp = MatchLo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
10888 SDValue Unpck = DAG.getNode(UnpckOp, DL, VT, Ops);
10889 return DAG.getVectorShuffle(VT, DL, Unpck, DAG.getUNDEF(VT), PermuteMask);
10890}
10891
10892/// Helper to form a PALIGNR-based rotate+permute, merging 2 inputs and then
10893/// permuting the elements of the result in place.
10894static SDValue lowerShuffleAsByteRotateAndPermute(
10895 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
10896 const X86Subtarget &Subtarget, SelectionDAG &DAG) {
10897 if ((VT.is128BitVector() && !Subtarget.hasSSSE3()) ||
10898 (VT.is256BitVector() && !Subtarget.hasAVX2()) ||
10899 (VT.is512BitVector() && !Subtarget.hasBWI()))
10900 return SDValue();
10901
10902 // We don't currently support lane crossing permutes.
10903 if (is128BitLaneCrossingShuffleMask(VT, Mask))
10904 return SDValue();
10905
10906 int Scale = VT.getScalarSizeInBits() / 8;
10907 int NumLanes = VT.getSizeInBits() / 128;
10908 int NumElts = VT.getVectorNumElements();
10909 int NumEltsPerLane = NumElts / NumLanes;
10910
10911 // Determine range of mask elts.
10912 bool Blend1 = true;
10913 bool Blend2 = true;
10914 std::pair<int, int> Range1 = std::make_pair(INT_MAX2147483647, INT_MIN(-2147483647 -1));
10915 std::pair<int, int> Range2 = std::make_pair(INT_MAX2147483647, INT_MIN(-2147483647 -1));
10916 for (int Lane = 0; Lane != NumElts; Lane += NumEltsPerLane) {
10917 for (int Elt = 0; Elt != NumEltsPerLane; ++Elt) {
10918 int M = Mask[Lane + Elt];
10919 if (M < 0)
10920 continue;
10921 if (M < NumElts) {
10922 Blend1 &= (M == (Lane + Elt));
10923 assert(Lane <= M && M < (Lane + NumEltsPerLane) && "Out of range mask")((Lane <= M && M < (Lane + NumEltsPerLane) &&
"Out of range mask") ? static_cast<void> (0) : __assert_fail
("Lane <= M && M < (Lane + NumEltsPerLane) && \"Out of range mask\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 10923, __PRETTY_FUNCTION__))
;
10924 M = M % NumEltsPerLane;
10925 Range1.first = std::min(Range1.first, M);
10926 Range1.second = std::max(Range1.second, M);
10927 } else {
10928 M -= NumElts;
10929 Blend2 &= (M == (Lane + Elt));
10930 assert(Lane <= M && M < (Lane + NumEltsPerLane) && "Out of range mask")((Lane <= M && M < (Lane + NumEltsPerLane) &&
"Out of range mask") ? static_cast<void> (0) : __assert_fail
("Lane <= M && M < (Lane + NumEltsPerLane) && \"Out of range mask\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 10930, __PRETTY_FUNCTION__))
;
10931 M = M % NumEltsPerLane;
10932 Range2.first = std::min(Range2.first, M);
10933 Range2.second = std::max(Range2.second, M);
10934 }
10935 }
10936 }
10937
10938 // Bail if we don't need both elements.
10939 // TODO - it might be worth doing this for unary shuffles if the permute
10940 // can be widened.
10941 if (!(0 <= Range1.first && Range1.second < NumEltsPerLane) ||
10942 !(0 <= Range2.first && Range2.second < NumEltsPerLane))
10943 return SDValue();
10944
10945 if (VT.getSizeInBits() > 128 && (Blend1 || Blend2))
10946 return SDValue();
10947
10948 // Rotate the 2 ops so we can access both ranges, then permute the result.
10949 auto RotateAndPermute = [&](SDValue Lo, SDValue Hi, int RotAmt, int Ofs) {
10950 MVT ByteVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
10951 SDValue Rotate = DAG.getBitcast(
10952 VT, DAG.getNode(X86ISD::PALIGNR, DL, ByteVT, DAG.getBitcast(ByteVT, Hi),
10953 DAG.getBitcast(ByteVT, Lo),
10954 DAG.getConstant(Scale * RotAmt, DL, MVT::i8)));
10955 SmallVector<int, 64> PermMask(NumElts, SM_SentinelUndef);
10956 for (int Lane = 0; Lane != NumElts; Lane += NumEltsPerLane) {
10957 for (int Elt = 0; Elt != NumEltsPerLane; ++Elt) {
10958 int M = Mask[Lane + Elt];
10959 if (M < 0)
10960 continue;
10961 if (M < NumElts)
10962 PermMask[Lane + Elt] = Lane + ((M + Ofs - RotAmt) % NumEltsPerLane);
10963 else
10964 PermMask[Lane + Elt] = Lane + ((M - Ofs - RotAmt) % NumEltsPerLane);
10965 }
10966 }
10967 return DAG.getVectorShuffle(VT, DL, Rotate, DAG.getUNDEF(VT), PermMask);
10968 };
10969
10970 // Check if the ranges are small enough to rotate from either direction.
10971 if (Range2.second < Range1.first)
10972 return RotateAndPermute(V1, V2, Range1.first, 0);
10973 if (Range1.second < Range2.first)
10974 return RotateAndPermute(V2, V1, Range2.first, NumElts);
10975 return SDValue();
10976}
10977
10978/// Generic routine to decompose a shuffle and blend into independent
10979/// blends and permutes.
10980///
10981/// This matches the extremely common pattern for handling combined
10982/// shuffle+blend operations on newer X86 ISAs where we have very fast blend
10983/// operations. It will try to pick the best arrangement of shuffles and
10984/// blends.
10985static SDValue lowerShuffleAsDecomposedShuffleBlend(
10986 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
10987 const X86Subtarget &Subtarget, SelectionDAG &DAG) {
10988 // Shuffle the input elements into the desired positions in V1 and V2 and
10989 // blend them together.
10990 SmallVector<int, 32> V1Mask(Mask.size(), -1);
10991 SmallVector<int, 32> V2Mask(Mask.size(), -1);
10992 SmallVector<int, 32> BlendMask(Mask.size(), -1);
10993 for (int i = 0, Size = Mask.size(); i < Size; ++i)
10994 if (Mask[i] >= 0 && Mask[i] < Size) {
10995 V1Mask[i] = Mask[i];
10996 BlendMask[i] = i;
10997 } else if (Mask[i] >= Size) {
10998 V2Mask[i] = Mask[i] - Size;
10999 BlendMask[i] = i + Size;
11000 }
11001
11002 // Try to lower with the simpler initial blend/unpack/rotate strategies unless
11003 // one of the input shuffles would be a no-op. We prefer to shuffle inputs as
11004 // the shuffle may be able to fold with a load or other benefit. However, when
11005 // we'll have to do 2x as many shuffles in order to achieve this, a 2-input
11006 // pre-shuffle first is a better strategy.
11007 if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask)) {
11008 // Only prefer immediate blends to unpack/rotate.
11009 if (SDValue BlendPerm = lowerShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask,
11010 DAG, true))
11011 return BlendPerm;
11012 if (SDValue UnpackPerm = lowerShuffleAsUNPCKAndPermute(DL, VT, V1, V2, Mask,
11013 DAG))
11014 return UnpackPerm;
11015 if (SDValue RotatePerm = lowerShuffleAsByteRotateAndPermute(
11016 DL, VT, V1, V2, Mask, Subtarget, DAG))
11017 return RotatePerm;
11018 // Unpack/rotate failed - try again with variable blends.
11019 if (SDValue BlendPerm = lowerShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask,
11020 DAG))
11021 return BlendPerm;
11022 }
11023
11024 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
11025 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
11026 return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
11027}
11028
11029/// Try to lower a vector shuffle as a rotation.
11030///
11031/// This is used for support PALIGNR for SSSE3 or VALIGND/Q for AVX512.
11032static int matchShuffleAsRotate(SDValue &V1, SDValue &V2, ArrayRef<int> Mask) {
11033 int NumElts = Mask.size();
11034
11035 // We need to detect various ways of spelling a rotation:
11036 // [11, 12, 13, 14, 15, 0, 1, 2]
11037 // [-1, 12, 13, 14, -1, -1, 1, -1]
11038 // [-1, -1, -1, -1, -1, -1, 1, 2]
11039 // [ 3, 4, 5, 6, 7, 8, 9, 10]
11040 // [-1, 4, 5, 6, -1, -1, 9, -1]
11041 // [-1, 4, 5, 6, -1, -1, -1, -1]
11042 int Rotation = 0;
11043 SDValue Lo, Hi;
11044 for (int i = 0; i < NumElts; ++i) {
11045 int M = Mask[i];
11046 assert((M == SM_SentinelUndef || (0 <= M && M < (2*NumElts))) &&(((M == SM_SentinelUndef || (0 <= M && M < (2*NumElts
))) && "Unexpected mask index.") ? static_cast<void
> (0) : __assert_fail ("(M == SM_SentinelUndef || (0 <= M && M < (2*NumElts))) && \"Unexpected mask index.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 11047, __PRETTY_FUNCTION__))
11047 "Unexpected mask index.")(((M == SM_SentinelUndef || (0 <= M && M < (2*NumElts
))) && "Unexpected mask index.") ? static_cast<void
> (0) : __assert_fail ("(M == SM_SentinelUndef || (0 <= M && M < (2*NumElts))) && \"Unexpected mask index.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 11047, __PRETTY_FUNCTION__))
;
11048 if (M < 0)
11049 continue;
11050
11051 // Determine where a rotated vector would have started.
11052 int StartIdx = i - (M % NumElts);
11053 if (StartIdx == 0)
11054 // The identity rotation isn't interesting, stop.
11055 return -1;
11056
11057 // If we found the tail of a vector the rotation must be the missing
11058 // front. If we found the head of a vector, it must be how much of the
11059 // head.
11060 int CandidateRotation = StartIdx < 0 ? -StartIdx : NumElts - StartIdx;
11061
11062 if (Rotation == 0)
11063 Rotation = CandidateRotation;
11064 else if (Rotation != CandidateRotation)
11065 // The rotations don't match, so we can't match this mask.
11066 return -1;
11067
11068 // Compute which value this mask is pointing at.
11069 SDValue MaskV = M < NumElts ? V1 : V2;
11070
11071 // Compute which of the two target values this index should be assigned
11072 // to. This reflects whether the high elements are remaining or the low
11073 // elements are remaining.
11074 SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
11075
11076 // Either set up this value if we've not encountered it before, or check
11077 // that it remains consistent.
11078 if (!TargetV)
11079 TargetV = MaskV;
11080 else if (TargetV != MaskV)
11081 // This may be a rotation, but it pulls from the inputs in some
11082 // unsupported interleaving.
11083 return -1;
11084 }
11085
11086 // Check that we successfully analyzed the mask, and normalize the results.
11087 assert(Rotation != 0 && "Failed to locate a viable rotation!")((Rotation != 0 && "Failed to locate a viable rotation!"
) ? static_cast<void> (0) : __assert_fail ("Rotation != 0 && \"Failed to locate a viable rotation!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 11087, __PRETTY_FUNCTION__))
;
11088 assert((Lo || Hi) && "Failed to find a rotated input vector!")(((Lo || Hi) && "Failed to find a rotated input vector!"
) ? static_cast<void> (0) : __assert_fail ("(Lo || Hi) && \"Failed to find a rotated input vector!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 11088, __PRETTY_FUNCTION__))
;
11089 if (!Lo)
11090 Lo = Hi;
11091 else if (!Hi)
11092 Hi = Lo;
11093
11094 V1 = Lo;
11095 V2 = Hi;
11096
11097 return Rotation;
11098}
11099
11100/// Try to lower a vector shuffle as a byte rotation.
11101///
11102/// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
11103/// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
11104/// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
11105/// try to generically lower a vector shuffle through such an pattern. It
11106/// does not check for the profitability of lowering either as PALIGNR or
11107/// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
11108/// This matches shuffle vectors that look like:
11109///
11110/// v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
11111///
11112/// Essentially it concatenates V1 and V2, shifts right by some number of
11113/// elements, and takes the low elements as the result. Note that while this is
11114/// specified as a *right shift* because x86 is little-endian, it is a *left
11115/// rotate* of the vector lanes.
11116static int matchShuffleAsByteRotate(MVT VT, SDValue &V1, SDValue &V2,
11117 ArrayRef<int> Mask) {
11118 // Don't accept any shuffles with zero elements.
11119 if (any_of(Mask, [](int M) { return M == SM_SentinelZero; }))
11120 return -1;
11121
11122 // PALIGNR works on 128-bit lanes.
11123 SmallVector<int, 16> RepeatedMask;
11124 if (!is128BitLaneRepeatedShuffleMask(VT, Mask, RepeatedMask))
11125 return -1;
11126
11127 int Rotation = matchShuffleAsRotate(V1, V2, RepeatedMask);
11128 if (Rotation <= 0)
11129 return -1;
11130
11131 // PALIGNR rotates bytes, so we need to scale the
11132 // rotation based on how many bytes are in the vector lane.
11133 int NumElts = RepeatedMask.size();
11134 int Scale = 16 / NumElts;
11135 return Rotation * Scale;
11136}
11137
11138static SDValue lowerShuffleAsByteRotate(const SDLoc &DL, MVT VT, SDValue V1,
11139 SDValue V2, ArrayRef<int> Mask,
11140 const X86Subtarget &Subtarget,
11141 SelectionDAG &DAG) {
11142 assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!")((!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!"
) ? static_cast<void> (0) : __assert_fail ("!isNoopShuffleMask(Mask) && \"We shouldn't lower no-op shuffles!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 11142, __PRETTY_FUNCTION__))
;
11143
11144 SDValue Lo = V1, Hi = V2;
11145 int ByteRotation = matchShuffleAsByteRotate(VT, Lo, Hi, Mask);
11146 if (ByteRotation <= 0)
11147 return SDValue();
11148
11149 // Cast the inputs to i8 vector of correct length to match PALIGNR or
11150 // PSLLDQ/PSRLDQ.
11151 MVT ByteVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
11152 Lo = DAG.getBitcast(ByteVT, Lo);
11153 Hi = DAG.getBitcast(ByteVT, Hi);
11154
11155 // SSSE3 targets can use the palignr instruction.
11156 if (Subtarget.hasSSSE3()) {
11157 assert((!VT.is512BitVector() || Subtarget.hasBWI()) &&(((!VT.is512BitVector() || Subtarget.hasBWI()) && "512-bit PALIGNR requires BWI instructions"
) ? static_cast<void> (0) : __assert_fail ("(!VT.is512BitVector() || Subtarget.hasBWI()) && \"512-bit PALIGNR requires BWI instructions\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 11158, __PRETTY_FUNCTION__))
11158 "512-bit PALIGNR requires BWI instructions")(((!VT.is512BitVector() || Subtarget.hasBWI()) && "512-bit PALIGNR requires BWI instructions"
) ? static_cast<void> (0) : __assert_fail ("(!VT.is512BitVector() || Subtarget.hasBWI()) && \"512-bit PALIGNR requires BWI instructions\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 11158, __PRETTY_FUNCTION__))
;
11159 return DAG.getBitcast(
11160 VT, DAG.getNode(X86ISD::PALIGNR, DL, ByteVT, Lo, Hi,
11161 DAG.getConstant(ByteRotation, DL, MVT::i8)));
11162 }
11163
11164 assert(VT.is128BitVector() &&((VT.is128BitVector() && "Rotate-based lowering only supports 128-bit lowering!"
) ? static_cast<void> (0) : __assert_fail ("VT.is128BitVector() && \"Rotate-based lowering only supports 128-bit lowering!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 11165, __PRETTY_FUNCTION__))
11165 "Rotate-based lowering only supports 128-bit lowering!")((VT.is128BitVector() && "Rotate-based lowering only supports 128-bit lowering!"
) ? static_cast<void> (0) : __assert_fail ("VT.is128BitVector() && \"Rotate-based lowering only supports 128-bit lowering!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 11165, __PRETTY_FUNCTION__))
;
11166 assert(Mask.size() <= 16 &&((Mask.size() <= 16 && "Can shuffle at most 16 bytes in a 128-bit vector!"
) ? static_cast<void> (0) : __assert_fail ("Mask.size() <= 16 && \"Can shuffle at most 16 bytes in a 128-bit vector!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 11167, __PRETTY_FUNCTION__))
11167 "Can shuffle at most 16 bytes in a 128-bit vector!")((Mask.size() <= 16 && "Can shuffle at most 16 bytes in a 128-bit vector!"
) ? static_cast<void> (0) : __assert_fail ("Mask.size() <= 16 && \"Can shuffle at most 16 bytes in a 128-bit vector!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 11167, __PRETTY_FUNCTION__))
;
11168 assert(ByteVT == MVT::v16i8 &&((ByteVT == MVT::v16i8 && "SSE2 rotate lowering only needed for v16i8!"
) ? static_cast<void> (0) : __assert_fail ("ByteVT == MVT::v16i8 && \"SSE2 rotate lowering only needed for v16i8!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 11169, __PRETTY_FUNCTION__))
11169 "SSE2 rotate lowering only needed for v16i8!")((ByteVT == MVT::v16i8 && "SSE2 rotate lowering only needed for v16i8!"
) ? static_cast<void> (0) : __assert_fail ("ByteVT == MVT::v16i8 && \"SSE2 rotate lowering only needed for v16i8!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 11169, __PRETTY_FUNCTION__))
;
11170
11171 // Default SSE2 implementation
11172 int LoByteShift = 16 - ByteRotation;
11173 int HiByteShift = ByteRotation;
11174
11175 SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Lo,
11176 DAG.getConstant(LoByteShift, DL, MVT::i8));
11177 SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v16i8, Hi,
11178 DAG.getConstant(HiByteShift, DL, MVT::i8));
11179 return DAG.getBitcast(VT,
11180 DAG.getNode(ISD::OR, DL, MVT::v16i8, LoShift, HiShift));
11181}
11182
11183/// Try to lower a vector shuffle as a dword/qword rotation.
11184///
11185/// AVX512 has a VALIGND/VALIGNQ instructions that will do an arbitrary
11186/// rotation of the concatenation of two vectors; This routine will
11187/// try to generically lower a vector shuffle through such an pattern.
11188///
11189/// Essentially it concatenates V1 and V2, shifts right by some number of
11190/// elements, and takes the low elements as the result. Note that while this is
11191/// specified as a *right shift* because x86 is little-endian, it is a *left
11192/// rotate* of the vector lanes.
11193static SDValue lowerShuffleAsRotate(const SDLoc &DL, MVT VT, SDValue V1,
11194 SDValue V2, ArrayRef<int> Mask,
11195 const X86Subtarget &Subtarget,
11196 SelectionDAG &DAG) {
11197 assert((VT.getScalarType() == MVT::i32 || VT.getScalarType() == MVT::i64) &&(((VT.getScalarType() == MVT::i32 || VT.getScalarType() == MVT
::i64) && "Only 32-bit and 64-bit elements are supported!"
) ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 11198, __PRETTY_FUNCTION__))
11198 "Only 32-bit and 64-bit elements are supported!")(((VT.getScalarType() == MVT::i32 || VT.getScalarType() == MVT
::i64) && "Only 32-bit and 64-bit elements are supported!"
) ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 11198, __PRETTY_FUNCTION__))
;
11199
11200 // 128/256-bit vectors are only supported with VLX.
11201 assert((Subtarget.hasVLX() || (!VT.is128BitVector() && !VT.is256BitVector()))(((Subtarget.hasVLX() || (!VT.is128BitVector() && !VT
.is256BitVector())) && "VLX required for 128/256-bit vectors"
) ? static_cast<void> (0) : __assert_fail ("(Subtarget.hasVLX() || (!VT.is128BitVector() && !VT.is256BitVector())) && \"VLX required for 128/256-bit vectors\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 11202, __PRETTY_FUNCTION__))
11202 && "VLX required for 128/256-bit vectors")(((Subtarget.hasVLX() || (!VT.is128BitVector() && !VT
.is256BitVector())) && "VLX required for 128/256-bit vectors"
) ? static_cast<void> (0) : __assert_fail ("(Subtarget.hasVLX() || (!VT.is128BitVector() && !VT.is256BitVector())) && \"VLX required for 128/256-bit vectors\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 11202, __PRETTY_FUNCTION__))
;
11203
11204 SDValue Lo = V1, Hi = V2;
11205 int Rotation = matchShuffleAsRotate(Lo, Hi, Mask);
11206 if (Rotation <= 0)
11207 return SDValue();
11208
11209 return DAG.getNode(X86ISD::VALIGN, DL, VT, Lo, Hi,
11210 DAG.getConstant(Rotation, DL, MVT::i8));
11211}
11212
11213/// Try to lower a vector shuffle as a byte shift sequence.
11214static SDValue lowerVectorShuffleAsByteShiftMask(
11215 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
11216 const APInt &Zeroable, const X86Subtarget &Subtarget, SelectionDAG &DAG) {
11217 assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!")((!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!"
) ? static_cast<void> (0) : __assert_fail ("!isNoopShuffleMask(Mask) && \"We shouldn't lower no-op shuffles!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 11217, __PRETTY_FUNCTION__))
;
11218 assert(VT.is128BitVector() && "Only 128-bit vectors supported")((VT.is128BitVector() && "Only 128-bit vectors supported"
) ? static_cast<void> (0) : __assert_fail ("VT.is128BitVector() && \"Only 128-bit vectors supported\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 11218, __PRETTY_FUNCTION__))
;
11219
11220 // We need a shuffle that has zeros at one/both ends and a sequential
11221 // shuffle from one source within.
11222 unsigned ZeroLo = Zeroable.countTrailingOnes();
11223 unsigned ZeroHi = Zeroable.countLeadingOnes();
11224 if (!ZeroLo && !ZeroHi)
11225 return SDValue();
11226
11227 unsigned NumElts = Mask.size();
11228 unsigned Len = NumElts - (ZeroLo + ZeroHi);
11229 if (!isSequentialOrUndefInRange(Mask, ZeroLo, Len, Mask[ZeroLo]))
11230 return SDValue();
11231
11232 unsigned Scale = VT.getScalarSizeInBits() / 8;
11233 ArrayRef<int> StubMask = Mask.slice(ZeroLo, Len);
11234 if (!isUndefOrInRange(StubMask, 0, NumElts) &&
11235 !isUndefOrInRange(StubMask, NumElts, 2 * NumElts))
11236 return SDValue();
11237
11238 SDValue Res = Mask[ZeroLo] < (int)NumElts ? V1 : V2;
11239 Res = DAG.getBitcast(MVT::v16i8, Res);
11240
11241 // Use VSHLDQ/VSRLDQ ops to zero the ends of a vector and leave an
11242 // inner sequential set of elements, possibly offset:
11243 // 01234567 --> zzzzzz01 --> 1zzzzzzz
11244 // 01234567 --> 4567zzzz --> zzzzz456
11245 // 01234567 --> z0123456 --> 3456zzzz --> zz3456zz
11246 if (ZeroLo == 0) {
11247 unsigned Shift = (NumElts - 1) - (Mask[ZeroLo + Len - 1] % NumElts);
11248 Res = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Res,
11249 DAG.getConstant(Scale * Shift, DL, MVT::i8));
11250 Res = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v16i8, Res,
11251 DAG.getConstant(Scale * ZeroHi, DL, MVT::i8));
11252 } else if (ZeroHi == 0) {
11253 unsigned Shift = Mask[ZeroLo] % NumElts;
11254 Res = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v16i8, Res,
11255 DAG.getConstant(Scale * Shift, DL, MVT::i8));
11256 Res = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Res,
11257 DAG.getConstant(Scale * ZeroLo, DL, MVT::i8));
11258 } else if (!Subtarget.hasSSSE3()) {
11259 // If we don't have PSHUFB then its worth avoiding an AND constant mask
11260 // by performing 3 byte shifts. Shuffle combining can kick in above that.
11261 // TODO: There may be some cases where VSH{LR}DQ+PAND is still better.
11262 unsigned Shift = (NumElts - 1) - (Mask[ZeroLo + Len - 1] % NumElts);
11263 Res = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Res,
11264 DAG.getConstant(Scale * Shift, DL, MVT::i8));
11265 Shift += Mask[ZeroLo] % NumElts;
11266 Res = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v16i8, Res,
11267 DAG.getConstant(Scale * Shift, DL, MVT::i8));
11268 Res = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v16i8, Res,
11269 DAG.getConstant(Scale * ZeroLo, DL, MVT::i8));
11270 } else
11271 return SDValue();
11272
11273 return DAG.getBitcast(VT, Res);
11274}
11275
11276/// Try to lower a vector shuffle as a bit shift (shifts in zeros).
11277///
11278/// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
11279/// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
11280/// matches elements from one of the input vectors shuffled to the left or
11281/// right with zeroable elements 'shifted in'. It handles both the strictly
11282/// bit-wise element shifts and the byte shift across an entire 128-bit double
11283/// quad word lane.
11284///
11285/// PSHL : (little-endian) left bit shift.
11286/// [ zz, 0, zz, 2 ]
11287/// [ -1, 4, zz, -1 ]
11288/// PSRL : (little-endian) right bit shift.
11289/// [ 1, zz, 3, zz]
11290/// [ -1, -1, 7, zz]
11291/// PSLLDQ : (little-endian) left byte shift
11292/// [ zz, 0, 1, 2, 3, 4, 5, 6]
11293/// [ zz, zz, -1, -1, 2, 3, 4, -1]
11294/// [ zz, zz, zz, zz, zz, zz, -1, 1]
11295/// PSRLDQ : (little-endian) right byte shift
11296/// [ 5, 6, 7, zz, zz, zz, zz, zz]
11297/// [ -1, 5, 6, 7, zz, zz, zz, zz]
11298/// [ 1, 2, -1, -1, -1, -1, zz, zz]
11299static int matchShuffleAsShift(MVT &ShiftVT, unsigned &Opcode,
11300 unsigned ScalarSizeInBits, ArrayRef<int> Mask,
11301 int MaskOffset, const APInt &Zeroable,
11302 const X86Subtarget &Subtarget) {
11303 int Size = Mask.size();
11304 unsigned SizeInBits = Size * ScalarSizeInBits;
11305
11306 auto CheckZeros = [&](int Shift, int Scale, bool Left) {
11307 for (int i = 0; i < Size; i += Scale)
11308 for (int j = 0; j < Shift; ++j)
11309 if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
11310 return false;
11311
11312 return true;
11313 };
11314
11315 auto MatchShift = [&](int Shift, int Scale, bool Left) {
11316 for (int i = 0; i != Size; i += Scale) {
11317 unsigned Pos = Left ? i + Shift : i;
11318 unsigned Low = Left ? i : i + Shift;
11319 unsigned Len = Scale - Shift;
11320 if (!isSequentialOrUndefInRange(Mask, Pos, Len, Low + MaskOffset))
11321 return -1;
11322 }
11323
11324 int ShiftEltBits = ScalarSizeInBits * Scale;
11325 bool ByteShift = ShiftEltBits > 64;
11326 Opcode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
11327 : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
11328 int ShiftAmt = Shift * ScalarSizeInBits / (ByteShift ? 8 : 1);
11329
11330 // Normalize the scale for byte shifts to still produce an i64 element
11331 // type.
11332 Scale = ByteShift ? Scale / 2 : Scale;
11333
11334 // We need to round trip through the appropriate type for the shift.
11335 MVT ShiftSVT = MVT::getIntegerVT(ScalarSizeInBits * Scale);
11336 ShiftVT = ByteShift ? MVT::getVectorVT(MVT::i8, SizeInBits / 8)
11337 : MVT::getVectorVT(ShiftSVT, Size / Scale);
11338 return (int)ShiftAmt;
11339 };
11340
11341 // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
11342 // keep doubling the size of the integer elements up to that. We can
11343 // then shift the elements of the integer vector by whole multiples of
11344 // their width within the elements of the larger integer vector. Test each
11345 // multiple to see if we can find a match with the moved element indices
11346 // and that the shifted in elements are all zeroable.
11347 unsigned MaxWidth = ((SizeInBits == 512) && !Subtarget.hasBWI() ? 64 : 128);
11348 for (int Scale = 2; Scale * ScalarSizeInBits <= MaxWidth; Scale *= 2)
11349 for (int Shift = 1; Shift != Scale; ++Shift)
11350 for (bool Left : {true, false})
11351 if (CheckZeros(Shift, Scale, Left)) {
11352 int ShiftAmt = MatchShift(Shift, Scale, Left);
11353 if (0 < ShiftAmt)
11354 return ShiftAmt;
11355 }
11356
11357 // no match
11358 return -1;
11359}
11360
11361static SDValue lowerShuffleAsShift(const SDLoc &DL, MVT VT, SDValue V1,
11362 SDValue V2, ArrayRef<int> Mask,
11363 const APInt &Zeroable,
11364 const X86Subtarget &Subtarget,
11365 SelectionDAG &DAG) {
11366 int Size = Mask.size();
11367 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size")((Size == (int)VT.getVectorNumElements() && "Unexpected mask size"
) ? static_cast<void> (0) : __assert_fail ("Size == (int)VT.getVectorNumElements() && \"Unexpected mask size\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 11367, __PRETTY_FUNCTION__))
;
11368
11369 MVT ShiftVT;
11370 SDValue V = V1;
11371 unsigned Opcode;
11372
11373 // Try to match shuffle against V1 shift.
11374 int ShiftAmt = matchShuffleAsShift(ShiftVT, Opcode, VT.getScalarSizeInBits(),
11375 Mask, 0, Zeroable, Subtarget);
11376
11377 // If V1 failed, try to match shuffle against V2 shift.
11378 if (ShiftAmt < 0) {
11379 ShiftAmt = matchShuffleAsShift(ShiftVT, Opcode, VT.getScalarSizeInBits(),
11380 Mask, Size, Zeroable, Subtarget);
11381 V = V2;
11382 }
11383
11384 if (ShiftAmt < 0)
11385 return SDValue();
11386
11387 assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&((DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
"Illegal integer vector type") ? static_cast<void> (0)
: __assert_fail ("DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) && \"Illegal integer vector type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 11388, __PRETTY_FUNCTION__))
11388 "Illegal integer vector type")((DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
"Illegal integer vector type") ? static_cast<void> (0)
: __assert_fail ("DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) && \"Illegal integer vector type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 11388, __PRETTY_FUNCTION__))
;
11389 V = DAG.getBitcast(ShiftVT, V);
11390 V = DAG.getNode(Opcode, DL, ShiftVT, V,
11391 DAG.getConstant(ShiftAmt, DL, MVT::i8));
11392 return DAG.getBitcast(VT, V);
11393}
11394
11395// EXTRQ: Extract Len elements from lower half of source, starting at Idx.
11396// Remainder of lower half result is zero and upper half is all undef.
11397static bool matchShuffleAsEXTRQ(MVT VT, SDValue &V1, SDValue &V2,
11398 ArrayRef<int> Mask, uint64_t &BitLen,
11399 uint64_t &BitIdx, const APInt &Zeroable) {
11400 int Size = Mask.size();
11401 int HalfSize = Size / 2;
11402 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size")((Size == (int)VT.getVectorNumElements() && "Unexpected mask size"
) ? static_cast<void> (0) : __assert_fail ("Size == (int)VT.getVectorNumElements() && \"Unexpected mask size\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 11402, __PRETTY_FUNCTION__))
;
11403 assert(!Zeroable.isAllOnesValue() && "Fully zeroable shuffle mask")((!Zeroable.isAllOnesValue() && "Fully zeroable shuffle mask"
) ? static_cast<void> (0) : __assert_fail ("!Zeroable.isAllOnesValue() && \"Fully zeroable shuffle mask\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 11403, __PRETTY_FUNCTION__))
;
11404
11405 // Upper half must be undefined.
11406 if (!isUndefUpperHalf(Mask))
11407 return false;
11408
11409 // Determine the extraction length from the part of the
11410 // lower half that isn't zeroable.
11411 int Len = HalfSize;
11412 for (; Len > 0; --Len)
11413 if (!Zeroable[Len - 1])
11414 break;
11415 assert(Len > 0 && "Zeroable shuffle mask")((Len > 0 && "Zeroable shuffle mask") ? static_cast
<void> (0) : __assert_fail ("Len > 0 && \"Zeroable shuffle mask\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 11415, __PRETTY_FUNCTION__))
;
11416
11417 // Attempt to match first Len sequential elements from the lower half.
11418 SDValue Src;
11419 int Idx = -1;
11420 for (int i = 0; i != Len; ++i) {
11421 int M = Mask[i];
11422 if (M == SM_SentinelUndef)
11423 continue;
11424 SDValue &V = (M < Size ? V1 : V2);
11425 M = M % Size;
11426
11427 // The extracted elements must start at a valid index and all mask
11428 // elements must be in the lower half.
11429 if (i > M || M >= HalfSize)
11430 return false;
11431
11432 if (Idx < 0 || (Src == V && Idx == (M - i))) {
11433 Src = V;
11434 Idx = M - i;
11435 continue;
11436 }
11437 return false;
11438 }
11439
11440 if (!Src || Idx < 0)
11441 return false;
11442
11443 assert((Idx + Len) <= HalfSize && "Illegal extraction mask")(((Idx + Len) <= HalfSize && "Illegal extraction mask"
) ? static_cast<void> (0) : __assert_fail ("(Idx + Len) <= HalfSize && \"Illegal extraction mask\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 11443, __PRETTY_FUNCTION__))
;
11444 BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
11445 BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
11446 V1 = Src;
11447 return true;
11448}
11449
11450// INSERTQ: Extract lowest Len elements from lower half of second source and
11451// insert over first source, starting at Idx.
11452// { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
11453static bool matchShuffleAsINSERTQ(MVT VT, SDValue &V1, SDValue &V2,
11454 ArrayRef<int> Mask, uint64_t &BitLen,
11455 uint64_t &BitIdx) {
11456 int Size = Mask.size();
11457 int HalfSize = Size / 2;
11458 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size")((Size == (int)VT.getVectorNumElements() && "Unexpected mask size"
) ? static_cast<void> (0) : __assert_fail ("Size == (int)VT.getVectorNumElements() && \"Unexpected mask size\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 11458, __PRETTY_FUNCTION__))
;
11459
11460 // Upper half must be undefined.
11461 if (!isUndefUpperHalf(Mask))
11462 return false;
11463
11464 for (int Idx = 0; Idx != HalfSize; ++Idx) {
11465 SDValue Base;
11466
11467 // Attempt to match first source from mask before insertion point.
11468 if (isUndefInRange(Mask, 0, Idx)) {
11469 /* EMPTY */
11470 } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
11471 Base = V1;
11472 } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
11473 Base = V2;
11474 } else {
11475 continue;
11476 }
11477
11478 // Extend the extraction length looking to match both the insertion of
11479 // the second source and the remaining elements of the first.
11480 for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
11481 SDValue Insert;
11482 int Len = Hi - Idx;
11483
11484 // Match insertion.
11485 if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
11486 Insert = V1;
11487 } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
11488 Insert = V2;
11489 } else {
11490 continue;
11491 }
11492
11493 // Match the remaining elements of the lower half.
11494 if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
11495 /* EMPTY */
11496 } else if ((!Base || (Base == V1)) &&
11497 isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
11498 Base = V1;
11499 } else if ((!Base || (Base == V2)) &&
11500 isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
11501 Size + Hi)) {
11502 Base = V2;
11503 } else {
11504 continue;
11505 }
11506
11507 BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
11508 BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
11509 V1 = Base;
11510 V2 = Insert;
11511 return true;
11512 }
11513 }
11514
11515 return false;
11516}
11517
11518/// Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
11519static SDValue lowerShuffleWithSSE4A(const SDLoc &DL, MVT VT, SDValue V1,
11520 SDValue V2, ArrayRef<int> Mask,
11521 const APInt &Zeroable, SelectionDAG &DAG) {
11522 uint64_t BitLen, BitIdx;
11523 if (matchShuffleAsEXTRQ(VT, V1, V2, Mask, BitLen, BitIdx, Zeroable))
11524 return DAG.getNode(X86ISD::EXTRQI, DL, VT, V1,
11525 DAG.getConstant(BitLen, DL, MVT::i8),
11526 DAG.getConstant(BitIdx, DL, MVT::i8));
11527
11528 if (matchShuffleAsINSERTQ(VT, V1, V2, Mask, BitLen, BitIdx))
11529 return DAG.getNode(X86ISD::INSERTQI, DL, VT, V1 ? V1 : DAG.getUNDEF(VT),
11530 V2 ? V2 : DAG.getUNDEF(VT),
11531 DAG.getConstant(BitLen, DL, MVT::i8),
11532 DAG.getConstant(BitIdx, DL, MVT::i8));
11533
11534 return SDValue();
11535}
11536
11537/// Lower a vector shuffle as a zero or any extension.
11538///
11539/// Given a specific number of elements, element bit width, and extension
11540/// stride, produce either a zero or any extension based on the available
11541/// features of the subtarget. The extended elements are consecutive and
11542/// begin and can start from an offsetted element index in the input; to
11543/// avoid excess shuffling the offset must either being in the bottom lane
11544/// or at the start of a higher lane. All extended elements must be from
11545/// the same lane.
11546static SDValue lowerShuffleAsSpecificZeroOrAnyExtend(
11547 const SDLoc &DL, MVT VT, int Scale, int Offset, bool AnyExt, SDValue InputV,
11548 ArrayRef<int> Mask, const X86Subtarget &Subtarget, SelectionDAG &DAG) {
11549 assert(Scale > 1 && "Need a scale to extend.")((Scale > 1 && "Need a scale to extend.") ? static_cast
<void> (0) : __assert_fail ("Scale > 1 && \"Need a scale to extend.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 11549, __PRETTY_FUNCTION__))
;
11550 int EltBits = VT.getScalarSizeInBits();
11551 int NumElements = VT.getVectorNumElements();
11552 int NumEltsPerLane = 128 / EltBits;
11553 int OffsetLane = Offset / NumEltsPerLane;
11554 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&(((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
"Only 8, 16, and 32 bit elements can be extended.") ? static_cast
<void> (0) : __assert_fail ("(EltBits == 8 || EltBits == 16 || EltBits == 32) && \"Only 8, 16, and 32 bit elements can be extended.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 11555, __PRETTY_FUNCTION__))
11555 "Only 8, 16, and 32 bit elements can be extended.")(((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
"Only 8, 16, and 32 bit elements can be extended.") ? static_cast
<void> (0) : __assert_fail ("(EltBits == 8 || EltBits == 16 || EltBits == 32) && \"Only 8, 16, and 32 bit elements can be extended.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 11555, __PRETTY_FUNCTION__))
;
11556 assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.")((Scale * EltBits <= 64 && "Cannot zero extend past 64 bits."
) ? static_cast<void> (0) : __assert_fail ("Scale * EltBits <= 64 && \"Cannot zero extend past 64 bits.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 11556, __PRETTY_FUNCTION__))
;
11557 assert(0 <= Offset && "Extension offset must be positive.")((0 <= Offset && "Extension offset must be positive."
) ? static_cast<void> (0) : __assert_fail ("0 <= Offset && \"Extension offset must be positive.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 11557, __PRETTY_FUNCTION__))
;
11558 assert((Offset < NumEltsPerLane || Offset % NumEltsPerLane == 0) &&(((Offset < NumEltsPerLane || Offset % NumEltsPerLane == 0
) && "Extension offset must be in the first lane or start an upper lane."
) ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 11559, __PRETTY_FUNCTION__))
11559 "Extension offset must be in the first lane or start an upper lane.")(((Offset < NumEltsPerLane || Offset % NumEltsPerLane == 0
) && "Extension offset must be in the first lane or start an upper lane."
) ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 11559, __PRETTY_FUNCTION__))
;
11560
11561 // Check that an index is in same lane as the base offset.
11562 auto SafeOffset = [&](int Idx) {
11563 return OffsetLane == (Idx / NumEltsPerLane);
11564 };
11565
11566 // Shift along an input so that the offset base moves to the first element.
11567 auto ShuffleOffset = [&](SDValue V) {
11568 if (!Offset)
11569 return V;
11570
11571 SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
11572 for (int i = 0; i * Scale < NumElements; ++i) {
11573 int SrcIdx = i + Offset;
11574 ShMask[i] = SafeOffset(SrcIdx) ? SrcIdx : -1;
11575 }
11576 return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), ShMask);
11577 };
11578
11579 // Found a valid zext mask! Try various lowering strategies based on the
11580 // input type and available ISA extensions.
11581 if (Subtarget.hasSSE41()) {
11582 // Not worth offsetting 128-bit vectors if scale == 2, a pattern using
11583 // PUNPCK will catch this in a later shuffle match.
11584 if (Offset && Scale == 2 && VT.is128BitVector())
11585 return SDValue();
11586 MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
11587 NumElements / Scale);
11588 InputV = ShuffleOffset(InputV);
11589 InputV = getExtendInVec(/*Signed*/false, DL, ExtVT, InputV, DAG);
11590 return DAG.getBitcast(VT, InputV);
11591 }
11592
11593 assert(VT.is128BitVector() && "Only 128-bit vectors can be extended.")((VT.is128BitVector() && "Only 128-bit vectors can be extended."
) ? static_cast<void> (0) : __assert_fail ("VT.is128BitVector() && \"Only 128-bit vectors can be extended.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 11593, __PRETTY_FUNCTION__))
;
11594
11595 // For any extends we can cheat for larger element sizes and use shuffle
11596 // instructions that can fold with a load and/or copy.
11597 if (AnyExt && EltBits == 32) {
11598 int PSHUFDMask[4] = {Offset, -1, SafeOffset(Offset + 1) ? Offset + 1 : -1,
11599 -1};
11600 return DAG.getBitcast(
11601 VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
11602 DAG.getBitcast(MVT::v4i32, InputV),
11603 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
11604 }
11605 if (AnyExt && EltBits == 16 && Scale > 2) {
11606 int PSHUFDMask[4] = {Offset / 2, -1,
11607 SafeOffset(Offset + 1) ? (Offset + 1) / 2 : -1, -1};
11608 InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
11609 DAG.getBitcast(MVT::v4i32, InputV),
11610 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
11611 int PSHUFWMask[4] = {1, -1, -1, -1};
11612 unsigned OddEvenOp = (Offset & 1) ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
11613 return DAG.getBitcast(
11614 VT, DAG.getNode(OddEvenOp, DL, MVT::v8i16,
11615 DAG.getBitcast(MVT::v8i16, InputV),
11616 getV4X86ShuffleImm8ForMask(PSHUFWMask, DL, DAG)));
11617 }
11618
11619 // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
11620 // to 64-bits.
11621 if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget.hasSSE4A()) {
11622 assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!")((NumElements == (int)Mask.size() && "Unexpected shuffle mask size!"
) ? static_cast<void> (0) : __assert_fail ("NumElements == (int)Mask.size() && \"Unexpected shuffle mask size!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 11622, __PRETTY_FUNCTION__))
;
11623 assert(VT.is128BitVector() && "Unexpected vector width!")((VT.is128BitVector() && "Unexpected vector width!") ?
static_cast<void> (0) : __assert_fail ("VT.is128BitVector() && \"Unexpected vector width!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 11623, __PRETTY_FUNCTION__))
;
11624
11625 int LoIdx = Offset * EltBits;
11626 SDValue Lo = DAG.getBitcast(
11627 MVT::v2i64, DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
11628 DAG.getConstant(EltBits, DL, MVT::i8),
11629 DAG.getConstant(LoIdx, DL, MVT::i8)));
11630
11631 if (isUndefUpperHalf(Mask) || !SafeOffset(Offset + 1))
11632 return DAG.getBitcast(VT, Lo);
11633
11634 int HiIdx = (Offset + 1) * EltBits;
11635 SDValue Hi = DAG.getBitcast(
11636 MVT::v2i64, DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
11637 DAG.getConstant(EltBits, DL, MVT::i8),
11638 DAG.getConstant(HiIdx, DL, MVT::i8)));
11639 return DAG.getBitcast(VT,
11640 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
11641 }
11642
11643 // If this would require more than 2 unpack instructions to expand, use
11644 // pshufb when available. We can only use more than 2 unpack instructions
11645 // when zero extending i8 elements which also makes it easier to use pshufb.
11646 if (Scale > 4 && EltBits == 8 && Subtarget.hasSSSE3()) {
11647 assert(NumElements == 16 && "Unexpected byte vector width!")((NumElements == 16 && "Unexpected byte vector width!"
) ? static_cast<void> (0) : __assert_fail ("NumElements == 16 && \"Unexpected byte vector width!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 11647, __PRETTY_FUNCTION__))
;
11648 SDValue PSHUFBMask[16];
11649 for (int i = 0; i < 16; ++i) {
11650 int Idx = Offset + (i / Scale);
11651 PSHUFBMask[i] = DAG.getConstant(
11652 (i % Scale == 0 && SafeOffset(Idx)) ? Idx : 0x80, DL, MVT::i8);
11653 }
11654 InputV = DAG.getBitcast(MVT::v16i8, InputV);
11655 return DAG.getBitcast(
11656 VT, DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
11657 DAG.getBuildVector(MVT::v16i8, DL, PSHUFBMask)));
11658 }
11659
11660 // If we are extending from an offset, ensure we start on a boundary that
11661 // we can unpack from.
11662 int AlignToUnpack = Offset % (NumElements / Scale);
11663 if (AlignToUnpack) {
11664 SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
11665 for (int i = AlignToUnpack; i < NumElements; ++i)
11666 ShMask[i - AlignToUnpack] = i;
11667 InputV = DAG.getVectorShuffle(VT, DL, InputV, DAG.getUNDEF(VT), ShMask);
11668 Offset -= AlignToUnpack;
11669 }
11670
11671 // Otherwise emit a sequence of unpacks.
11672 do {
11673 unsigned UnpackLoHi = X86ISD::UNPCKL;
11674 if (Offset >= (NumElements / 2)) {
11675 UnpackLoHi = X86ISD::UNPCKH;
11676 Offset -= (NumElements / 2);
11677 }
11678
11679 MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
11680 SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
11681 : getZeroVector(InputVT, Subtarget, DAG, DL);
11682 InputV = DAG.getBitcast(InputVT, InputV);
11683 InputV = DAG.getNode(UnpackLoHi, DL, InputVT, InputV, Ext);
11684 Scale /= 2;
11685 EltBits *= 2;
11686 NumElements /= 2;
11687 } while (Scale > 1);
11688 return DAG.getBitcast(VT, InputV);
11689}
11690
11691/// Try to lower a vector shuffle as a zero extension on any microarch.
11692///
11693/// This routine will try to do everything in its power to cleverly lower
11694/// a shuffle which happens to match the pattern of a zero extend. It doesn't
11695/// check for the profitability of this lowering, it tries to aggressively
11696/// match this pattern. It will use all of the micro-architectural details it
11697/// can to emit an efficient lowering. It handles both blends with all-zero
11698/// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
11699/// masking out later).
11700///
11701/// The reason we have dedicated lowering for zext-style shuffles is that they
11702/// are both incredibly common and often quite performance sensitive.
11703static SDValue lowerShuffleAsZeroOrAnyExtend(
11704 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
11705 const APInt &Zeroable, const X86Subtarget &Subtarget,
11706 SelectionDAG &DAG) {
11707 int Bits = VT.getSizeInBits();
11708 int NumLanes = Bits / 128;
11709 int NumElements = VT.getVectorNumElements();
11710 int NumEltsPerLane = NumElements / NumLanes;
11711 assert(VT.getScalarSizeInBits() <= 32 &&((VT.getScalarSizeInBits() <= 32 && "Exceeds 32-bit integer zero extension limit"
) ? static_cast<void> (0) : __assert_fail ("VT.getScalarSizeInBits() <= 32 && \"Exceeds 32-bit integer zero extension limit\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 11712, __PRETTY_FUNCTION__))
11712 "Exceeds 32-bit integer zero extension limit")((VT.getScalarSizeInBits() <= 32 && "Exceeds 32-bit integer zero extension limit"
) ? static_cast<void> (0) : __assert_fail ("VT.getScalarSizeInBits() <= 32 && \"Exceeds 32-bit integer zero extension limit\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 11712, __PRETTY_FUNCTION__))
;
11713 assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size")(((int)Mask.size() == NumElements && "Unexpected shuffle mask size"
) ? static_cast<void> (0) : __assert_fail ("(int)Mask.size() == NumElements && \"Unexpected shuffle mask size\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 11713, __PRETTY_FUNCTION__))
;
11714
11715 // Define a helper function to check a particular ext-scale and lower to it if
11716 // valid.
11717 auto Lower = [&](int Scale) -> SDValue {
11718 SDValue InputV;
11719 bool AnyExt = true;
11720 int Offset = 0;
11721 int Matches = 0;
11722 for (int i = 0; i < NumElements; ++i) {
11723 int M = Mask[i];
11724 if (M < 0)
11725 continue; // Valid anywhere but doesn't tell us anything.
11726 if (i % Scale != 0) {
11727 // Each of the extended elements need to be zeroable.
11728 if (!Zeroable[i])
11729 return SDValue();
11730
11731 // We no longer are in the anyext case.
11732 AnyExt = false;
11733 continue;
11734 }
11735
11736 // Each of the base elements needs to be consecutive indices into the
11737 // same input vector.
11738 SDValue V = M < NumElements ? V1 : V2;
11739 M = M % NumElements;
11740 if (!InputV) {
11741 InputV = V;
11742 Offset = M - (i / Scale);
11743 } else if (InputV != V)
11744 return SDValue(); // Flip-flopping inputs.
11745
11746 // Offset must start in the lowest 128-bit lane or at the start of an
11747 // upper lane.
11748 // FIXME: Is it ever worth allowing a negative base offset?
11749 if (!((0 <= Offset && Offset < NumEltsPerLane) ||
11750 (Offset % NumEltsPerLane) == 0))
11751 return SDValue();
11752
11753 // If we are offsetting, all referenced entries must come from the same
11754 // lane.
11755 if (Offset && (Offset / NumEltsPerLane) != (M / NumEltsPerLane))
11756 return SDValue();
11757
11758 if ((M % NumElements) != (Offset + (i / Scale)))
11759 return SDValue(); // Non-consecutive strided elements.
11760 Matches++;
11761 }
11762
11763 // If we fail to find an input, we have a zero-shuffle which should always
11764 // have already been handled.
11765 // FIXME: Maybe handle this here in case during blending we end up with one?
11766 if (!InputV)
11767 return SDValue();
11768
11769 // If we are offsetting, don't extend if we only match a single input, we
11770 // can always do better by using a basic PSHUF or PUNPCK.
11771 if (Offset != 0 && Matches < 2)
11772 return SDValue();
11773
11774 return lowerShuffleAsSpecificZeroOrAnyExtend(DL, VT, Scale, Offset, AnyExt,
11775 InputV, Mask, Subtarget, DAG);
11776 };
11777
11778 // The widest scale possible for extending is to a 64-bit integer.
11779 assert(Bits % 64 == 0 &&((Bits % 64 == 0 && "The number of bits in a vector must be divisible by 64 on x86!"
) ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 11780, __PRETTY_FUNCTION__))
11780 "The number of bits in a vector must be divisible by 64 on x86!")((Bits % 64 == 0 && "The number of bits in a vector must be divisible by 64 on x86!"
) ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 11780, __PRETTY_FUNCTION__))
;
11781 int NumExtElements = Bits / 64;
11782
11783 // Each iteration, try extending the elements half as much, but into twice as
11784 // many elements.
11785 for (; NumExtElements < NumElements; NumExtElements *= 2) {
11786 assert(NumElements % NumExtElements == 0 &&((NumElements % NumExtElements == 0 && "The input vector size must be divisible by the extended size."
) ? static_cast<void> (0) : __assert_fail ("NumElements % NumExtElements == 0 && \"The input vector size must be divisible by the extended size.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 11787, __PRETTY_FUNCTION__))
11787 "The input vector size must be divisible by the extended size.")((NumElements % NumExtElements == 0 && "The input vector size must be divisible by the extended size."
) ? static_cast<void> (0) : __assert_fail ("NumElements % NumExtElements == 0 && \"The input vector size must be divisible by the extended size.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 11787, __PRETTY_FUNCTION__))
;
11788 if (SDValue V = Lower(NumElements / NumExtElements))
11789 return V;
11790 }
11791
11792 // General extends failed, but 128-bit vectors may be able to use MOVQ.
11793 if (Bits != 128)
11794 return SDValue();
11795
11796 // Returns one of the source operands if the shuffle can be reduced to a
11797 // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
11798 auto CanZExtLowHalf = [&]() {
11799 for (int i = NumElements / 2; i != NumElements; ++i)
11800 if (!Zeroable[i])
11801 return SDValue();
11802 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
11803 return V1;
11804 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
11805 return V2;
11806 return SDValue();
11807 };
11808
11809 if (SDValue V = CanZExtLowHalf()) {
11810 V = DAG.getBitcast(MVT::v2i64, V);
11811 V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
11812 return DAG.getBitcast(VT, V);
11813 }
11814
11815 // No viable ext lowering found.
11816 return SDValue();
11817}
11818
11819/// Try to get a scalar value for a specific element of a vector.
11820///
11821/// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
11822static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
11823 SelectionDAG &DAG) {
11824 MVT VT = V.getSimpleValueType();
11825 MVT EltVT = VT.getVectorElementType();
11826 V = peekThroughBitcasts(V);
11827
11828 // If the bitcasts shift the element size, we can't extract an equivalent
11829 // element from it.
11830 MVT NewVT = V.getSimpleValueType();
11831 if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
11832 return SDValue();
11833
11834 if (V.getOpcode() == ISD::BUILD_VECTOR ||
11835 (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
11836 // Ensure the scalar operand is the same size as the destination.
11837 // FIXME: Add support for scalar truncation where possible.
11838 SDValue S = V.getOperand(Idx);
11839 if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
11840 return DAG.getBitcast(EltVT, S);
11841 }
11842
11843 return SDValue();
11844}
11845
11846/// Helper to test for a load that can be folded with x86 shuffles.
11847///
11848/// This is particularly important because the set of instructions varies
11849/// significantly based on whether the operand is a load or not.
11850static bool isShuffleFoldableLoad(SDValue V) {
11851 V = peekThroughBitcasts(V);
11852 return ISD::isNON_EXTLoad(V.getNode());
11853}
11854
11855/// Try to lower insertion of a single element into a zero vector.
11856///
11857/// This is a common pattern that we have especially efficient patterns to lower
11858/// across all subtarget feature sets.
11859static SDValue lowerShuffleAsElementInsertion(
11860 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
11861 const APInt &Zeroable, const X86Subtarget &Subtarget,
11862 SelectionDAG &DAG) {
11863 MVT ExtVT = VT;
11864 MVT EltVT = VT.getVectorElementType();
11865
11866 int V2Index =
11867 find_if(Mask, [&Mask](int M) { return M >= (int)Mask.size(); }) -
11868 Mask.begin();
11869 bool IsV1Zeroable = true;
11870 for (int i = 0, Size = Mask.size(); i < Size; ++i)
11871 if (i != V2Index && !Zeroable[i]) {
11872 IsV1Zeroable = false;
11873 break;
11874 }
11875
11876 // Check for a single input from a SCALAR_TO_VECTOR node.
11877 // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
11878 // all the smarts here sunk into that routine. However, the current
11879 // lowering of BUILD_VECTOR makes that nearly impossible until the old
11880 // vector shuffle lowering is dead.
11881 SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
11882 DAG);
11883 if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
11884 // We need to zext the scalar if it is smaller than an i32.
11885 V2S = DAG.getBitcast(EltVT, V2S);
11886 if (EltVT == MVT::i8 || EltVT == MVT::i16) {
11887 // Using zext to expand a narrow element won't work for non-zero
11888 // insertions.
11889 if (!IsV1Zeroable)
11890 return SDValue();
11891
11892 // Zero-extend directly to i32.
11893 ExtVT = MVT::getVectorVT(MVT::i32, ExtVT.getSizeInBits() / 32);
11894 V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
11895 }
11896 V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
11897 } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
11898 EltVT == MVT::i16) {
11899 // Either not inserting from the low element of the input or the input
11900 // element size is too small to use VZEXT_MOVL to clear the high bits.
11901 return SDValue();
11902 }
11903
11904 if (!IsV1Zeroable) {
11905 // If V1 can't be treated as a zero vector we have fewer options to lower
11906 // this. We can't support integer vectors or non-zero targets cheaply, and
11907 // the V1 elements can't be permuted in any way.
11908 assert(VT == ExtVT && "Cannot change extended type when non-zeroable!")((VT == ExtVT && "Cannot change extended type when non-zeroable!"
) ? static_cast<void> (0) : __assert_fail ("VT == ExtVT && \"Cannot change extended type when non-zeroable!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 11908, __PRETTY_FUNCTION__))
;
11909 if (!VT.isFloatingPoint() || V2Index != 0)
11910 return SDValue();
11911 SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
11912 V1Mask[V2Index] = -1;
11913 if (!isNoopShuffleMask(V1Mask))
11914 return SDValue();
11915 if (!VT.is128BitVector())
11916 return SDValue();
11917
11918 // Otherwise, use MOVSD or MOVSS.
11919 assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&(((EltVT == MVT::f32 || EltVT == MVT::f64) && "Only two types of floating point element types to handle!"
) ? static_cast<void> (0) : __assert_fail ("(EltVT == MVT::f32 || EltVT == MVT::f64) && \"Only two types of floating point element types to handle!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 11920, __PRETTY_FUNCTION__))
11920 "Only two types of floating point element types to handle!")(((EltVT == MVT::f32 || EltVT == MVT::f64) && "Only two types of floating point element types to handle!"
) ? static_cast<void> (0) : __assert_fail ("(EltVT == MVT::f32 || EltVT == MVT::f64) && \"Only two types of floating point element types to handle!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 11920, __PRETTY_FUNCTION__))
;
11921 return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
11922 ExtVT, V1, V2);
11923 }
11924
11925 // This lowering only works for the low element with floating point vectors.
11926 if (VT.isFloatingPoint() && V2Index != 0)
11927 return SDValue();
11928
11929 V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
11930 if (ExtVT != VT)
11931 V2 = DAG.getBitcast(VT, V2);
11932
11933 if (V2Index != 0) {
11934 // If we have 4 or fewer lanes we can cheaply shuffle the element into
11935 // the desired position. Otherwise it is more efficient to do a vector
11936 // shift left. We know that we can do a vector shift left because all
11937 // the inputs are zero.
11938 if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
11939 SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
11940 V2Shuffle[V2Index] = 0;
11941 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
11942 } else {
11943 V2 = DAG.getBitcast(MVT::v16i8, V2);
11944 V2 = DAG.getNode(
11945 X86ISD::VSHLDQ, DL, MVT::v16i8, V2,
11946 DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL, MVT::i8));
11947 V2 = DAG.getBitcast(VT, V2);
11948 }
11949 }
11950 return V2;
11951}
11952
11953/// Try to lower broadcast of a single - truncated - integer element,
11954/// coming from a scalar_to_vector/build_vector node \p V0 with larger elements.
11955///
11956/// This assumes we have AVX2.
11957static SDValue lowerShuffleAsTruncBroadcast(const SDLoc &DL, MVT VT, SDValue V0,
11958 int BroadcastIdx,
11959 const X86Subtarget &Subtarget,
11960 SelectionDAG &DAG) {
11961 assert(Subtarget.hasAVX2() &&((Subtarget.hasAVX2() && "We can only lower integer broadcasts with AVX2!"
) ? static_cast<void> (0) : __assert_fail ("Subtarget.hasAVX2() && \"We can only lower integer broadcasts with AVX2!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 11962, __PRETTY_FUNCTION__))
11962 "We can only lower integer broadcasts with AVX2!")((Subtarget.hasAVX2() && "We can only lower integer broadcasts with AVX2!"
) ? static_cast<void> (0) : __assert_fail ("Subtarget.hasAVX2() && \"We can only lower integer broadcasts with AVX2!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 11962, __PRETTY_FUNCTION__))
;
11963
11964 EVT EltVT = VT.getVectorElementType();
11965 EVT V0VT = V0.getValueType();
11966
11967 assert(VT.isInteger() && "Unexpected non-integer trunc broadcast!")((VT.isInteger() && "Unexpected non-integer trunc broadcast!"
) ? static_cast<void> (0) : __assert_fail ("VT.isInteger() && \"Unexpected non-integer trunc broadcast!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 11967, __PRETTY_FUNCTION__))
;
11968 assert(V0VT.isVector() && "Unexpected non-vector vector-sized value!")((V0VT.isVector() && "Unexpected non-vector vector-sized value!"
) ? static_cast<void> (0) : __assert_fail ("V0VT.isVector() && \"Unexpected non-vector vector-sized value!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 11968, __PRETTY_FUNCTION__))
;
11969
11970 EVT V0EltVT = V0VT.getVectorElementType();
11971 if (!V0EltVT.isInteger())
11972 return SDValue();
11973
11974 const unsigned EltSize = EltVT.getSizeInBits();
11975 const unsigned V0EltSize = V0EltVT.getSizeInBits();
11976
11977 // This is only a truncation if the original element type is larger.
11978 if (V0EltSize <= EltSize)
11979 return SDValue();
11980
11981 assert(((V0EltSize % EltSize) == 0) &&((((V0EltSize % EltSize) == 0) && "Scalar type sizes must all be powers of 2 on x86!"
) ? static_cast<void> (0) : __assert_fail ("((V0EltSize % EltSize) == 0) && \"Scalar type sizes must all be powers of 2 on x86!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 11982, __PRETTY_FUNCTION__))
11982 "Scalar type sizes must all be powers of 2 on x86!")((((V0EltSize % EltSize) == 0) && "Scalar type sizes must all be powers of 2 on x86!"
) ? static_cast<void> (0) : __assert_fail ("((V0EltSize % EltSize) == 0) && \"Scalar type sizes must all be powers of 2 on x86!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 11982, __PRETTY_FUNCTION__))
;
11983
11984 const unsigned V0Opc = V0.getOpcode();
11985 const unsigned Scale = V0EltSize / EltSize;
11986 const unsigned V0BroadcastIdx = BroadcastIdx / Scale;
11987
11988 if ((V0Opc != ISD::SCALAR_TO_VECTOR || V0BroadcastIdx != 0) &&
11989 V0Opc != ISD::BUILD_VECTOR)
11990 return SDValue();
11991
11992 SDValue Scalar = V0.getOperand(V0BroadcastIdx);
11993
11994 // If we're extracting non-least-significant bits, shift so we can truncate.
11995 // Hopefully, we can fold away the trunc/srl/load into the broadcast.
11996 // Even if we can't (and !isShuffleFoldableLoad(Scalar)), prefer
11997 // vpbroadcast+vmovd+shr to vpshufb(m)+vmovd.
11998 if (const int OffsetIdx = BroadcastIdx % Scale)
11999 Scalar = DAG.getNode(ISD::SRL, DL, Scalar.getValueType(), Scalar,
12000 DAG.getConstant(OffsetIdx * EltSize, DL, MVT::i8));
12001
12002 return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
12003 DAG.getNode(ISD::TRUNCATE, DL, EltVT, Scalar));
12004}
12005
12006/// Test whether this can be lowered with a single SHUFPS instruction.
12007///
12008/// This is used to disable more specialized lowerings when the shufps lowering
12009/// will happen to be efficient.
12010static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
12011 // This routine only handles 128-bit shufps.
12012 assert(Mask.size() == 4 && "Unsupported mask size!")((Mask.size() == 4 && "Unsupported mask size!") ? static_cast
<void> (0) : __assert_fail ("Mask.size() == 4 && \"Unsupported mask size!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 12012, __PRETTY_FUNCTION__))
;
12013 assert(Mask[0] >= -1 && Mask[0] < 8 && "Out of bound mask element!")((Mask[0] >= -1 && Mask[0] < 8 && "Out of bound mask element!"
) ? static_cast<void> (0) : __assert_fail ("Mask[0] >= -1 && Mask[0] < 8 && \"Out of bound mask element!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 12013, __PRETTY_FUNCTION__))
;
12014 assert(Mask[1] >= -1 && Mask[1] < 8 && "Out of bound mask element!")((Mask[1] >= -1 && Mask[1] < 8 && "Out of bound mask element!"
) ? static_cast<void> (0) : __assert_fail ("Mask[1] >= -1 && Mask[1] < 8 && \"Out of bound mask element!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 12014, __PRETTY_FUNCTION__))
;
12015 assert(Mask[2] >= -1 && Mask[2] < 8 && "Out of bound mask element!")((Mask[2] >= -1 && Mask[2] < 8 && "Out of bound mask element!"
) ? static_cast<void> (0) : __assert_fail ("Mask[2] >= -1 && Mask[2] < 8 && \"Out of bound mask element!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 12015, __PRETTY_FUNCTION__))
;
12016 assert(Mask[3] >= -1 && Mask[3] < 8 && "Out of bound mask element!")((Mask[3] >= -1 && Mask[3] < 8 && "Out of bound mask element!"
) ? static_cast<void> (0) : __assert_fail ("Mask[3] >= -1 && Mask[3] < 8 && \"Out of bound mask element!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 12016, __PRETTY_FUNCTION__))
;
12017
12018 // To lower with a single SHUFPS we need to have the low half and high half
12019 // each requiring a single input.
12020 if (Mask[0] >= 0 && Mask[1] >= 0 && (Mask[0] < 4) != (Mask[1] < 4))
12021 return false;
12022 if (Mask[2] >= 0 && Mask[3] >= 0 && (Mask[2] < 4) != (Mask[3] < 4))
12023 return false;
12024
12025 return true;
12026}
12027
12028/// If we are extracting two 128-bit halves of a vector and shuffling the
12029/// result, match that to a 256-bit AVX2 vperm* instruction to avoid a
12030/// multi-shuffle lowering.
12031static SDValue lowerShuffleOfExtractsAsVperm(const SDLoc &DL, SDValue N0,
12032 SDValue N1, ArrayRef<int> Mask,
12033 SelectionDAG &DAG) {
12034 EVT VT = N0.getValueType();
12035 assert((VT.is128BitVector() &&(((VT.is128BitVector() && (VT.getScalarSizeInBits() ==
32 || VT.getScalarSizeInBits() == 64)) && "VPERM* family of shuffles requires 32-bit or 64-bit elements"
) ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 12037, __PRETTY_FUNCTION__))
12036 (VT.getScalarSizeInBits() == 32 || VT.getScalarSizeInBits() == 64)) &&(((VT.is128BitVector() && (VT.getScalarSizeInBits() ==
32 || VT.getScalarSizeInBits() == 64)) && "VPERM* family of shuffles requires 32-bit or 64-bit elements"
) ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 12037, __PRETTY_FUNCTION__))
12037 "VPERM* family of shuffles requires 32-bit or 64-bit elements")(((VT.is128BitVector() && (VT.getScalarSizeInBits() ==
32 || VT.getScalarSizeInBits() == 64)) && "VPERM* family of shuffles requires 32-bit or 64-bit elements"
) ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 12037, __PRETTY_FUNCTION__))
;
12038
12039 // Check that both sources are extracts of the same source vector.
12040 if (!N0.hasOneUse() || !N1.hasOneUse() ||
12041 N0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
12042 N1.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
12043 N0.getOperand(0) != N1.getOperand(0))
12044 return SDValue();
12045
12046 SDValue WideVec = N0.getOperand(0);
12047 EVT WideVT = WideVec.getValueType();
12048 if (!WideVT.is256BitVector() || !isa<ConstantSDNode>(N0.getOperand(1)) ||
12049 !isa<ConstantSDNode>(N1.getOperand(1)))
12050 return SDValue();
12051
12052 // Match extracts of each half of the wide source vector. Commute the shuffle
12053 // if the extract of the low half is N1.
12054 unsigned NumElts = VT.getVectorNumElements();
12055 SmallVector<int, 4> NewMask(Mask.begin(), Mask.end());
12056 const APInt &ExtIndex0 = N0.getConstantOperandAPInt(1);
12057 const APInt &ExtIndex1 = N1.getConstantOperandAPInt(1);
12058 if (ExtIndex1 == 0 && ExtIndex0 == NumElts)
12059 ShuffleVectorSDNode::commuteMask(NewMask);
12060 else if (ExtIndex0 != 0 || ExtIndex1 != NumElts)
12061 return SDValue();
12062
12063 // Final bailout: if the mask is simple, we are better off using an extract
12064 // and a simple narrow shuffle. Prefer extract+unpack(h/l)ps to vpermps
12065 // because that avoids a constant load from memory.
12066 if (NumElts == 4 &&
12067 (isSingleSHUFPSMask(NewMask) || is128BitUnpackShuffleMask(NewMask)))
12068 return SDValue();
12069
12070 // Extend the shuffle mask with undef elements.
12071 NewMask.append(NumElts, -1);
12072
12073 // shuf (extract X, 0), (extract X, 4), M --> extract (shuf X, undef, M'), 0
12074 SDValue Shuf = DAG.getVectorShuffle(WideVT, DL, WideVec, DAG.getUNDEF(WideVT),
12075 NewMask);
12076 // This is free: ymm -> xmm.
12077 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuf,
12078 DAG.getIntPtrConstant(0, DL));
12079}
12080
12081/// Try to lower broadcast of a single element.
12082///
12083/// For convenience, this code also bundles all of the subtarget feature set
12084/// filtering. While a little annoying to re-dispatch on type here, there isn't
12085/// a convenient way to factor it out.
12086static SDValue lowerShuffleAsBroadcast(const SDLoc &DL, MVT VT, SDValue V1,
12087 SDValue V2, ArrayRef<int> Mask,
12088 const X86Subtarget &Subtarget,
12089 SelectionDAG &DAG) {
12090 if (!((Subtarget.hasSSE3() && VT == MVT::v2f64) ||
12091 (Subtarget.hasAVX() && VT.isFloatingPoint()) ||
12092 (Subtarget.hasAVX2() && VT.isInteger())))
12093 return SDValue();
12094
12095 // With MOVDDUP (v2f64) we can broadcast from a register or a load, otherwise
12096 // we can only broadcast from a register with AVX2.
12097 unsigned NumElts = Mask.size();
12098 unsigned NumEltBits = VT.getScalarSizeInBits();
12099 unsigned Opcode = (VT == MVT::v2f64 && !Subtarget.hasAVX2())
12100 ? X86ISD::MOVDDUP
12101 : X86ISD::VBROADCAST;
12102 bool BroadcastFromReg = (Opcode == X86ISD::MOVDDUP) || Subtarget.hasAVX2();
12103
12104 // Check that the mask is a broadcast.
12105 int BroadcastIdx = -1;
12106 for (int i = 0; i != (int)NumElts; ++i) {
12107 SmallVector<int, 8> BroadcastMask(NumElts, i);
12108 if (isShuffleEquivalent(V1, V2, Mask, BroadcastMask)) {
12109 BroadcastIdx = i;
12110 break;
12111 }
12112 }
12113
12114 if (BroadcastIdx < 0)
12115 return SDValue();
12116 assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "((BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
"a sorted mask where the broadcast " "comes from V1.") ? static_cast
<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 12118, __PRETTY_FUNCTION__))
12117 "a sorted mask where the broadcast "((BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
"a sorted mask where the broadcast " "comes from V1.") ? static_cast
<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 12118, __PRETTY_FUNCTION__))
12118 "comes from V1.")((BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
"a sorted mask where the broadcast " "comes from V1.") ? static_cast
<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 12118, __PRETTY_FUNCTION__))
;
12119
12120 // Go up the chain of (vector) values to find a scalar load that we can
12121 // combine with the broadcast.
12122 int BitOffset = BroadcastIdx * NumEltBits;
12123 SDValue V = V1;
12124 for (;;) {
12125 switch (V.getOpcode()) {
12126 case ISD::BITCAST: {
12127 V = V.getOperand(0);
12128 continue;
12129 }
12130 case ISD::CONCAT_VECTORS: {
12131 int OpBitWidth = V.getOperand(0).getValueSizeInBits();
12132 int OpIdx = BitOffset / OpBitWidth;
12133 V = V.getOperand(OpIdx);
12134 BitOffset %= OpBitWidth;
12135 continue;
12136 }
12137 case ISD::INSERT_SUBVECTOR: {
12138 SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
12139 auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
12140 if (!ConstantIdx)
12141 break;
12142
12143 int EltBitWidth = VOuter.getScalarValueSizeInBits();
12144 int Idx = (int)ConstantIdx->getZExtValue();
12145 int NumSubElts = (int)VInner.getSimpleValueType().getVectorNumElements();
12146 int BeginOffset = Idx * EltBitWidth;
12147 int EndOffset = BeginOffset + NumSubElts * EltBitWidth;
12148 if (BeginOffset <= BitOffset && BitOffset < EndOffset) {
12149 BitOffset -= BeginOffset;
12150 V = VInner;
12151 } else {
12152 V = VOuter;
12153 }
12154 continue;
12155 }
12156 }
12157 break;
12158 }
12159 assert((BitOffset % NumEltBits) == 0 && "Illegal bit-offset")(((BitOffset % NumEltBits) == 0 && "Illegal bit-offset"
) ? static_cast<void> (0) : __assert_fail ("(BitOffset % NumEltBits) == 0 && \"Illegal bit-offset\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 12159, __PRETTY_FUNCTION__))
;
12160 BroadcastIdx = BitOffset / NumEltBits;
12161
12162 // Do we need to bitcast the source to retrieve the original broadcast index?
12163 bool BitCastSrc = V.getScalarValueSizeInBits() != NumEltBits;
12164
12165 // Check if this is a broadcast of a scalar. We special case lowering
12166 // for scalars so that we can more effectively fold with loads.
12167 // If the original value has a larger element type than the shuffle, the
12168 // broadcast element is in essence truncated. Make that explicit to ease
12169 // folding.
12170 if (BitCastSrc && VT.isInteger())
12171 if (SDValue TruncBroadcast = lowerShuffleAsTruncBroadcast(
12172 DL, VT, V, BroadcastIdx, Subtarget, DAG))
12173 return TruncBroadcast;
12174
12175 MVT BroadcastVT = VT;
12176
12177 // Also check the simpler case, where we can directly reuse the scalar.
12178 if (!BitCastSrc &&
12179 ((V.getOpcode() == ISD::BUILD_VECTOR && V.hasOneUse()) ||
12180 (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0))) {
12181 V = V.getOperand(BroadcastIdx);
12182
12183 // If we can't broadcast from a register, check that the input is a load.
12184 if (!BroadcastFromReg && !isShuffleFoldableLoad(V))
12185 return SDValue();
12186 } else if (MayFoldLoad(V) && !cast<LoadSDNode>(V)->isVolatile()) {
12187 // 32-bit targets need to load i64 as a f64 and then bitcast the result.
12188 if (!Subtarget.is64Bit() && VT.getScalarType() == MVT::i64) {
12189 BroadcastVT = MVT::getVectorVT(MVT::f64, VT.getVectorNumElements());
12190 Opcode = (BroadcastVT.is128BitVector() && !Subtarget.hasAVX2())
12191 ? X86ISD::MOVDDUP
12192 : Opcode;
12193 }
12194
12195 // If we are broadcasting a load that is only used by the shuffle
12196 // then we can reduce the vector load to the broadcasted scalar load.
12197 LoadSDNode *Ld = cast<LoadSDNode>(V);
12198 SDValue BaseAddr = Ld->getOperand(1);
12199 EVT SVT = BroadcastVT.getScalarType();
12200 unsigned Offset = BroadcastIdx * SVT.getStoreSize();
12201 assert((int)(Offset * 8) == BitOffset && "Unexpected bit-offset")(((int)(Offset * 8) == BitOffset && "Unexpected bit-offset"
) ? static_cast<void> (0) : __assert_fail ("(int)(Offset * 8) == BitOffset && \"Unexpected bit-offset\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 12201, __PRETTY_FUNCTION__))
;
12202 SDValue NewAddr = DAG.getMemBasePlusOffset(BaseAddr, Offset, DL);
12203 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
12204 DAG.getMachineFunction().getMachineMemOperand(
12205 Ld->getMemOperand(), Offset, SVT.getStoreSize()));
12206 DAG.makeEquivalentMemoryOrdering(Ld, V);
12207 } else if (!BroadcastFromReg) {
12208 // We can't broadcast from a vector register.
12209 return SDValue();
12210 } else if (BitOffset != 0) {
12211 // We can only broadcast from the zero-element of a vector register,
12212 // but it can be advantageous to broadcast from the zero-element of a
12213 // subvector.
12214 if (!VT.is256BitVector() && !VT.is512BitVector())
12215 return SDValue();
12216
12217 // VPERMQ/VPERMPD can perform the cross-lane shuffle directly.
12218 if (VT == MVT::v4f64 || VT == MVT::v4i64)
12219 return SDValue();
12220
12221 // Only broadcast the zero-element of a 128-bit subvector.
12222 if ((BitOffset % 128) != 0)
12223 return SDValue();
12224
12225 assert((BitOffset % V.getScalarValueSizeInBits()) == 0 &&(((BitOffset % V.getScalarValueSizeInBits()) == 0 && "Unexpected bit-offset"
) ? static_cast<void> (0) : __assert_fail ("(BitOffset % V.getScalarValueSizeInBits()) == 0 && \"Unexpected bit-offset\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 12226, __PRETTY_FUNCTION__))
12226 "Unexpected bit-offset")(((BitOffset % V.getScalarValueSizeInBits()) == 0 && "Unexpected bit-offset"
) ? static_cast<void> (0) : __assert_fail ("(BitOffset % V.getScalarValueSizeInBits()) == 0 && \"Unexpected bit-offset\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 12226, __PRETTY_FUNCTION__))
;
12227 assert((V.getValueSizeInBits() == 256 || V.getValueSizeInBits() == 512) &&(((V.getValueSizeInBits() == 256 || V.getValueSizeInBits() ==
512) && "Unexpected vector size") ? static_cast<void
> (0) : __assert_fail ("(V.getValueSizeInBits() == 256 || V.getValueSizeInBits() == 512) && \"Unexpected vector size\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 12228, __PRETTY_FUNCTION__))
12228 "Unexpected vector size")(((V.getValueSizeInBits() == 256 || V.getValueSizeInBits() ==
512) && "Unexpected vector size") ? static_cast<void
> (0) : __assert_fail ("(V.getValueSizeInBits() == 256 || V.getValueSizeInBits() == 512) && \"Unexpected vector size\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 12228, __PRETTY_FUNCTION__))
;
12229 unsigned ExtractIdx = BitOffset / V.getScalarValueSizeInBits();
12230 V = extract128BitVector(V, ExtractIdx, DAG, DL);
12231 }
12232
12233 if (Opcode == X86ISD::MOVDDUP && !V.getValueType().isVector())
12234 V = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
12235 DAG.getBitcast(MVT::f64, V));
12236
12237 // Bitcast back to the same scalar type as BroadcastVT.
12238 if (V.getValueType().getScalarType() != BroadcastVT.getScalarType()) {
12239 assert(NumEltBits == BroadcastVT.getScalarSizeInBits() &&((NumEltBits == BroadcastVT.getScalarSizeInBits() && "Unexpected vector element size"
) ? static_cast<void> (0) : __assert_fail ("NumEltBits == BroadcastVT.getScalarSizeInBits() && \"Unexpected vector element size\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 12240, __PRETTY_FUNCTION__))
12240 "Unexpected vector element size")((NumEltBits == BroadcastVT.getScalarSizeInBits() && "Unexpected vector element size"
) ? static_cast<void> (0) : __assert_fail ("NumEltBits == BroadcastVT.getScalarSizeInBits() && \"Unexpected vector element size\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 12240, __PRETTY_FUNCTION__))
;
12241 MVT ExtVT;
12242 if (V.getValueType().isVector()) {
12243 unsigned NumSrcElts = V.getValueSizeInBits() / NumEltBits;
12244 ExtVT = MVT::getVectorVT(BroadcastVT.getScalarType(), NumSrcElts);
12245 } else {
12246 ExtVT = BroadcastVT.getScalarType();
12247 }
12248 V = DAG.getBitcast(ExtVT, V);
12249 }
12250
12251 // 32-bit targets need to load i64 as a f64 and then bitcast the result.
12252 if (!Subtarget.is64Bit() && V.getValueType() == MVT::i64) {
12253 V = DAG.getBitcast(MVT::f64, V);
12254 unsigned NumBroadcastElts = BroadcastVT.getVectorNumElements();
12255 BroadcastVT = MVT::getVectorVT(MVT::f64, NumBroadcastElts);
12256 }
12257
12258 // We only support broadcasting from 128-bit vectors to minimize the
12259 // number of patterns we need to deal with in isel. So extract down to
12260 // 128-bits, removing as many bitcasts as possible.
12261 if (V.getValueSizeInBits() > 128) {
12262 MVT ExtVT = V.getSimpleValueType().getScalarType();
12263 ExtVT = MVT::getVectorVT(ExtVT, 128 / ExtVT.getScalarSizeInBits());
12264 V = extract128BitVector(peekThroughBitcasts(V), 0, DAG, DL);
12265 V = DAG.getBitcast(ExtVT, V);
12266 }
12267
12268 return DAG.getBitcast(VT, DAG.getNode(Opcode, DL, BroadcastVT, V));
12269}
12270
12271// Check for whether we can use INSERTPS to perform the shuffle. We only use
12272// INSERTPS when the V1 elements are already in the correct locations
12273// because otherwise we can just always use two SHUFPS instructions which
12274// are much smaller to encode than a SHUFPS and an INSERTPS. We can also
12275// perform INSERTPS if a single V1 element is out of place and all V2
12276// elements are zeroable.
12277static bool matchShuffleAsInsertPS(SDValue &V1, SDValue &V2,
12278 unsigned &InsertPSMask,
12279 const APInt &Zeroable,
12280 ArrayRef<int> Mask, SelectionDAG &DAG) {
12281 assert(V1.getSimpleValueType().is128BitVector() && "Bad operand type!")((V1.getSimpleValueType().is128BitVector() && "Bad operand type!"
) ? static_cast<void> (0) : __assert_fail ("V1.getSimpleValueType().is128BitVector() && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 12281, __PRETTY_FUNCTION__))
;
12282 assert(V2.getSimpleValueType().is128BitVector() && "Bad operand type!")((V2.getSimpleValueType().is128BitVector() && "Bad operand type!"
) ? static_cast<void> (0) : __assert_fail ("V2.getSimpleValueType().is128BitVector() && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 12282, __PRETTY_FUNCTION__))
;
12283 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!")((Mask.size() == 4 && "Unexpected mask size for v4 shuffle!"
) ? static_cast<void> (0) : __assert_fail ("Mask.size() == 4 && \"Unexpected mask size for v4 shuffle!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 12283, __PRETTY_FUNCTION__))
;
12284
12285 // Attempt to match INSERTPS with one element from VA or VB being
12286 // inserted into VA (or undef). If successful, V1, V2 and InsertPSMask
12287 // are updated.
12288 auto matchAsInsertPS = [&](SDValue VA, SDValue VB,
12289 ArrayRef<int> CandidateMask) {
12290 unsigned ZMask = 0;
12291 int VADstIndex = -1;
12292 int VBDstIndex = -1;
12293 bool VAUsedInPlace = false;
12294
12295 for (int i = 0; i < 4; ++i) {
12296 // Synthesize a zero mask from the zeroable elements (includes undefs).
12297 if (Zeroable[i]) {
12298 ZMask |= 1 << i;
12299 continue;
12300 }
12301
12302 // Flag if we use any VA inputs in place.
12303 if (i == CandidateMask[i]) {
12304 VAUsedInPlace = true;
12305 continue;
12306 }
12307
12308 // We can only insert a single non-zeroable element.
12309 if (VADstIndex >= 0 || VBDstIndex >= 0)
12310 return false;
12311
12312 if (CandidateMask[i] < 4) {
12313 // VA input out of place for insertion.
12314 VADstIndex = i;
12315 } else {
12316 // VB input for insertion.
12317 VBDstIndex = i;
12318 }
12319 }
12320
12321 // Don't bother if we have no (non-zeroable) element for insertion.
12322 if (VADstIndex < 0 && VBDstIndex < 0)
12323 return false;
12324
12325 // Determine element insertion src/dst indices. The src index is from the
12326 // start of the inserted vector, not the start of the concatenated vector.
12327 unsigned VBSrcIndex = 0;
12328 if (VADstIndex >= 0) {
12329 // If we have a VA input out of place, we use VA as the V2 element
12330 // insertion and don't use the original V2 at all.
12331 VBSrcIndex = CandidateMask[VADstIndex];
12332 VBDstIndex = VADstIndex;
12333 VB = VA;
12334 } else {
12335 VBSrcIndex = CandidateMask[VBDstIndex] - 4;
12336 }
12337
12338 // If no V1 inputs are used in place, then the result is created only from
12339 // the zero mask and the V2 insertion - so remove V1 dependency.
12340 if (!VAUsedInPlace)
12341 VA = DAG.getUNDEF(MVT::v4f32);
12342
12343 // Update V1, V2 and InsertPSMask accordingly.
12344 V1 = VA;
12345 V2 = VB;
12346
12347 // Insert the V2 element into the desired position.
12348 InsertPSMask = VBSrcIndex << 6 | VBDstIndex << 4 | ZMask;
12349 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!")(((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!"
) ? static_cast<void> (0) : __assert_fail ("(InsertPSMask & ~0xFFu) == 0 && \"Invalid mask!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 12349, __PRETTY_FUNCTION__))
;
12350 return true;
12351 };
12352
12353 if (matchAsInsertPS(V1, V2, Mask))
12354 return true;
12355
12356 // Commute and try again.
12357 SmallVector<int, 4> CommutedMask(Mask.begin(), Mask.end());
12358 ShuffleVectorSDNode::commuteMask(CommutedMask);
12359 if (matchAsInsertPS(V2, V1, CommutedMask))
12360 return true;
12361
12362 return false;
12363}
12364
12365static SDValue lowerShuffleAsInsertPS(const SDLoc &DL, SDValue V1, SDValue V2,
12366 ArrayRef<int> Mask, const APInt &Zeroable,
12367 SelectionDAG &DAG) {
12368 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!")((V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!"
) ? static_cast<void> (0) : __assert_fail ("V1.getSimpleValueType() == MVT::v4f32 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 12368, __PRETTY_FUNCTION__))
;
12369 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!")((V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!"
) ? static_cast<void> (0) : __assert_fail ("V2.getSimpleValueType() == MVT::v4f32 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 12369, __PRETTY_FUNCTION__))
;
12370
12371 // Attempt to match the insertps pattern.
12372 unsigned InsertPSMask;
12373 if (!matchShuffleAsInsertPS(V1, V2, InsertPSMask, Zeroable, Mask, DAG))
12374 return SDValue();
12375
12376 // Insert the V2 element into the desired position.
12377 return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
12378 DAG.getConstant(InsertPSMask, DL, MVT::i8));
12379}
12380
12381/// Try to lower a shuffle as a permute of the inputs followed by an
12382/// UNPCK instruction.
12383///
12384/// This specifically targets cases where we end up with alternating between
12385/// the two inputs, and so can permute them into something that feeds a single
12386/// UNPCK instruction. Note that this routine only targets integer vectors
12387/// because for floating point vectors we have a generalized SHUFPS lowering
12388/// strategy that handles everything that doesn't *exactly* match an unpack,
12389/// making this clever lowering unnecessary.
12390static SDValue lowerShuffleAsPermuteAndUnpack(
12391 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
12392 const X86Subtarget &Subtarget, SelectionDAG &DAG) {
12393 assert(!VT.isFloatingPoint() &&((!VT.isFloatingPoint() && "This routine only supports integer vectors."
) ? static_cast<void> (0) : __assert_fail ("!VT.isFloatingPoint() && \"This routine only supports integer vectors.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 12394, __PRETTY_FUNCTION__))
12394 "This routine only supports integer vectors.")((!VT.isFloatingPoint() && "This routine only supports integer vectors."
) ? static_cast<void> (0) : __assert_fail ("!VT.isFloatingPoint() && \"This routine only supports integer vectors.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 12394, __PRETTY_FUNCTION__))
;
12395 assert(VT.is128BitVector() &&((VT.is128BitVector() && "This routine only works on 128-bit vectors."
) ? static_cast<void> (0) : __assert_fail ("VT.is128BitVector() && \"This routine only works on 128-bit vectors.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 12396, __PRETTY_FUNCTION__))
12396 "This routine only works on 128-bit vectors.")((VT.is128BitVector() && "This routine only works on 128-bit vectors."
) ? static_cast<void> (0) : __assert_fail ("VT.is128BitVector() && \"This routine only works on 128-bit vectors.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 12396, __PRETTY_FUNCTION__))
;
12397 assert(!V2.isUndef() &&((!V2.isUndef() && "This routine should only be used when blending two inputs."
) ? static_cast<void> (0) : __assert_fail ("!V2.isUndef() && \"This routine should only be used when blending two inputs.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 12398, __PRETTY_FUNCTION__))
12398 "This routine should only be used when blending two inputs.")((!V2.isUndef() && "This routine should only be used when blending two inputs."
) ? static_cast<void> (0) : __assert_fail ("!V2.isUndef() && \"This routine should only be used when blending two inputs.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 12398, __PRETTY_FUNCTION__))
;
12399 assert(Mask.size() >= 2 && "Single element masks are invalid.")((Mask.size() >= 2 && "Single element masks are invalid."
) ? static_cast<void> (0) : __assert_fail ("Mask.size() >= 2 && \"Single element masks are invalid.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 12399, __PRETTY_FUNCTION__))
;
12400
12401 int Size = Mask.size();
12402
12403 int NumLoInputs =
12404 count_if(Mask, [Size](int M) { return M >= 0 && M % Size < Size / 2; });
12405 int NumHiInputs =
12406 count_if(Mask, [Size](int M) { return M % Size >= Size / 2; });
12407
12408 bool UnpackLo = NumLoInputs >= NumHiInputs;
12409
12410 auto TryUnpack = [&](int ScalarSize, int Scale) {
12411 SmallVector<int, 16> V1Mask((unsigned)Size, -1);
12412 SmallVector<int, 16> V2Mask((unsigned)Size, -1);
12413
12414 for (int i = 0; i < Size; ++i) {
12415 if (Mask[i] < 0)
12416 continue;
12417
12418 // Each element of the unpack contains Scale elements from this mask.
12419 int UnpackIdx = i / Scale;
12420
12421 // We only handle the case where V1 feeds the first slots of the unpack.
12422 // We rely on canonicalization to ensure this is the case.
12423 if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
12424 return SDValue();
12425
12426 // Setup the mask for this input. The indexing is tricky as we have to
12427 // handle the unpack stride.
12428 SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
12429 VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
12430 Mask[i] % Size;
12431 }
12432
12433 // If we will have to shuffle both inputs to use the unpack, check whether
12434 // we can just unpack first and shuffle the result. If so, skip this unpack.
12435 if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
12436 !isNoopShuffleMask(V2Mask))
12437 return SDValue();
12438
12439 // Shuffle the inputs into place.
12440 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
12441 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
12442
12443 // Cast the inputs to the type we will use to unpack them.
12444 MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), Size / Scale);
12445 V1 = DAG.getBitcast(UnpackVT, V1);
12446 V2 = DAG.getBitcast(UnpackVT, V2);
12447
12448 // Unpack the inputs and cast the result back to the desired type.
12449 return DAG.getBitcast(
12450 VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
12451 UnpackVT, V1, V2));
12452 };
12453
12454 // We try each unpack from the largest to the smallest to try and find one
12455 // that fits this mask.
12456 int OrigScalarSize = VT.getScalarSizeInBits();
12457 for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2)
12458 if (SDValue Unpack = TryUnpack(ScalarSize, ScalarSize / OrigScalarSize))
12459 return Unpack;
12460
12461 // If we're shuffling with a zero vector then we're better off not doing
12462 // VECTOR_SHUFFLE(UNPCK()) as we lose track of those zero elements.
12463 if (ISD::isBuildVectorAllZeros(V1.getNode()) ||
12464 ISD::isBuildVectorAllZeros(V2.getNode()))
12465 return SDValue();
12466
12467 // If none of the unpack-rooted lowerings worked (or were profitable) try an
12468 // initial unpack.
12469 if (NumLoInputs == 0 || NumHiInputs == 0) {
12470 assert((NumLoInputs > 0 || NumHiInputs > 0) &&(((NumLoInputs > 0 || NumHiInputs > 0) && "We have to have *some* inputs!"
) ? static_cast<void> (0) : __assert_fail ("(NumLoInputs > 0 || NumHiInputs > 0) && \"We have to have *some* inputs!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 12471, __PRETTY_FUNCTION__))
12471 "We have to have *some* inputs!")(((NumLoInputs > 0 || NumHiInputs > 0) && "We have to have *some* inputs!"
) ? static_cast<void> (0) : __assert_fail ("(NumLoInputs > 0 || NumHiInputs > 0) && \"We have to have *some* inputs!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 12471, __PRETTY_FUNCTION__))
;
12472 int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
12473
12474 // FIXME: We could consider the total complexity of the permute of each
12475 // possible unpacking. Or at the least we should consider how many
12476 // half-crossings are created.
12477 // FIXME: We could consider commuting the unpacks.
12478
12479 SmallVector<int, 32> PermMask((unsigned)Size, -1);
12480 for (int i = 0; i < Size; ++i) {
12481 if (Mask[i] < 0)
12482 continue;
12483
12484 assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!")((Mask[i] % Size >= HalfOffset && "Found input from wrong half!"
) ? static_cast<void> (0) : __assert_fail ("Mask[i] % Size >= HalfOffset && \"Found input from wrong half!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 12484, __PRETTY_FUNCTION__))
;
12485
12486 PermMask[i] =
12487 2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
12488 }
12489 return DAG.getVectorShuffle(
12490 VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
12491 DL, VT, V1, V2),
12492 DAG.getUNDEF(VT), PermMask);
12493 }
12494
12495 return SDValue();
12496}
12497
12498/// Handle lowering of 2-lane 64-bit floating point shuffles.
12499///
12500/// This is the basis function for the 2-lane 64-bit shuffles as we have full
12501/// support for floating point shuffles but not integer shuffles. These
12502/// instructions will incur a domain crossing penalty on some chips though so
12503/// it is better to avoid lowering through this for integer vectors where
12504/// possible.
12505static SDValue lowerV2F64Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
12506 const APInt &Zeroable, SDValue V1, SDValue V2,
12507 const X86Subtarget &Subtarget,
12508 SelectionDAG &DAG) {
12509 assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!")((V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!"
) ? static_cast<void> (0) : __assert_fail ("V1.getSimpleValueType() == MVT::v2f64 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 12509, __PRETTY_FUNCTION__))
;
12510 assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!")((V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!"
) ? static_cast<void> (0) : __assert_fail ("V2.getSimpleValueType() == MVT::v2f64 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 12510, __PRETTY_FUNCTION__))
;
12511 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!")((Mask.size() == 2 && "Unexpected mask size for v2 shuffle!"
) ? static_cast<void> (0) : __assert_fail ("Mask.size() == 2 && \"Unexpected mask size for v2 shuffle!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 12511, __PRETTY_FUNCTION__))
;
12512
12513 if (V2.isUndef()) {
12514 // Check for being able to broadcast a single element.
12515 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v2f64, V1, V2,
12516 Mask, Subtarget, DAG))
12517 return Broadcast;
12518
12519 // Straight shuffle of a single input vector. Simulate this by using the
12520 // single input as both of the "inputs" to this instruction..
12521 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
12522
12523 if (Subtarget.hasAVX()) {
12524 // If we have AVX, we can use VPERMILPS which will allow folding a load
12525 // into the shuffle.
12526 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
12527 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
12528 }
12529
12530 return DAG.getNode(
12531 X86ISD::SHUFP, DL, MVT::v2f64,
12532 Mask[0] == SM_SentinelUndef ? DAG.getUNDEF(MVT::v2f64) : V1,
12533 Mask[1] == SM_SentinelUndef ? DAG.getUNDEF(MVT::v2f64) : V1,
12534 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
12535 }
12536 assert(Mask[0] >= 0 && "No undef lanes in multi-input v2 shuffles!")((Mask[0] >= 0 && "No undef lanes in multi-input v2 shuffles!"
) ? static_cast<void> (0) : __assert_fail ("Mask[0] >= 0 && \"No undef lanes in multi-input v2 shuffles!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 12536, __PRETTY_FUNCTION__))
;
12537 assert(Mask[1] >= 0 && "No undef lanes in multi-input v2 shuffles!")((Mask[1] >= 0 && "No undef lanes in multi-input v2 shuffles!"
) ? static_cast<void> (0) : __assert_fail ("Mask[1] >= 0 && \"No undef lanes in multi-input v2 shuffles!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 12537, __PRETTY_FUNCTION__))
;
12538 assert(Mask[0] < 2 && "We sort V1 to be the first input.")((Mask[0] < 2 && "We sort V1 to be the first input."
) ? static_cast<void> (0) : __assert_fail ("Mask[0] < 2 && \"We sort V1 to be the first input.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 12538, __PRETTY_FUNCTION__))
;
12539 assert(Mask[1] >= 2 && "We sort V2 to be the second input.")((Mask[1] >= 2 && "We sort V2 to be the second input."
) ? static_cast<void> (0) : __assert_fail ("Mask[1] >= 2 && \"We sort V2 to be the second input.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 12539, __PRETTY_FUNCTION__))
;
12540
12541 if (Subtarget.hasAVX2())
12542 if (SDValue Extract = lowerShuffleOfExtractsAsVperm(DL, V1, V2, Mask, DAG))
12543 return Extract;
12544
12545 // When loading a scalar and then shuffling it into a vector we can often do
12546 // the insertion cheaply.
12547 if (SDValue Insertion = lowerShuffleAsElementInsertion(
12548 DL, MVT::v2f64, V1, V2, Mask, Zeroable, Subtarget, DAG))
12549 return Insertion;
12550 // Try inverting the insertion since for v2 masks it is easy to do and we
12551 // can't reliably sort the mask one way or the other.
12552 int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
12553 Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
12554 if (SDValue Insertion = lowerShuffleAsElementInsertion(
12555 DL, MVT::v2f64, V2, V1, InverseMask, Zeroable, Subtarget, DAG))
12556 return Insertion;
12557
12558 // Try to use one of the special instruction patterns to handle two common
12559 // blend patterns if a zero-blend above didn't work.
12560 if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
12561 isShuffleEquivalent(V1, V2, Mask, {1, 3}))
12562 if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
12563 // We can either use a special instruction to load over the low double or
12564 // to move just the low double.
12565 return DAG.getNode(
12566 X86ISD::MOVSD, DL, MVT::v2f64, V2,
12567 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
12568
12569 if (Subtarget.hasSSE41())
12570 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
12571 Zeroable, Subtarget, DAG))
12572 return Blend;
12573
12574 // Use dedicated unpack instructions for masks that match their pattern.
12575 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v2f64, Mask, V1, V2, DAG))
12576 return V;
12577
12578 unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
12579 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
12580 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
12581}
12582
12583/// Handle lowering of 2-lane 64-bit integer shuffles.
12584///
12585/// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
12586/// the integer unit to minimize domain crossing penalties. However, for blends
12587/// it falls back to the floating point shuffle operation with appropriate bit
12588/// casting.
12589static SDValue lowerV2I64Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
12590 const APInt &Zeroable, SDValue V1, SDValue V2,
12591 const X86Subtarget &Subtarget,
12592 SelectionDAG &DAG) {
12593 assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!")((V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!"
) ? static_cast<void> (0) : __assert_fail ("V1.getSimpleValueType() == MVT::v2i64 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 12593, __PRETTY_FUNCTION__))
;
12594 assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!")((V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!"
) ? static_cast<void> (0) : __assert_fail ("V2.getSimpleValueType() == MVT::v2i64 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 12594, __PRETTY_FUNCTION__))
;
12595 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!")((Mask.size() == 2 && "Unexpected mask size for v2 shuffle!"
) ? static_cast<void> (0) : __assert_fail ("Mask.size() == 2 && \"Unexpected mask size for v2 shuffle!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 12595, __PRETTY_FUNCTION__))
;
12596
12597 if (V2.isUndef()) {
12598 // Check for being able to broadcast a single element.
12599 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v2i64, V1, V2,
12600 Mask, Subtarget, DAG))
12601 return Broadcast;
12602
12603 // Straight shuffle of a single input vector. For everything from SSE2
12604 // onward this has a single fast instruction with no scary immediates.
12605 // We have to map the mask as it is actually a v4i32 shuffle instruction.
12606 V1 = DAG.getBitcast(MVT::v4i32, V1);
12607 int WidenedMask[4] = {
12608 std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
12609 std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
12610 return DAG.getBitcast(
12611 MVT::v2i64,
12612 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
12613 getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
12614 }
12615 assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!")((Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!"
) ? static_cast<void> (0) : __assert_fail ("Mask[0] != -1 && \"No undef lanes in multi-input v2 shuffles!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 12615, __PRETTY_FUNCTION__))
;
12616 assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!")((Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!"
) ? static_cast<void> (0) : __assert_fail ("Mask[1] != -1 && \"No undef lanes in multi-input v2 shuffles!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 12616, __PRETTY_FUNCTION__))
;
12617 assert(Mask[0] < 2 && "We sort V1 to be the first input.")((Mask[0] < 2 && "We sort V1 to be the first input."
) ? static_cast<void> (0) : __assert_fail ("Mask[0] < 2 && \"We sort V1 to be the first input.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 12617, __PRETTY_FUNCTION__))
;
12618 assert(Mask[1] >= 2 && "We sort V2 to be the second input.")((Mask[1] >= 2 && "We sort V2 to be the second input."
) ? static_cast<void> (0) : __assert_fail ("Mask[1] >= 2 && \"We sort V2 to be the second input.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 12618, __PRETTY_FUNCTION__))
;
12619
12620 if (Subtarget.hasAVX2())
12621 if (SDValue Extract = lowerShuffleOfExtractsAsVperm(DL, V1, V2, Mask, DAG))
12622 return Extract;
12623
12624 // Try to use shift instructions.
12625 if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask,
12626 Zeroable, Subtarget, DAG))
12627 return Shift;
12628
12629 // When loading a scalar and then shuffling it into a vector we can often do
12630 // the insertion cheaply.
12631 if (SDValue Insertion = lowerShuffleAsElementInsertion(
12632 DL, MVT::v2i64, V1, V2, Mask, Zeroable, Subtarget, DAG))
12633 return Insertion;
12634 // Try inverting the insertion since for v2 masks it is easy to do and we
12635 // can't reliably sort the mask one way or the other.
12636 int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
12637 if (SDValue Insertion = lowerShuffleAsElementInsertion(
12638 DL, MVT::v2i64, V2, V1, InverseMask, Zeroable, Subtarget, DAG))
12639 return Insertion;
12640
12641 // We have different paths for blend lowering, but they all must use the
12642 // *exact* same predicate.
12643 bool IsBlendSupported = Subtarget.hasSSE41();
12644 if (IsBlendSupported)
12645 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
12646 Zeroable, Subtarget, DAG))
12647 return Blend;
12648
12649 // Use dedicated unpack instructions for masks that match their pattern.
12650 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v2i64, Mask, V1, V2, DAG))
12651 return V;
12652
12653 // Try to use byte rotation instructions.
12654 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
12655 if (Subtarget.hasSSSE3()) {
12656 if (Subtarget.hasVLX())
12657 if (SDValue Rotate = lowerShuffleAsRotate(DL, MVT::v2i64, V1, V2, Mask,
12658 Subtarget, DAG))
12659 return Rotate;
12660
12661 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v2i64, V1, V2, Mask,
12662 Subtarget, DAG))
12663 return Rotate;
12664 }
12665
12666 // If we have direct support for blends, we should lower by decomposing into
12667 // a permute. That will be faster than the domain cross.
12668 if (IsBlendSupported)
12669 return lowerShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2, Mask,
12670 Subtarget, DAG);
12671
12672 // We implement this with SHUFPD which is pretty lame because it will likely
12673 // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
12674 // However, all the alternatives are still more cycles and newer chips don't
12675 // have this problem. It would be really nice if x86 had better shuffles here.
12676 V1 = DAG.getBitcast(MVT::v2f64, V1);
12677 V2 = DAG.getBitcast(MVT::v2f64, V2);
12678 return DAG.getBitcast(MVT::v2i64,
12679 DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
12680}
12681
12682/// Lower a vector shuffle using the SHUFPS instruction.
12683///
12684/// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
12685/// It makes no assumptions about whether this is the *best* lowering, it simply
12686/// uses it.
12687static SDValue lowerShuffleWithSHUFPS(const SDLoc &DL, MVT VT,
12688 ArrayRef<int> Mask, SDValue V1,
12689 SDValue V2, SelectionDAG &DAG) {
12690 SDValue LowV = V1, HighV = V2;
12691 int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
12692
12693 int NumV2Elements = count_if(Mask, [](int M) { return M >= 4; });
12694
12695 if (NumV2Elements == 1) {
12696 int V2Index = find_if(Mask, [](int M) { return M >= 4; }) - Mask.begin();
12697
12698 // Compute the index adjacent to V2Index and in the same half by toggling
12699 // the low bit.
12700 int V2AdjIndex = V2Index ^ 1;
12701
12702 if (Mask[V2AdjIndex] < 0) {
12703 // Handles all the cases where we have a single V2 element and an undef.
12704 // This will only ever happen in the high lanes because we commute the
12705 // vector otherwise.
12706 if (V2Index < 2)
12707 std::swap(LowV, HighV);
12708 NewMask[V2Index] -= 4;
12709 } else {
12710 // Handle the case where the V2 element ends up adjacent to a V1 element.
12711 // To make this work, blend them together as the first step.
12712 int V1Index = V2AdjIndex;
12713 int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
12714 V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
12715 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
12716
12717 // Now proceed to reconstruct the final blend as we have the necessary
12718 // high or low half formed.
12719 if (V2Index < 2) {
12720 LowV = V2;
12721 HighV = V1;
12722 } else {
12723 HighV = V2;
12724 }
12725 NewMask[V1Index] = 2; // We put the V1 element in V2[2].
12726 NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
12727 }
12728 } else if (NumV2Elements == 2) {
12729 if (Mask[0] < 4 && Mask[1] < 4) {
12730 // Handle the easy case where we have V1 in the low lanes and V2 in the
12731 // high lanes.
12732 NewMask[2] -= 4;
12733 NewMask[3] -= 4;
12734 } else if (Mask[2] < 4 && Mask[3] < 4) {
12735 // We also handle the reversed case because this utility may get called
12736 // when we detect a SHUFPS pattern but can't easily commute the shuffle to
12737 // arrange things in the right direction.
12738 NewMask[0] -= 4;
12739 NewMask[1] -= 4;
12740 HighV = V1;
12741 LowV = V2;
12742 } else {
12743 // We have a mixture of V1 and V2 in both low and high lanes. Rather than
12744 // trying to place elements directly, just blend them and set up the final
12745 // shuffle to place them.
12746
12747 // The first two blend mask elements are for V1, the second two are for
12748 // V2.
12749 int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
12750 Mask[2] < 4 ? Mask[2] : Mask[3],
12751 (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
12752 (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
12753 V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
12754 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
12755
12756 // Now we do a normal shuffle of V1 by giving V1 as both operands to
12757 // a blend.
12758 LowV = HighV = V1;
12759 NewMask[0] = Mask[0] < 4 ? 0 : 2;
12760 NewMask[1] = Mask[0] < 4 ? 2 : 0;
12761 NewMask[2] = Mask[2] < 4 ? 1 : 3;
12762 NewMask[3] = Mask[2] < 4 ? 3 : 1;
12763 }
12764 }
12765 return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
12766 getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
12767}
12768
12769/// Lower 4-lane 32-bit floating point shuffles.
12770///
12771/// Uses instructions exclusively from the floating point unit to minimize
12772/// domain crossing penalties, as these are sufficient to implement all v4f32
12773/// shuffles.
12774static SDValue lowerV4F32Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
12775 const APInt &Zeroable, SDValue V1, SDValue V2,
12776 const X86Subtarget &Subtarget,
12777 SelectionDAG &DAG) {
12778 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!")((V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!"
) ? static_cast<void> (0) : __assert_fail ("V1.getSimpleValueType() == MVT::v4f32 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 12778, __PRETTY_FUNCTION__))
;
12779 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!")((V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!"
) ? static_cast<void> (0) : __assert_fail ("V2.getSimpleValueType() == MVT::v4f32 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 12779, __PRETTY_FUNCTION__))
;
12780 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!")((Mask.size() == 4 && "Unexpected mask size for v4 shuffle!"
) ? static_cast<void> (0) : __assert_fail ("Mask.size() == 4 && \"Unexpected mask size for v4 shuffle!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 12780, __PRETTY_FUNCTION__))
;
12781
12782 int NumV2Elements = count_if(Mask, [](int M) { return M >= 4; });
12783
12784 if (NumV2Elements == 0) {
12785 // Check for being able to broadcast a single element.
12786 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v4f32, V1, V2,
12787 Mask, Subtarget, DAG))
12788 return Broadcast;
12789
12790 // Use even/odd duplicate instructions for masks that match their pattern.
12791 if (Subtarget.hasSSE3()) {
12792 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
12793 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
12794 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
12795 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
12796 }
12797
12798 if (Subtarget.hasAVX()) {
12799 // If we have AVX, we can use VPERMILPS which will allow folding a load
12800 // into the shuffle.
12801 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
12802 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
12803 }
12804
12805 // Use MOVLHPS/MOVHLPS to simulate unary shuffles. These are only valid
12806 // in SSE1 because otherwise they are widened to v2f64 and never get here.
12807 if (!Subtarget.hasSSE2()) {
12808 if (isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1}))
12809 return DAG.getNode(X86ISD::MOVLHPS, DL, MVT::v4f32, V1, V1);
12810 if (isShuffleEquivalent(V1, V2, Mask, {2, 3, 2, 3}))
12811 return DAG.getNode(X86ISD::MOVHLPS, DL, MVT::v4f32, V1, V1);
12812 }
12813
12814 // Otherwise, use a straight shuffle of a single input vector. We pass the
12815 // input vector to both operands to simulate this with a SHUFPS.
12816 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
12817 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
12818 }
12819
12820 if (Subtarget.hasAVX2())
12821 if (SDValue Extract = lowerShuffleOfExtractsAsVperm(DL, V1, V2, Mask, DAG))
12822 return Extract;
12823
12824 // There are special ways we can lower some single-element blends. However, we
12825 // have custom ways we can lower more complex single-element blends below that
12826 // we defer to if both this and BLENDPS fail to match, so restrict this to
12827 // when the V2 input is targeting element 0 of the mask -- that is the fast
12828 // case here.
12829 if (NumV2Elements == 1 && Mask[0] >= 4)
12830 if (SDValue V = lowerShuffleAsElementInsertion(
12831 DL, MVT::v4f32, V1, V2, Mask, Zeroable, Subtarget, DAG))
12832 return V;
12833
12834 if (Subtarget.hasSSE41()) {
12835 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
12836 Zeroable, Subtarget, DAG))
12837 return Blend;
12838
12839 // Use INSERTPS if we can complete the shuffle efficiently.
12840 if (SDValue V = lowerShuffleAsInsertPS(DL, V1, V2, Mask, Zeroable, DAG))
12841 return V;
12842
12843 if (!isSingleSHUFPSMask(Mask))
12844 if (SDValue BlendPerm = lowerShuffleAsBlendAndPermute(DL, MVT::v4f32, V1,
12845 V2, Mask, DAG))
12846 return BlendPerm;
12847 }
12848
12849 // Use low/high mov instructions. These are only valid in SSE1 because
12850 // otherwise they are widened to v2f64 and never get here.
12851 if (!Subtarget.hasSSE2()) {
12852 if (isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5}))
12853 return DAG.getNode(X86ISD::MOVLHPS, DL, MVT::v4f32, V1, V2);
12854 if (isShuffleEquivalent(V1, V2, Mask, {2, 3, 6, 7}))
12855 return DAG.getNode(X86ISD::MOVHLPS, DL, MVT::v4f32, V2, V1);
12856 }
12857
12858 // Use dedicated unpack instructions for masks that match their pattern.
12859 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v4f32, Mask, V1, V2, DAG))
12860 return V;
12861
12862 // Otherwise fall back to a SHUFPS lowering strategy.
12863 return lowerShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
12864}
12865
12866/// Lower 4-lane i32 vector shuffles.
12867///
12868/// We try to handle these with integer-domain shuffles where we can, but for
12869/// blends we use the floating point domain blend instructions.
12870static SDValue lowerV4I32Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
12871 const APInt &Zeroable, SDValue V1, SDValue V2,
12872 const X86Subtarget &Subtarget,
12873 SelectionDAG &DAG) {
12874 assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!")((V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!"
) ? static_cast<void> (0) : __assert_fail ("V1.getSimpleValueType() == MVT::v4i32 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 12874, __PRETTY_FUNCTION__))
;
12875 assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!")((V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!"
) ? static_cast<void> (0) : __assert_fail ("V2.getSimpleValueType() == MVT::v4i32 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 12875, __PRETTY_FUNCTION__))
;
12876 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!")((Mask.size() == 4 && "Unexpected mask size for v4 shuffle!"
) ? static_cast<void> (0) : __assert_fail ("Mask.size() == 4 && \"Unexpected mask size for v4 shuffle!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 12876, __PRETTY_FUNCTION__))
;
12877
12878 // Whenever we can lower this as a zext, that instruction is strictly faster
12879 // than any alternative. It also allows us to fold memory operands into the
12880 // shuffle in many cases.
12881 if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2, Mask,
12882 Zeroable, Subtarget, DAG))
12883 return ZExt;
12884
12885 int NumV2Elements = count_if(Mask, [](int M) { return M >= 4; });
12886
12887 if (NumV2Elements == 0) {
12888 // Check for being able to broadcast a single element.
12889 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v4i32, V1, V2,
12890 Mask, Subtarget, DAG))
12891 return Broadcast;
12892
12893 // Straight shuffle of a single input vector. For everything from SSE2
12894 // onward this has a single fast instruction with no scary immediates.
12895 // We coerce the shuffle pattern to be compatible with UNPCK instructions
12896 // but we aren't actually going to use the UNPCK instruction because doing
12897 // so prevents folding a load into this instruction or making a copy.
12898 const int UnpackLoMask[] = {0, 0, 1, 1};
12899 const int UnpackHiMask[] = {2, 2, 3, 3};
12900 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
12901 Mask = UnpackLoMask;
12902 else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
12903 Mask = UnpackHiMask;
12904
12905 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
12906 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
12907 }
12908
12909 if (Subtarget.hasAVX2())
12910 if (SDValue Extract = lowerShuffleOfExtractsAsVperm(DL, V1, V2, Mask, DAG))
12911 return Extract;
12912
12913 // Try to use shift instructions.
12914 if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask,
12915 Zeroable, Subtarget, DAG))
12916 return Shift;
12917
12918 // There are special ways we can lower some single-element blends.
12919 if (NumV2Elements == 1)
12920 if (SDValue V = lowerShuffleAsElementInsertion(
12921 DL, MVT::v4i32, V1, V2, Mask, Zeroable, Subtarget, DAG))
12922 return V;
12923
12924 // We have different paths for blend lowering, but they all must use the
12925 // *exact* same predicate.
12926 bool IsBlendSupported = Subtarget.hasSSE41();
12927 if (IsBlendSupported)
12928 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
12929 Zeroable, Subtarget, DAG))
12930 return Blend;
12931
12932 if (SDValue Masked = lowerShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask,
12933 Zeroable, Subtarget, DAG))
12934 return Masked;
12935
12936 // Use dedicated unpack instructions for masks that match their pattern.
12937 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v4i32, Mask, V1, V2, DAG))
12938 return V;
12939
12940 // Try to use byte rotation instructions.
12941 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
12942 if (Subtarget.hasSSSE3()) {
12943 if (Subtarget.hasVLX())
12944 if (SDValue Rotate = lowerShuffleAsRotate(DL, MVT::v4i32, V1, V2, Mask,
12945 Subtarget, DAG))
12946 return Rotate;
12947
12948 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v4i32, V1, V2, Mask,
12949 Subtarget, DAG))
12950 return Rotate;
12951 }
12952
12953 // Assume that a single SHUFPS is faster than an alternative sequence of
12954 // multiple instructions (even if the CPU has a domain penalty).
12955 // If some CPU is harmed by the domain switch, we can fix it in a later pass.
12956 if (!isSingleSHUFPSMask(Mask)) {
12957 // If we have direct support for blends, we should lower by decomposing into
12958 // a permute. That will be faster than the domain cross.
12959 if (IsBlendSupported)
12960 return lowerShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2, Mask,
12961 Subtarget, DAG);
12962
12963 // Try to lower by permuting the inputs into an unpack instruction.
12964 if (SDValue Unpack = lowerShuffleAsPermuteAndUnpack(DL, MVT::v4i32, V1, V2,
12965 Mask, Subtarget, DAG))
12966 return Unpack;
12967 }
12968
12969 // We implement this with SHUFPS because it can blend from two vectors.
12970 // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
12971 // up the inputs, bypassing domain shift penalties that we would incur if we
12972 // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
12973 // relevant.
12974 SDValue CastV1 = DAG.getBitcast(MVT::v4f32, V1);
12975 SDValue CastV2 = DAG.getBitcast(MVT::v4f32, V2);
12976 SDValue ShufPS = DAG.getVectorShuffle(MVT::v4f32, DL, CastV1, CastV2, Mask);
12977 return DAG.getBitcast(MVT::v4i32, ShufPS);
12978}
12979
12980/// Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
12981/// shuffle lowering, and the most complex part.
12982///
12983/// The lowering strategy is to try to form pairs of input lanes which are
12984/// targeted at the same half of the final vector, and then use a dword shuffle
12985/// to place them onto the right half, and finally unpack the paired lanes into
12986/// their final position.
12987///
12988/// The exact breakdown of how to form these dword pairs and align them on the
12989/// correct sides is really tricky. See the comments within the function for
12990/// more of the details.
12991///
12992/// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
12993/// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
12994/// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
12995/// vector, form the analogous 128-bit 8-element Mask.
12996static SDValue lowerV8I16GeneralSingleInputShuffle(
12997 const SDLoc &DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
12998 const X86Subtarget &Subtarget, SelectionDAG &DAG) {
12999 assert(VT.getVectorElementType() == MVT::i16 && "Bad input type!")((VT.getVectorElementType() == MVT::i16 && "Bad input type!"
) ? static_cast<void> (0) : __assert_fail ("VT.getVectorElementType() == MVT::i16 && \"Bad input type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 12999, __PRETTY_FUNCTION__))
;
13000 MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
13001
13002 assert(Mask.size() == 8 && "Shuffle mask length doesn't match!")((Mask.size() == 8 && "Shuffle mask length doesn't match!"
) ? static_cast<void> (0) : __assert_fail ("Mask.size() == 8 && \"Shuffle mask length doesn't match!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 13002, __PRETTY_FUNCTION__))
;
13003 MutableArrayRef<int> LoMask = Mask.slice(0, 4);
13004 MutableArrayRef<int> HiMask = Mask.slice(4, 4);
13005
13006 // Attempt to directly match PSHUFLW or PSHUFHW.
13007 if (isUndefOrInRange(LoMask, 0, 4) &&
13008 isSequentialOrUndefInRange(HiMask, 0, 4, 4)) {
13009 return DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
13010 getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
13011 }
13012 if (isUndefOrInRange(HiMask, 4, 8) &&
13013 isSequentialOrUndefInRange(LoMask, 0, 4, 0)) {
13014 for (int i = 0; i != 4; ++i)
13015 HiMask[i] = (HiMask[i] < 0 ? HiMask[i] : (HiMask[i] - 4));
13016 return DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
13017 getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
13018 }
13019
13020 SmallVector<int, 4> LoInputs;
13021 copy_if(LoMask, std::back_inserter(LoInputs), [](int M) { return M >= 0; });
13022 array_pod_sort(LoInputs.begin(), LoInputs.end());
13023 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
13024 SmallVector<int, 4> HiInputs;
13025 copy_if(HiMask, std::back_inserter(HiInputs), [](int M) { return M >= 0; });
13026 array_pod_sort(HiInputs.begin(), HiInputs.end());
13027 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
13028 int NumLToL =
13029 std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
13030 int NumHToL = LoInputs.size() - NumLToL;
13031 int NumLToH =
13032 std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
13033 int NumHToH = HiInputs.size() - NumLToH;
13034 MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
13035 MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
13036 MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
13037 MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
13038
13039 // If we are shuffling values from one half - check how many different DWORD
13040 // pairs we need to create. If only 1 or 2 then we can perform this as a
13041 // PSHUFLW/PSHUFHW + PSHUFD instead of the PSHUFD+PSHUFLW+PSHUFHW chain below.
13042 auto ShuffleDWordPairs = [&](ArrayRef<int> PSHUFHalfMask,
13043 ArrayRef<int> PSHUFDMask, unsigned ShufWOp) {
13044 V = DAG.getNode(ShufWOp, DL, VT, V,
13045 getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
13046 V = DAG.getBitcast(PSHUFDVT, V);
13047 V = DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, V,
13048 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
13049 return DAG.getBitcast(VT, V);
13050 };
13051
13052 if ((NumHToL + NumHToH) == 0 || (NumLToL + NumLToH) == 0) {
13053 int PSHUFDMask[4] = { -1, -1, -1, -1 };
13054 SmallVector<std::pair<int, int>, 4> DWordPairs;
13055 int DOffset = ((NumHToL + NumHToH) == 0 ? 0 : 2);
13056
13057 // Collect the different DWORD pairs.
13058 for (int DWord = 0; DWord != 4; ++DWord) {
13059 int M0 = Mask[2 * DWord + 0];
13060 int M1 = Mask[2 * DWord + 1];
13061 M0 = (M0 >= 0 ? M0 % 4 : M0);
13062 M1 = (M1 >= 0 ? M1 % 4 : M1);
13063 if (M0 < 0 && M1 < 0)
13064 continue;
13065
13066 bool Match = false;
13067 for (int j = 0, e = DWordPairs.size(); j < e; ++j) {
13068 auto &DWordPair = DWordPairs[j];
13069 if ((M0 < 0 || isUndefOrEqual(DWordPair.first, M0)) &&
13070 (M1 < 0 || isUndefOrEqual(DWordPair.second, M1))) {
13071 DWordPair.first = (M0 >= 0 ? M0 : DWordPair.first);
13072 DWordPair.second = (M1 >= 0 ? M1 : DWordPair.second);
13073 PSHUFDMask[DWord] = DOffset + j;
13074 Match = true;
13075 break;
13076 }
13077 }
13078 if (!Match) {
13079 PSHUFDMask[DWord] = DOffset + DWordPairs.size();
13080 DWordPairs.push_back(std::make_pair(M0, M1));
13081 }
13082 }
13083
13084 if (DWordPairs.size() <= 2) {
13085 DWordPairs.resize(2, std::make_pair(-1, -1));
13086 int PSHUFHalfMask[4] = {DWordPairs[0].first, DWordPairs[0].second,
13087 DWordPairs[1].first, DWordPairs[1].second};
13088 if ((NumHToL + NumHToH) == 0)
13089 return ShuffleDWordPairs(PSHUFHalfMask, PSHUFDMask, X86ISD::PSHUFLW);
13090 if ((NumLToL + NumLToH) == 0)
13091 return ShuffleDWordPairs(PSHUFHalfMask, PSHUFDMask, X86ISD::PSHUFHW);
13092 }
13093 }
13094
13095 // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
13096 // such inputs we can swap two of the dwords across the half mark and end up
13097 // with <=2 inputs to each half in each half. Once there, we can fall through
13098 // to the generic code below. For example:
13099 //
13100 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
13101 // Mask: [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
13102 //
13103 // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
13104 // and an existing 2-into-2 on the other half. In this case we may have to
13105 // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
13106 // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
13107 // Fortunately, we don't have to handle anything but a 2-into-2 pattern
13108 // because any other situation (including a 3-into-1 or 1-into-3 in the other
13109 // half than the one we target for fixing) will be fixed when we re-enter this
13110 // path. We will also combine away any sequence of PSHUFD instructions that
13111 // result into a single instruction. Here is an example of the tricky case:
13112 //
13113 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
13114 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
13115 //
13116 // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
13117 //
13118 // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
13119 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
13120 //
13121 // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
13122 // Mask: [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
13123 //
13124 // The result is fine to be handled by the generic logic.
13125 auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
13126 ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
13127 int AOffset, int BOffset) {
13128 assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&(((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
"Must call this with A having 3 or 1 inputs from the A half."
) ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 13129, __PRETTY_FUNCTION__))
13129 "Must call this with A having 3 or 1 inputs from the A half.")(((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
"Must call this with A having 3 or 1 inputs from the A half."
) ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 13129, __PRETTY_FUNCTION__))
;
13130 assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&(((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
"Must call this with B having 1 or 3 inputs from the B half."
) ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 13131, __PRETTY_FUNCTION__))
13131 "Must call this with B having 1 or 3 inputs from the B half.")(((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
"Must call this with B having 1 or 3 inputs from the B half."
) ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 13131, __PRETTY_FUNCTION__))
;
13132 assert(AToAInputs.size() + BToAInputs.size() == 4 &&((AToAInputs.size() + BToAInputs.size() == 4 && "Must call this with either 3:1 or 1:3 inputs (summing to 4)."
) ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 13133, __PRETTY_FUNCTION__))
13133 "Must call this with either 3:1 or 1:3 inputs (summing to 4).")((AToAInputs.size() + BToAInputs.size() == 4 && "Must call this with either 3:1 or 1:3 inputs (summing to 4)."
) ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 13133, __PRETTY_FUNCTION__))
;
13134
13135 bool ThreeAInputs = AToAInputs.size() == 3;
13136
13137 // Compute the index of dword with only one word among the three inputs in
13138 // a half by taking the sum of the half with three inputs and subtracting
13139 // the sum of the actual three inputs. The difference is the remaining
13140 // slot.
13141 int ADWord, BDWord;
13142 int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
13143 int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
13144 int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
13145 ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
13146 int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
13147 int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
13148 int TripleNonInputIdx =
13149 TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
13150 TripleDWord = TripleNonInputIdx / 2;
13151
13152 // We use xor with one to compute the adjacent DWord to whichever one the
13153 // OneInput is in.
13154 OneInputDWord = (OneInput / 2) ^ 1;
13155
13156 // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
13157 // and BToA inputs. If there is also such a problem with the BToB and AToB
13158 // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
13159 // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
13160 // is essential that we don't *create* a 3<-1 as then we might oscillate.
13161 if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
13162 // Compute how many inputs will be flipped by swapping these DWords. We
13163 // need
13164 // to balance this to ensure we don't form a 3-1 shuffle in the other
13165 // half.
13166 int NumFlippedAToBInputs =
13167 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
13168 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
13169 int NumFlippedBToBInputs =
13170 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
13171 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
13172 if ((NumFlippedAToBInputs == 1 &&
13173 (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
13174 (NumFlippedBToBInputs == 1 &&
13175 (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
13176 // We choose whether to fix the A half or B half based on whether that
13177 // half has zero flipped inputs. At zero, we may not be able to fix it
13178 // with that half. We also bias towards fixing the B half because that
13179 // will more commonly be the high half, and we have to bias one way.
13180 auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
13181 ArrayRef<int> Inputs) {
13182 int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
13183 bool IsFixIdxInput = is_contained(Inputs, PinnedIdx ^ 1);
13184 // Determine whether the free index is in the flipped dword or the
13185 // unflipped dword based on where the pinned index is. We use this bit
13186 // in an xor to conditionally select the adjacent dword.
13187 int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
13188 bool IsFixFreeIdxInput = is_contained(Inputs, FixFreeIdx);
13189 if (IsFixIdxInput == IsFixFreeIdxInput)
13190 FixFreeIdx += 1;
13191 IsFixFreeIdxInput = is_contained(Inputs, FixFreeIdx);
13192 assert(IsFixIdxInput != IsFixFreeIdxInput &&((IsFixIdxInput != IsFixFreeIdxInput && "We need to be changing the number of flipped inputs!"
) ? static_cast<void> (0) : __assert_fail ("IsFixIdxInput != IsFixFreeIdxInput && \"We need to be changing the number of flipped inputs!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 13193, __PRETTY_FUNCTION__))
13193 "We need to be changing the number of flipped inputs!")((IsFixIdxInput != IsFixFreeIdxInput && "We need to be changing the number of flipped inputs!"
) ? static_cast<void> (0) : __assert_fail ("IsFixIdxInput != IsFixFreeIdxInput && \"We need to be changing the number of flipped inputs!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 13193, __PRETTY_FUNCTION__))
;
13194 int PSHUFHalfMask[] = {0, 1, 2, 3};
13195 std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
13196 V = DAG.getNode(
13197 FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
13198 MVT::getVectorVT(MVT::i16, V.getValueSizeInBits() / 16), V,
13199 getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
13200
13201 for (int &M : Mask)
13202 if (M >= 0 && M == FixIdx)
13203 M = FixFreeIdx;
13204 else if (M >= 0 && M == FixFreeIdx)
13205 M = FixIdx;
13206 };
13207 if (NumFlippedBToBInputs != 0) {
13208 int BPinnedIdx =
13209 BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
13210 FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
13211 } else {
13212 assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!")((NumFlippedAToBInputs != 0 && "Impossible given predicates!"
) ? static_cast<void> (0) : __assert_fail ("NumFlippedAToBInputs != 0 && \"Impossible given predicates!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 13212, __PRETTY_FUNCTION__))
;
13213 int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
13214 FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
13215 }
13216 }
13217 }
13218
13219 int PSHUFDMask[] = {0, 1, 2, 3};
13220 PSHUFDMask[ADWord] = BDWord;
13221 PSHUFDMask[BDWord] = ADWord;
13222 V = DAG.getBitcast(
13223 VT,
13224 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
13225 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
13226
13227 // Adjust the mask to match the new locations of A and B.
13228 for (int &M : Mask)
13229 if (M >= 0 && M/2 == ADWord)
13230 M = 2 * BDWord + M % 2;
13231 else if (M >= 0 && M/2 == BDWord)
13232 M = 2 * ADWord + M % 2;
13233
13234 // Recurse back into this routine to re-compute state now that this isn't
13235 // a 3 and 1 problem.
13236 return lowerV8I16GeneralSingleInputShuffle(DL, VT, V, Mask, Subtarget, DAG);
13237 };
13238 if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
13239 return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
13240 if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
13241 return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
13242
13243 // At this point there are at most two inputs to the low and high halves from
13244 // each half. That means the inputs can always be grouped into dwords and
13245 // those dwords can then be moved to the correct half with a dword shuffle.
13246 // We use at most one low and one high word shuffle to collect these paired
13247 // inputs into dwords, and finally a dword shuffle to place them.
13248 int PSHUFLMask[4] = {-1, -1, -1, -1};
13249 int PSHUFHMask[4] = {-1, -1, -1, -1};
13250 int PSHUFDMask[4] = {-1, -1, -1, -1};
13251
13252 // First fix the masks for all the inputs that are staying in their
13253 // original halves. This will then dictate the targets of the cross-half
13254 // shuffles.
13255 auto fixInPlaceInputs =
13256 [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
13257 MutableArrayRef<int> SourceHalfMask,
13258 MutableArrayRef<int> HalfMask, int HalfOffset) {
13259 if (InPlaceInputs.empty())
13260 return;
13261 if (InPlaceInputs.size() == 1) {
13262 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
13263 InPlaceInputs[0] - HalfOffset;
13264 PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
13265 return;
13266 }
13267 if (IncomingInputs.empty()) {
13268 // Just fix all of the in place inputs.
13269 for (int Input : InPlaceInputs) {
13270 SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
13271 PSHUFDMask[Input / 2] = Input / 2;
13272 }
13273 return;
13274 }
13275
13276 assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!")((InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!"
) ? static_cast<void> (0) : __assert_fail ("InPlaceInputs.size() == 2 && \"Cannot handle 3 or 4 inputs!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 13276, __PRETTY_FUNCTION__))
;
13277 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
13278 InPlaceInputs[0] - HalfOffset;
13279 // Put the second input next to the first so that they are packed into
13280 // a dword. We find the adjacent index by toggling the low bit.
13281 int AdjIndex = InPlaceInputs[0] ^ 1;
13282 SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
13283 std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
13284 PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
13285 };
13286 fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
13287 fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
13288
13289 // Now gather the cross-half inputs and place them into a free dword of
13290 // their target half.
13291 // FIXME: This operation could almost certainly be simplified dramatically to
13292 // look more like the 3-1 fixing operation.
13293 auto moveInputsToRightHalf = [&PSHUFDMask](
13294 MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
13295 MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
13296 MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
13297 int DestOffset) {
13298 auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
13299 return SourceHalfMask[Word] >= 0 && SourceHalfMask[Word] != Word;
13300 };
13301 auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
13302 int Word) {
13303 int LowWord = Word & ~1;
13304 int HighWord = Word | 1;
13305 return isWordClobbered(SourceHalfMask, LowWord) ||
13306 isWordClobbered(SourceHalfMask, HighWord);
13307 };
13308
13309 if (IncomingInputs.empty())
13310 return;
13311
13312 if (ExistingInputs.empty()) {
13313 // Map any dwords with inputs from them into the right half.
13314 for (int Input : IncomingInputs) {
13315 // If the source half mask maps over the inputs, turn those into
13316 // swaps and use the swapped lane.
13317 if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
13318 if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] < 0) {
13319 SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
13320 Input - SourceOffset;
13321 // We have to swap the uses in our half mask in one sweep.
13322 for (int &M : HalfMask)
13323 if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
13324 M = Input;
13325 else if (M == Input)
13326 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
13327 } else {
13328 assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==((SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == Input
- SourceOffset && "Previous placement doesn't match!"
) ? static_cast<void> (0) : __assert_fail ("SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == Input - SourceOffset && \"Previous placement doesn't match!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 13330, __PRETTY_FUNCTION__))
13329 Input - SourceOffset &&((SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == Input
- SourceOffset && "Previous placement doesn't match!"
) ? static_cast<void> (0) : __assert_fail ("SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == Input - SourceOffset && \"Previous placement doesn't match!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 13330, __PRETTY_FUNCTION__))
13330 "Previous placement doesn't match!")((SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == Input
- SourceOffset && "Previous placement doesn't match!"
) ? static_cast<void> (0) : __assert_fail ("SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == Input - SourceOffset && \"Previous placement doesn't match!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 13330, __PRETTY_FUNCTION__))
;
13331 }
13332 // Note that this correctly re-maps both when we do a swap and when
13333 // we observe the other side of the swap above. We rely on that to
13334 // avoid swapping the members of the input list directly.
13335 Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
13336 }
13337
13338 // Map the input's dword into the correct half.
13339 if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] < 0)
13340 PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
13341 else
13342 assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==((PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == Input
/ 2 && "Previous placement doesn't match!") ? static_cast
<void> (0) : __assert_fail ("PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == Input / 2 && \"Previous placement doesn't match!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 13344, __PRETTY_FUNCTION__))
13343 Input / 2 &&((PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == Input
/ 2 && "Previous placement doesn't match!") ? static_cast
<void> (0) : __assert_fail ("PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == Input / 2 && \"Previous placement doesn't match!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 13344, __PRETTY_FUNCTION__))
13344 "Previous placement doesn't match!")((PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == Input
/ 2 && "Previous placement doesn't match!") ? static_cast
<void> (0) : __assert_fail ("PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == Input / 2 && \"Previous placement doesn't match!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 13344, __PRETTY_FUNCTION__))
;
13345 }
13346
13347 // And just directly shift any other-half mask elements to be same-half
13348 // as we will have mirrored the dword containing the element into the
13349 // same position within that half.
13350 for (int &M : HalfMask)
13351 if (M >= SourceOffset && M < SourceOffset + 4) {
13352 M = M - SourceOffset + DestOffset;
13353 assert(M >= 0 && "This should never wrap below zero!")((M >= 0 && "This should never wrap below zero!") ?
static_cast<void> (0) : __assert_fail ("M >= 0 && \"This should never wrap below zero!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 13353, __PRETTY_FUNCTION__))
;
13354 }
13355 return;
13356 }
13357
13358 // Ensure we have the input in a viable dword of its current half. This
13359 // is particularly tricky because the original position may be clobbered
13360 // by inputs being moved and *staying* in that half.
13361 if (IncomingInputs.size() == 1) {
13362 if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
13363 int InputFixed = find(SourceHalfMask, -1) - std::begin(SourceHalfMask) +
13364 SourceOffset;
13365 SourceHalfMask[InputFixed - SourceOffset] =
13366 IncomingInputs[0] - SourceOffset;
13367 std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
13368 InputFixed);
13369 IncomingInputs[0] = InputFixed;
13370 }
13371 } else if (IncomingInputs.size() == 2) {
13372 if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
13373 isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
13374 // We have two non-adjacent or clobbered inputs we need to extract from
13375 // the source half. To do this, we need to map them into some adjacent
13376 // dword slot in the source mask.
13377 int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
13378 IncomingInputs[1] - SourceOffset};
13379
13380 // If there is a free slot in the source half mask adjacent to one of
13381 // the inputs, place the other input in it. We use (Index XOR 1) to
13382 // compute an adjacent index.
13383 if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
13384 SourceHalfMask[InputsFixed[0] ^ 1] < 0) {
13385 SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
13386 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
13387 InputsFixed[1] = InputsFixed[0] ^ 1;
13388 } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
13389 SourceHalfMask[InputsFixed[1] ^ 1] < 0) {
13390 SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
13391 SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
13392 InputsFixed[0] = InputsFixed[1] ^ 1;
13393 } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] < 0 &&
13394 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] < 0) {
13395 // The two inputs are in the same DWord but it is clobbered and the
13396 // adjacent DWord isn't used at all. Move both inputs to the free
13397 // slot.
13398 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
13399 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
13400 InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
13401 InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
13402 } else {
13403 // The only way we hit this point is if there is no clobbering
13404 // (because there are no off-half inputs to this half) and there is no
13405 // free slot adjacent to one of the inputs. In this case, we have to
13406 // swap an input with a non-input.
13407 for (int i = 0; i < 4; ++i)
13408 assert((SourceHalfMask[i] < 0 || SourceHalfMask[i] == i) &&(((SourceHalfMask[i] < 0 || SourceHalfMask[i] == i) &&
"We can't handle any clobbers here!") ? static_cast<void>
(0) : __assert_fail ("(SourceHalfMask[i] < 0 || SourceHalfMask[i] == i) && \"We can't handle any clobbers here!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 13409, __PRETTY_FUNCTION__))
13409 "We can't handle any clobbers here!")(((SourceHalfMask[i] < 0 || SourceHalfMask[i] == i) &&
"We can't handle any clobbers here!") ? static_cast<void>
(0) : __assert_fail ("(SourceHalfMask[i] < 0 || SourceHalfMask[i] == i) && \"We can't handle any clobbers here!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 13409, __PRETTY_FUNCTION__))
;
13410 assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&((InputsFixed[1] != (InputsFixed[0] ^ 1) && "Cannot have adjacent inputs here!"
) ? static_cast<void> (0) : __assert_fail ("InputsFixed[1] != (InputsFixed[0] ^ 1) && \"Cannot have adjacent inputs here!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 13411, __PRETTY_FUNCTION__))
13411 "Cannot have adjacent inputs here!")((InputsFixed[1] != (InputsFixed[0] ^ 1) && "Cannot have adjacent inputs here!"
) ? static_cast<void> (0) : __assert_fail ("InputsFixed[1] != (InputsFixed[0] ^ 1) && \"Cannot have adjacent inputs here!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 13411, __PRETTY_FUNCTION__))
;
13412
13413 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
13414 SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
13415
13416 // We also have to update the final source mask in this case because
13417 // it may need to undo the above swap.
13418 for (int &M : FinalSourceHalfMask)
13419 if (M == (InputsFixed[0] ^ 1) + SourceOffset)
13420 M = InputsFixed[1] + SourceOffset;
13421 else if (M == InputsFixed[1] + SourceOffset)
13422 M = (InputsFixed[0] ^ 1) + SourceOffset;
13423
13424 InputsFixed[1] = InputsFixed[0] ^ 1;
13425 }
13426
13427 // Point everything at the fixed inputs.
13428 for (int &M : HalfMask)
13429 if (M == IncomingInputs[0])
13430 M = InputsFixed[0] + SourceOffset;
13431 else if (M == IncomingInputs[1])
13432 M = InputsFixed[1] + SourceOffset;
13433
13434 IncomingInputs[0] = InputsFixed[0] + SourceOffset;
13435 IncomingInputs[1] = InputsFixed[1] + SourceOffset;
13436 }
13437 } else {
13438 llvm_unreachable("Unhandled input size!")::llvm::llvm_unreachable_internal("Unhandled input size!", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 13438)
;
13439 }
13440
13441 // Now hoist the DWord down to the right half.
13442 int FreeDWord = (PSHUFDMask[DestOffset / 2] < 0 ? 0 : 1) + DestOffset / 2;
13443 assert(PSHUFDMask[FreeDWord] < 0 && "DWord not free")((PSHUFDMask[FreeDWord] < 0 && "DWord not free") ?
static_cast<void> (0) : __assert_fail ("PSHUFDMask[FreeDWord] < 0 && \"DWord not free\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 13443, __PRETTY_FUNCTION__))
;
13444 PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
13445 for (int &M : HalfMask)
13446 for (int Input : IncomingInputs)
13447 if (M == Input)
13448 M = FreeDWord * 2 + Input % 2;
13449 };
13450 moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
13451 /*SourceOffset*/ 4, /*DestOffset*/ 0);
13452 moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
13453 /*SourceOffset*/ 0, /*DestOffset*/ 4);
13454
13455 // Now enact all the shuffles we've computed to move the inputs into their
13456 // target half.
13457 if (!isNoopShuffleMask(PSHUFLMask))
13458 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
13459 getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
13460 if (!isNoopShuffleMask(PSHUFHMask))
13461 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
13462 getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
13463 if (!isNoopShuffleMask(PSHUFDMask))
13464 V = DAG.getBitcast(
13465 VT,
13466 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
13467 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
13468
13469 // At this point, each half should contain all its inputs, and we can then
13470 // just shuffle them into their final position.
13471 assert(count_if(LoMask, [](int M) { return M >= 4; }) == 0 &&((count_if(LoMask, [](int M) { return M >= 4; }) == 0 &&
"Failed to lift all the high half inputs to the low mask!") ?
static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 13472, __PRETTY_FUNCTION__))
13472 "Failed to lift all the high half inputs to the low mask!")((count_if(LoMask, [](int M) { return M >= 4; }) == 0 &&
"Failed to lift all the high half inputs to the low mask!") ?
static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 13472, __PRETTY_FUNCTION__))
;
13473 assert(count_if(HiMask, [](int M) { return M >= 0 && M < 4; }) == 0 &&((count_if(HiMask, [](int M) { return M >= 0 && M <
4; }) == 0 && "Failed to lift all the low half inputs to the high mask!"
) ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 13474, __PRETTY_FUNCTION__))
13474 "Failed to lift all the low half inputs to the high mask!")((count_if(HiMask, [](int M) { return M >= 0 && M <
4; }) == 0 && "Failed to lift all the low half inputs to the high mask!"
) ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 13474, __PRETTY_FUNCTION__))
;
13475
13476 // Do a half shuffle for the low mask.
13477 if (!isNoopShuffleMask(LoMask))
13478 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
13479 getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
13480
13481 // Do a half shuffle with the high mask after shifting its values down.
13482 for (int &M : HiMask)
13483 if (M >= 0)
13484 M -= 4;
13485 if (!isNoopShuffleMask(HiMask))
13486 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
13487 getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
13488
13489 return V;
13490}
13491
13492/// Helper to form a PSHUFB-based shuffle+blend, opportunistically avoiding the
13493/// blend if only one input is used.
13494static SDValue lowerShuffleAsBlendOfPSHUFBs(
13495 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
13496 const APInt &Zeroable, SelectionDAG &DAG, bool &V1InUse, bool &V2InUse) {
13497 assert(!is128BitLaneCrossingShuffleMask(VT, Mask) &&((!is128BitLaneCrossingShuffleMask(VT, Mask) && "Lane crossing shuffle masks not supported"
) ? static_cast<void> (0) : __assert_fail ("!is128BitLaneCrossingShuffleMask(VT, Mask) && \"Lane crossing shuffle masks not supported\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 13498, __PRETTY_FUNCTION__))
13498 "Lane crossing shuffle masks not supported")((!is128BitLaneCrossingShuffleMask(VT, Mask) && "Lane crossing shuffle masks not supported"
) ? static_cast<void> (0) : __assert_fail ("!is128BitLaneCrossingShuffleMask(VT, Mask) && \"Lane crossing shuffle masks not supported\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 13498, __PRETTY_FUNCTION__))
;
13499
13500 int NumBytes = VT.getSizeInBits() / 8;
13501 int Size = Mask.size();
13502 int Scale = NumBytes / Size;
13503
13504 SmallVector<SDValue, 64> V1Mask(NumBytes, DAG.getUNDEF(MVT::i8));
13505 SmallVector<SDValue, 64> V2Mask(NumBytes, DAG.getUNDEF(MVT::i8));
13506 V1InUse = false;
13507 V2InUse = false;
13508
13509 for (int i = 0; i < NumBytes; ++i) {
13510 int M = Mask[i / Scale];
13511 if (M < 0)
13512 continue;
13513
13514 const int ZeroMask = 0x80;
13515 int V1Idx = M < Size ? M * Scale + i % Scale : ZeroMask;
13516 int V2Idx = M < Size ? ZeroMask : (M - Size) * Scale + i % Scale;
13517 if (Zeroable[i / Scale])
13518 V1Idx = V2Idx = ZeroMask;
13519
13520 V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
13521 V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
13522 V1InUse |= (ZeroMask != V1Idx);
13523 V2InUse |= (ZeroMask != V2Idx);
13524 }
13525
13526 MVT ShufVT = MVT::getVectorVT(MVT::i8, NumBytes);
13527 if (V1InUse)
13528 V1 = DAG.getNode(X86ISD::PSHUFB, DL, ShufVT, DAG.getBitcast(ShufVT, V1),
13529 DAG.getBuildVector(ShufVT, DL, V1Mask));
13530 if (V2InUse)
13531 V2 = DAG.getNode(X86ISD::PSHUFB, DL, ShufVT, DAG.getBitcast(ShufVT, V2),
13532 DAG.getBuildVector(ShufVT, DL, V2Mask));
13533
13534 // If we need shuffled inputs from both, blend the two.
13535 SDValue V;
13536 if (V1InUse && V2InUse)
13537 V = DAG.getNode(ISD::OR, DL, ShufVT, V1, V2);
13538 else
13539 V = V1InUse ? V1 : V2;
13540
13541 // Cast the result back to the correct type.
13542 return DAG.getBitcast(VT, V);
13543}
13544
13545/// Generic lowering of 8-lane i16 shuffles.
13546///
13547/// This handles both single-input shuffles and combined shuffle/blends with
13548/// two inputs. The single input shuffles are immediately delegated to
13549/// a dedicated lowering routine.
13550///
13551/// The blends are lowered in one of three fundamental ways. If there are few
13552/// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
13553/// of the input is significantly cheaper when lowered as an interleaving of
13554/// the two inputs, try to interleave them. Otherwise, blend the low and high
13555/// halves of the inputs separately (making them have relatively few inputs)
13556/// and then concatenate them.
13557static SDValue lowerV8I16Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
13558 const APInt &Zeroable, SDValue V1, SDValue V2,
13559 const X86Subtarget &Subtarget,
13560 SelectionDAG &DAG) {
13561 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!")((V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!"
) ? static_cast<void> (0) : __assert_fail ("V1.getSimpleValueType() == MVT::v8i16 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 13561, __PRETTY_FUNCTION__))
;
13562 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!")((V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!"
) ? static_cast<void> (0) : __assert_fail ("V2.getSimpleValueType() == MVT::v8i16 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 13562, __PRETTY_FUNCTION__))
;
13563 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!")((Mask.size() == 8 && "Unexpected mask size for v8 shuffle!"
) ? static_cast<void> (0) : __assert_fail ("Mask.size() == 8 && \"Unexpected mask size for v8 shuffle!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 13563, __PRETTY_FUNCTION__))
;
13564
13565 // Whenever we can lower this as a zext, that instruction is strictly faster
13566 // than any alternative.
13567 if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v8i16, V1, V2, Mask,
13568 Zeroable, Subtarget, DAG))
13569 return ZExt;
13570
13571 int NumV2Inputs = count_if(Mask, [](int M) { return M >= 8; });
13572
13573 if (NumV2Inputs == 0) {
13574 // Check for being able to broadcast a single element.
13575 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v8i16, V1, V2,
13576 Mask, Subtarget, DAG))
13577 return Broadcast;
13578
13579 // Try to use shift instructions.
13580 if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask,
13581 Zeroable, Subtarget, DAG))
13582 return Shift;
13583
13584 // Use dedicated unpack instructions for masks that match their pattern.
13585 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
13586 return V;
13587
13588 // Use dedicated pack instructions for masks that match their pattern.
13589 if (SDValue V = lowerShuffleWithPACK(DL, MVT::v8i16, Mask, V1, V2, DAG,
13590 Subtarget))
13591 return V;
13592
13593 // Try to use byte rotation instructions.
13594 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v8i16, V1, V1, Mask,
13595 Subtarget, DAG))
13596 return Rotate;
13597
13598 // Make a copy of the mask so it can be modified.
13599 SmallVector<int, 8> MutableMask(Mask.begin(), Mask.end());
13600 return lowerV8I16GeneralSingleInputShuffle(DL, MVT::v8i16, V1, MutableMask,
13601 Subtarget, DAG);
13602 }
13603
13604 assert(llvm::any_of(Mask, [](int M) { return M >= 0 && M < 8; }) &&((llvm::any_of(Mask, [](int M) { return M >= 0 && M
< 8; }) && "All single-input shuffles should be canonicalized to be V1-input "
"shuffles.") ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 13606, __PRETTY_FUNCTION__))
13605 "All single-input shuffles should be canonicalized to be V1-input "((llvm::any_of(Mask, [](int M) { return M >= 0 && M
< 8; }) && "All single-input shuffles should be canonicalized to be V1-input "
"shuffles.") ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 13606, __PRETTY_FUNCTION__))
13606 "shuffles.")((llvm::any_of(Mask, [](int M) { return M >= 0 && M
< 8; }) && "All single-input shuffles should be canonicalized to be V1-input "
"shuffles.") ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 13606, __PRETTY_FUNCTION__))
;
13607
13608 // Try to use shift instructions.
13609 if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask,
13610 Zeroable, Subtarget, DAG))
13611 return Shift;
13612
13613 // See if we can use SSE4A Extraction / Insertion.
13614 if (Subtarget.hasSSE4A())
13615 if (SDValue V = lowerShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask,
13616 Zeroable, DAG))
13617 return V;
13618
13619 // There are special ways we can lower some single-element blends.
13620 if (NumV2Inputs == 1)
13621 if (SDValue V = lowerShuffleAsElementInsertion(
13622 DL, MVT::v8i16, V1, V2, Mask, Zeroable, Subtarget, DAG))
13623 return V;
13624
13625 // We have different paths for blend lowering, but they all must use the
13626 // *exact* same predicate.
13627 bool IsBlendSupported = Subtarget.hasSSE41();
13628 if (IsBlendSupported)
13629 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
13630 Zeroable, Subtarget, DAG))
13631 return Blend;
13632
13633 if (SDValue Masked = lowerShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask,
13634 Zeroable, Subtarget, DAG))
13635 return Masked;
13636
13637 // Use dedicated unpack instructions for masks that match their pattern.
13638 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
13639 return V;
13640
13641 // Use dedicated pack instructions for masks that match their pattern.
13642 if (SDValue V = lowerShuffleWithPACK(DL, MVT::v8i16, Mask, V1, V2, DAG,
13643 Subtarget))
13644 return V;
13645
13646 // Try to use byte rotation instructions.
13647 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v8i16, V1, V2, Mask,
13648 Subtarget, DAG))
13649 return Rotate;
13650
13651 if (SDValue BitBlend =
13652 lowerShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
13653 return BitBlend;
13654
13655 // Try to use byte shift instructions to mask.
13656 if (SDValue V = lowerVectorShuffleAsByteShiftMask(
13657 DL, MVT::v8i16, V1, V2, Mask, Zeroable, Subtarget, DAG))
13658 return V;
13659
13660 // Try to lower by permuting the inputs into an unpack instruction.
13661 if (SDValue Unpack = lowerShuffleAsPermuteAndUnpack(DL, MVT::v8i16, V1, V2,
13662 Mask, Subtarget, DAG))
13663 return Unpack;
13664
13665 // If we can't directly blend but can use PSHUFB, that will be better as it
13666 // can both shuffle and set up the inefficient blend.
13667 if (!IsBlendSupported && Subtarget.hasSSSE3()) {
13668 bool V1InUse, V2InUse;
13669 return lowerShuffleAsBlendOfPSHUFBs(DL, MVT::v8i16, V1, V2, Mask,
13670 Zeroable, DAG, V1InUse, V2InUse);
13671 }
13672
13673 // We can always bit-blend if we have to so the fallback strategy is to
13674 // decompose into single-input permutes and blends.
13675 return lowerShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
13676 Mask, Subtarget, DAG);
13677}
13678
13679/// Check whether a compaction lowering can be done by dropping even
13680/// elements and compute how many times even elements must be dropped.
13681///
13682/// This handles shuffles which take every Nth element where N is a power of
13683/// two. Example shuffle masks:
13684///
13685/// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14
13686/// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
13687/// N = 2: 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12
13688/// N = 2: 0, 4, 8, 12, 16, 20, 24, 28, 0, 4, 8, 12, 16, 20, 24, 28
13689/// N = 3: 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8
13690/// N = 3: 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24
13691///
13692/// Any of these lanes can of course be undef.
13693///
13694/// This routine only supports N <= 3.
13695/// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
13696/// for larger N.
13697///
13698/// \returns N above, or the number of times even elements must be dropped if
13699/// there is such a number. Otherwise returns zero.
13700static int canLowerByDroppingEvenElements(ArrayRef<int> Mask,
13701 bool IsSingleInput) {
13702 // The modulus for the shuffle vector entries is based on whether this is
13703 // a single input or not.
13704 int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
13705 assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&((isPowerOf2_32((uint32_t)ShuffleModulus) && "We should only be called with masks with a power-of-2 size!"
) ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 13706, __PRETTY_FUNCTION__))
13706 "We should only be called with masks with a power-of-2 size!")((isPowerOf2_32((uint32_t)ShuffleModulus) && "We should only be called with masks with a power-of-2 size!"
) ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 13706, __PRETTY_FUNCTION__))
;
13707
13708 uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
13709
13710 // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
13711 // and 2^3 simultaneously. This is because we may have ambiguity with
13712 // partially undef inputs.
13713 bool ViableForN[3] = {true, true, true};
13714
13715 for (int i = 0, e = Mask.size(); i < e; ++i) {
13716 // Ignore undef lanes, we'll optimistically collapse them to the pattern we
13717 // want.
13718 if (Mask[i] < 0)
13719 continue;
13720
13721 bool IsAnyViable = false;
13722 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
13723 if (ViableForN[j]) {
13724 uint64_t N = j + 1;
13725
13726 // The shuffle mask must be equal to (i * 2^N) % M.
13727 if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
13728 IsAnyViable = true;
13729 else
13730 ViableForN[j] = false;
13731 }
13732 // Early exit if we exhaust the possible powers of two.
13733 if (!IsAnyViable)
13734 break;
13735 }
13736
13737 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
13738 if (ViableForN[j])
13739 return j + 1;
13740
13741 // Return 0 as there is no viable power of two.
13742 return 0;
13743}
13744
13745static SDValue lowerShuffleWithPERMV(const SDLoc &DL, MVT VT,
13746 ArrayRef<int> Mask, SDValue V1,
13747 SDValue V2, SelectionDAG &DAG) {
13748 MVT MaskEltVT = MVT::getIntegerVT(VT.getScalarSizeInBits());
13749 MVT MaskVecVT = MVT::getVectorVT(MaskEltVT, VT.getVectorNumElements());
13750
13751 SDValue MaskNode = getConstVector(Mask, MaskVecVT, DAG, DL, true);
13752 if (V2.isUndef())
13753 return DAG.getNode(X86ISD::VPERMV, DL, VT, MaskNode, V1);
13754
13755 return DAG.getNode(X86ISD::VPERMV3, DL, VT, V1, MaskNode, V2);
13756}
13757
13758/// Generic lowering of v16i8 shuffles.
13759///
13760/// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
13761/// detect any complexity reducing interleaving. If that doesn't help, it uses
13762/// UNPCK to spread the i8 elements across two i16-element vectors, and uses
13763/// the existing lowering for v8i16 blends on each half, finally PACK-ing them
13764/// back together.
13765static SDValue lowerV16I8Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
13766 const APInt &Zeroable, SDValue V1, SDValue V2,
13767 const X86Subtarget &Subtarget,
13768 SelectionDAG &DAG) {
13769 assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!")((V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!"
) ? static_cast<void> (0) : __assert_fail ("V1.getSimpleValueType() == MVT::v16i8 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 13769, __PRETTY_FUNCTION__))
;
13770 assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!")((V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!"
) ? static_cast<void> (0) : __assert_fail ("V2.getSimpleValueType() == MVT::v16i8 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 13770, __PRETTY_FUNCTION__))
;
13771 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!")((Mask.size() == 16 && "Unexpected mask size for v16 shuffle!"
) ? static_cast<void> (0) : __assert_fail ("Mask.size() == 16 && \"Unexpected mask size for v16 shuffle!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 13771, __PRETTY_FUNCTION__))
;
13772
13773 // Try to use shift instructions.
13774 if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask,
13775 Zeroable, Subtarget, DAG))
13776 return Shift;
13777
13778 // Try to use byte rotation instructions.
13779 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v16i8, V1, V2, Mask,
13780 Subtarget, DAG))
13781 return Rotate;
13782
13783 // Use dedicated pack instructions for masks that match their pattern.
13784 if (SDValue V = lowerShuffleWithPACK(DL, MVT::v16i8, Mask, V1, V2, DAG,
13785 Subtarget))
13786 return V;
13787
13788 // Try to use a zext lowering.
13789 if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v16i8, V1, V2, Mask,
13790 Zeroable, Subtarget, DAG))
13791 return ZExt;
13792
13793 // See if we can use SSE4A Extraction / Insertion.
13794 if (Subtarget.hasSSE4A())
13795 if (SDValue V = lowerShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask,
13796 Zeroable, DAG))
13797 return V;
13798
13799 int NumV2Elements = count_if(Mask, [](int M) { return M >= 16; });
13800
13801 // For single-input shuffles, there are some nicer lowering tricks we can use.
13802 if (NumV2Elements == 0) {
13803 // Check for being able to broadcast a single element.
13804 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v16i8, V1, V2,
13805 Mask, Subtarget, DAG))
13806 return Broadcast;
13807
13808 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16i8, Mask, V1, V2, DAG))
13809 return V;
13810
13811 // Check whether we can widen this to an i16 shuffle by duplicating bytes.
13812 // Notably, this handles splat and partial-splat shuffles more efficiently.
13813 // However, it only makes sense if the pre-duplication shuffle simplifies
13814 // things significantly. Currently, this means we need to be able to
13815 // express the pre-duplication shuffle as an i16 shuffle.
13816 //
13817 // FIXME: We should check for other patterns which can be widened into an
13818 // i16 shuffle as well.
13819 auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
13820 for (int i = 0; i < 16; i += 2)
13821 if (Mask[i] >= 0 && Mask[i + 1] >= 0 && Mask[i] != Mask[i + 1])
13822 return false;
13823
13824 return true;
13825 };
13826 auto tryToWidenViaDuplication = [&]() -> SDValue {
13827 if (!canWidenViaDuplication(Mask))
13828 return SDValue();
13829 SmallVector<int, 4> LoInputs;
13830 copy_if(Mask, std::back_inserter(LoInputs),
13831 [](int M) { return M >= 0 && M < 8; });
13832 array_pod_sort(LoInputs.begin(), LoInputs.end());
13833 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
13834 LoInputs.end());
13835 SmallVector<int, 4> HiInputs;
13836 copy_if(Mask, std::back_inserter(HiInputs), [](int M) { return M >= 8; });
13837 array_pod_sort(HiInputs.begin(), HiInputs.end());
13838 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
13839 HiInputs.end());
13840
13841 bool TargetLo = LoInputs.size() >= HiInputs.size();
13842 ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
13843 ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
13844
13845 int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
13846 SmallDenseMap<int, int, 8> LaneMap;
13847 for (int I : InPlaceInputs) {
13848 PreDupI16Shuffle[I/2] = I/2;
13849 LaneMap[I] = I;
13850 }
13851 int j = TargetLo ? 0 : 4, je = j + 4;
13852 for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
13853 // Check if j is already a shuffle of this input. This happens when
13854 // there are two adjacent bytes after we move the low one.
13855 if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
13856 // If we haven't yet mapped the input, search for a slot into which
13857 // we can map it.
13858 while (j < je && PreDupI16Shuffle[j] >= 0)
13859 ++j;
13860
13861 if (j == je)
13862 // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
13863 return SDValue();
13864
13865 // Map this input with the i16 shuffle.
13866 PreDupI16Shuffle[j] = MovingInputs[i] / 2;
13867 }
13868
13869 // Update the lane map based on the mapping we ended up with.
13870 LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
13871 }
13872 V1 = DAG.getBitcast(
13873 MVT::v16i8,
13874 DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
13875 DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
13876
13877 // Unpack the bytes to form the i16s that will be shuffled into place.
13878 V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
13879 MVT::v16i8, V1, V1);
13880
13881 int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
13882 for (int i = 0; i < 16; ++i)
13883 if (Mask[i] >= 0) {
13884 int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
13885 assert(MappedMask < 8 && "Invalid v8 shuffle mask!")((MappedMask < 8 && "Invalid v8 shuffle mask!") ? static_cast
<void> (0) : __assert_fail ("MappedMask < 8 && \"Invalid v8 shuffle mask!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 13885, __PRETTY_FUNCTION__))
;
13886 if (PostDupI16Shuffle[i / 2] < 0)
13887 PostDupI16Shuffle[i / 2] = MappedMask;
13888 else
13889 assert(PostDupI16Shuffle[i / 2] == MappedMask &&((PostDupI16Shuffle[i / 2] == MappedMask && "Conflicting entries in the original shuffle!"
) ? static_cast<void> (0) : __assert_fail ("PostDupI16Shuffle[i / 2] == MappedMask && \"Conflicting entries in the original shuffle!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 13890, __PRETTY_FUNCTION__))
13890 "Conflicting entries in the original shuffle!")((PostDupI16Shuffle[i / 2] == MappedMask && "Conflicting entries in the original shuffle!"
) ? static_cast<void> (0) : __assert_fail ("PostDupI16Shuffle[i / 2] == MappedMask && \"Conflicting entries in the original shuffle!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 13890, __PRETTY_FUNCTION__))
;
13891 }
13892 return DAG.getBitcast(
13893 MVT::v16i8,
13894 DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
13895 DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
13896 };
13897 if (SDValue V = tryToWidenViaDuplication())
13898 return V;
13899 }
13900
13901 if (SDValue Masked = lowerShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask,
13902 Zeroable, Subtarget, DAG))
13903 return Masked;
13904
13905 // Use dedicated unpack instructions for masks that match their pattern.
13906 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16i8, Mask, V1, V2, DAG))
13907 return V;
13908
13909 // Try to use byte shift instructions to mask.
13910 if (SDValue V = lowerVectorShuffleAsByteShiftMask(
13911 DL, MVT::v16i8, V1, V2, Mask, Zeroable, Subtarget, DAG))
13912 return V;
13913
13914 // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
13915 // with PSHUFB. It is important to do this before we attempt to generate any
13916 // blends but after all of the single-input lowerings. If the single input
13917 // lowerings can find an instruction sequence that is faster than a PSHUFB, we
13918 // want to preserve that and we can DAG combine any longer sequences into
13919 // a PSHUFB in the end. But once we start blending from multiple inputs,
13920 // the complexity of DAG combining bad patterns back into PSHUFB is too high,
13921 // and there are *very* few patterns that would actually be faster than the
13922 // PSHUFB approach because of its ability to zero lanes.
13923 //
13924 // FIXME: The only exceptions to the above are blends which are exact
13925 // interleavings with direct instructions supporting them. We currently don't
13926 // handle those well here.
13927 if (Subtarget.hasSSSE3()) {
13928 bool V1InUse = false;
13929 bool V2InUse = false;
13930
13931 SDValue PSHUFB = lowerShuffleAsBlendOfPSHUFBs(
13932 DL, MVT::v16i8, V1, V2, Mask, Zeroable, DAG, V1InUse, V2InUse);
13933
13934 // If both V1 and V2 are in use and we can use a direct blend or an unpack,
13935 // do so. This avoids using them to handle blends-with-zero which is
13936 // important as a single pshufb is significantly faster for that.
13937 if (V1InUse && V2InUse) {
13938 if (Subtarget.hasSSE41())
13939 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v16i8, V1, V2, Mask,
13940 Zeroable, Subtarget, DAG))
13941 return Blend;
13942
13943 // We can use an unpack to do the blending rather than an or in some
13944 // cases. Even though the or may be (very minorly) more efficient, we
13945 // preference this lowering because there are common cases where part of
13946 // the complexity of the shuffles goes away when we do the final blend as
13947 // an unpack.
13948 // FIXME: It might be worth trying to detect if the unpack-feeding
13949 // shuffles will both be pshufb, in which case we shouldn't bother with
13950 // this.
13951 if (SDValue Unpack = lowerShuffleAsPermuteAndUnpack(
13952 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
13953 return Unpack;
13954
13955 // If we have VBMI we can use one VPERM instead of multiple PSHUFBs.
13956 if (Subtarget.hasVBMI() && Subtarget.hasVLX())
13957 return lowerShuffleWithPERMV(DL, MVT::v16i8, Mask, V1, V2, DAG);
13958
13959 // Use PALIGNR+Permute if possible - permute might become PSHUFB but the
13960 // PALIGNR will be cheaper than the second PSHUFB+OR.
13961 if (SDValue V = lowerShuffleAsByteRotateAndPermute(
13962 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
13963 return V;
13964 }
13965
13966 return PSHUFB;
13967 }
13968
13969 // There are special ways we can lower some single-element blends.
13970 if (NumV2Elements == 1)
13971 if (SDValue V = lowerShuffleAsElementInsertion(
13972 DL, MVT::v16i8, V1, V2, Mask, Zeroable, Subtarget, DAG))
13973 return V;
13974
13975 if (SDValue Blend = lowerShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
13976 return Blend;
13977
13978 // Check whether a compaction lowering can be done. This handles shuffles
13979 // which take every Nth element for some even N. See the helper function for
13980 // details.
13981 //
13982 // We special case these as they can be particularly efficiently handled with
13983 // the PACKUSB instruction on x86 and they show up in common patterns of
13984 // rearranging bytes to truncate wide elements.
13985 bool IsSingleInput = V2.isUndef();
13986 if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask, IsSingleInput)) {
13987 // NumEvenDrops is the power of two stride of the elements. Another way of
13988 // thinking about it is that we need to drop the even elements this many
13989 // times to get the original input.
13990
13991 // First we need to zero all the dropped bytes.
13992 assert(NumEvenDrops <= 3 &&((NumEvenDrops <= 3 && "No support for dropping even elements more than 3 times."
) ? static_cast<void> (0) : __assert_fail ("NumEvenDrops <= 3 && \"No support for dropping even elements more than 3 times.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 13993, __PRETTY_FUNCTION__))
13993 "No support for dropping even elements more than 3 times.")((NumEvenDrops <= 3 && "No support for dropping even elements more than 3 times."
) ? static_cast<void> (0) : __assert_fail ("NumEvenDrops <= 3 && \"No support for dropping even elements more than 3 times.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 13993, __PRETTY_FUNCTION__))
;
13994 // We use the mask type to pick which bytes are preserved based on how many
13995 // elements are dropped.
13996 MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
13997 SDValue ByteClearMask = DAG.getBitcast(
13998 MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
13999 V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
14000 if (!IsSingleInput)
14001 V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
14002
14003 // Now pack things back together.
14004 V1 = DAG.getBitcast(MVT::v8i16, V1);
14005 V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
14006 SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
14007 for (int i = 1; i < NumEvenDrops; ++i) {
14008 Result = DAG.getBitcast(MVT::v8i16, Result);
14009 Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
14010 }
14011
14012 return Result;
14013 }
14014
14015 // Handle multi-input cases by blending single-input shuffles.
14016 if (NumV2Elements > 0)
14017 return lowerShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2, Mask,
14018 Subtarget, DAG);
14019
14020 // The fallback path for single-input shuffles widens this into two v8i16
14021 // vectors with unpacks, shuffles those, and then pulls them back together
14022 // with a pack.
14023 SDValue V = V1;
14024
14025 std::array<int, 8> LoBlendMask = {{-1, -1, -1, -1, -1, -1, -1, -1}};
14026 std::array<int, 8> HiBlendMask = {{-1, -1, -1, -1, -1, -1, -1, -1}};
14027 for (int i = 0; i < 16; ++i)
14028 if (Mask[i] >= 0)
14029 (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
14030
14031 SDValue VLoHalf, VHiHalf;
14032 // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
14033 // them out and avoid using UNPCK{L,H} to extract the elements of V as
14034 // i16s.
14035 if (none_of(LoBlendMask, [](int M) { return M >= 0 && M % 2 == 1; }) &&
14036 none_of(HiBlendMask, [](int M) { return M >= 0 && M % 2 == 1; })) {
14037 // Use a mask to drop the high bytes.
14038 VLoHalf = DAG.getBitcast(MVT::v8i16, V);
14039 VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
14040 DAG.getConstant(0x00FF, DL, MVT::v8i16));
14041
14042 // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
14043 VHiHalf = DAG.getUNDEF(MVT::v8i16);
14044
14045 // Squash the masks to point directly into VLoHalf.
14046 for (int &M : LoBlendMask)
14047 if (M >= 0)
14048 M /= 2;
14049 for (int &M : HiBlendMask)
14050 if (M >= 0)
14051 M /= 2;
14052 } else {
14053 // Otherwise just unpack the low half of V into VLoHalf and the high half into
14054 // VHiHalf so that we can blend them as i16s.
14055 SDValue Zero = getZeroVector(MVT::v16i8, Subtarget, DAG, DL);
14056
14057 VLoHalf = DAG.getBitcast(
14058 MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
14059 VHiHalf = DAG.getBitcast(
14060 MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
14061 }
14062
14063 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
14064 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
14065
14066 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
14067}
14068
14069/// Dispatching routine to lower various 128-bit x86 vector shuffles.
14070///
14071/// This routine breaks down the specific type of 128-bit shuffle and
14072/// dispatches to the lowering routines accordingly.
14073static SDValue lower128BitShuffle(const SDLoc &DL, ArrayRef<int> Mask,
14074 MVT VT, SDValue V1, SDValue V2,
14075 const APInt &Zeroable,
14076 const X86Subtarget &Subtarget,
14077 SelectionDAG &DAG) {
14078 switch (VT.SimpleTy) {
14079 case MVT::v2i64:
14080 return lowerV2I64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
14081 case MVT::v2f64:
14082 return lowerV2F64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
14083 case MVT::v4i32:
14084 return lowerV4I32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
14085 case MVT::v4f32:
14086 return lowerV4F32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
14087 case MVT::v8i16:
14088 return lowerV8I16Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
14089 case MVT::v16i8:
14090 return lowerV16I8Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
14091
14092 default:
14093 llvm_unreachable("Unimplemented!")::llvm::llvm_unreachable_internal("Unimplemented!", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 14093)
;
14094 }
14095}
14096
14097/// Generic routine to split vector shuffle into half-sized shuffles.
14098///
14099/// This routine just extracts two subvectors, shuffles them independently, and
14100/// then concatenates them back together. This should work effectively with all
14101/// AVX vector shuffle types.
14102static SDValue splitAndLowerShuffle(const SDLoc &DL, MVT VT, SDValue V1,
14103 SDValue V2, ArrayRef<int> Mask,
14104 SelectionDAG &DAG) {
14105 assert(VT.getSizeInBits() >= 256 &&((VT.getSizeInBits() >= 256 && "Only for 256-bit or wider vector shuffles!"
) ? static_cast<void> (0) : __assert_fail ("VT.getSizeInBits() >= 256 && \"Only for 256-bit or wider vector shuffles!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 14106, __PRETTY_FUNCTION__))
14106 "Only for 256-bit or wider vector shuffles!")((VT.getSizeInBits() >= 256 && "Only for 256-bit or wider vector shuffles!"
) ? static_cast<void> (0) : __assert_fail ("VT.getSizeInBits() >= 256 && \"Only for 256-bit or wider vector shuffles!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 14106, __PRETTY_FUNCTION__))
;
14107 assert(V1.getSimpleValueType() == VT && "Bad operand type!")((V1.getSimpleValueType() == VT && "Bad operand type!"
) ? static_cast<void> (0) : __assert_fail ("V1.getSimpleValueType() == VT && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 14107, __PRETTY_FUNCTION__))
;
14108 assert(V2.getSimpleValueType() == VT && "Bad operand type!")((V2.getSimpleValueType() == VT && "Bad operand type!"
) ? static_cast<void> (0) : __assert_fail ("V2.getSimpleValueType() == VT && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 14108, __PRETTY_FUNCTION__))
;
14109
14110 ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
14111 ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
14112
14113 int NumElements = VT.getVectorNumElements();
14114 int SplitNumElements = NumElements / 2;
14115 MVT ScalarVT = VT.getVectorElementType();
14116 MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
14117
14118 // Rather than splitting build-vectors, just build two narrower build
14119 // vectors. This helps shuffling with splats and zeros.
14120 auto SplitVector = [&](SDValue V) {
14121 V = peekThroughBitcasts(V);
14122
14123 MVT OrigVT = V.getSimpleValueType();
14124 int OrigNumElements = OrigVT.getVectorNumElements();
14125 int OrigSplitNumElements = OrigNumElements / 2;
14126 MVT OrigScalarVT = OrigVT.getVectorElementType();
14127 MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
14128
14129 SDValue LoV, HiV;
14130
14131 auto *BV = dyn_cast<BuildVectorSDNode>(V);
14132 if (!BV) {
14133 LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
14134 DAG.getIntPtrConstant(0, DL));
14135 HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
14136 DAG.getIntPtrConstant(OrigSplitNumElements, DL));
14137 } else {
14138
14139 SmallVector<SDValue, 16> LoOps, HiOps;
14140 for (int i = 0; i < OrigSplitNumElements; ++i) {
14141 LoOps.push_back(BV->getOperand(i));
14142 HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
14143 }
14144 LoV = DAG.getBuildVector(OrigSplitVT, DL, LoOps);
14145 HiV = DAG.getBuildVector(OrigSplitVT, DL, HiOps);
14146 }
14147 return std::make_pair(DAG.getBitcast(SplitVT, LoV),
14148 DAG.getBitcast(SplitVT, HiV));
14149 };
14150
14151 SDValue LoV1, HiV1, LoV2, HiV2;
14152 std::tie(LoV1, HiV1) = SplitVector(V1);
14153 std::tie(LoV2, HiV2) = SplitVector(V2);
14154
14155 // Now create two 4-way blends of these half-width vectors.
14156 auto HalfBlend = [&](ArrayRef<int> HalfMask) {
14157 bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
14158 SmallVector<int, 32> V1BlendMask((unsigned)SplitNumElements, -1);
14159 SmallVector<int, 32> V2BlendMask((unsigned)SplitNumElements, -1);
14160 SmallVector<int, 32> BlendMask((unsigned)SplitNumElements, -1);
14161 for (int i = 0; i < SplitNumElements; ++i) {
14162 int M = HalfMask[i];
14163 if (M >= NumElements) {
14164 if (M >= NumElements + SplitNumElements)
14165 UseHiV2 = true;
14166 else
14167 UseLoV2 = true;
14168 V2BlendMask[i] = M - NumElements;
14169 BlendMask[i] = SplitNumElements + i;
14170 } else if (M >= 0) {
14171 if (M >= SplitNumElements)
14172 UseHiV1 = true;
14173 else
14174 UseLoV1 = true;
14175 V1BlendMask[i] = M;
14176 BlendMask[i] = i;
14177 }
14178 }
14179
14180 // Because the lowering happens after all combining takes place, we need to
14181 // manually combine these blend masks as much as possible so that we create
14182 // a minimal number of high-level vector shuffle nodes.
14183
14184 // First try just blending the halves of V1 or V2.
14185 if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
14186 return DAG.getUNDEF(SplitVT);
14187 if (!UseLoV2 && !UseHiV2)
14188 return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
14189 if (!UseLoV1 && !UseHiV1)
14190 return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
14191
14192 SDValue V1Blend, V2Blend;
14193 if (UseLoV1 && UseHiV1) {
14194 V1Blend =
14195 DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
14196 } else {
14197 // We only use half of V1 so map the usage down into the final blend mask.
14198 V1Blend = UseLoV1 ? LoV1 : HiV1;
14199 for (int i = 0; i < SplitNumElements; ++i)
14200 if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
14201 BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
14202 }
14203 if (UseLoV2 && UseHiV2) {
14204 V2Blend =
14205 DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
14206 } else {
14207 // We only use half of V2 so map the usage down into the final blend mask.
14208 V2Blend = UseLoV2 ? LoV2 : HiV2;
14209 for (int i = 0; i < SplitNumElements; ++i)
14210 if (BlendMask[i] >= SplitNumElements)
14211 BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
14212 }
14213 return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
14214 };
14215 SDValue Lo = HalfBlend(LoMask);
14216 SDValue Hi = HalfBlend(HiMask);
14217 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
14218}
14219
14220/// Either split a vector in halves or decompose the shuffles and the
14221/// blend.
14222///
14223/// This is provided as a good fallback for many lowerings of non-single-input
14224/// shuffles with more than one 128-bit lane. In those cases, we want to select
14225/// between splitting the shuffle into 128-bit components and stitching those
14226/// back together vs. extracting the single-input shuffles and blending those
14227/// results.
14228static SDValue lowerShuffleAsSplitOrBlend(const SDLoc &DL, MVT VT, SDValue V1,
14229 SDValue V2, ArrayRef<int> Mask,
14230 const X86Subtarget &Subtarget,
14231 SelectionDAG &DAG) {
14232 assert(!V2.isUndef() && "This routine must not be used to lower single-input "((!V2.isUndef() && "This routine must not be used to lower single-input "
"shuffles as it could then recurse on itself.") ? static_cast
<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 14233, __PRETTY_FUNCTION__))
14233 "shuffles as it could then recurse on itself.")((!V2.isUndef() && "This routine must not be used to lower single-input "
"shuffles as it could then recurse on itself.") ? static_cast
<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 14233, __PRETTY_FUNCTION__))
;
14234 int Size = Mask.size();
14235
14236 // If this can be modeled as a broadcast of two elements followed by a blend,
14237 // prefer that lowering. This is especially important because broadcasts can
14238 // often fold with memory operands.
14239 auto DoBothBroadcast = [&] {
14240 int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
14241 for (int M : Mask)
14242 if (M >= Size) {
14243 if (V2BroadcastIdx < 0)
14244 V2BroadcastIdx = M - Size;
14245 else if (M - Size != V2BroadcastIdx)
14246 return false;
14247 } else if (M >= 0) {
14248 if (V1BroadcastIdx < 0)
14249 V1BroadcastIdx = M;
14250 else if (M != V1BroadcastIdx)
14251 return false;
14252 }
14253 return true;
14254 };
14255 if (DoBothBroadcast())
14256 return lowerShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
14257 Subtarget, DAG);
14258
14259 // If the inputs all stem from a single 128-bit lane of each input, then we
14260 // split them rather than blending because the split will decompose to
14261 // unusually few instructions.
14262 int LaneCount = VT.getSizeInBits() / 128;
14263 int LaneSize = Size / LaneCount;
14264 SmallBitVector LaneInputs[2];
14265 LaneInputs[0].resize(LaneCount, false);
14266 LaneInputs[1].resize(LaneCount, false);
14267 for (int i = 0; i < Size; ++i)
14268 if (Mask[i] >= 0)
14269 LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
14270 if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
14271 return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG);
14272
14273 // Otherwise, just fall back to decomposed shuffles and a blend. This requires
14274 // that the decomposed single-input shuffles don't end up here.
14275 return lowerShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, Subtarget,
14276 DAG);
14277}
14278
14279/// Lower a vector shuffle crossing multiple 128-bit lanes as
14280/// a lane permutation followed by a per-lane permutation.
14281///
14282/// This is mainly for cases where we can have non-repeating permutes
14283/// in each lane.
14284///
14285/// TODO: This is very similar to lowerShuffleAsLanePermuteAndRepeatedMask,
14286/// we should investigate merging them.
14287static SDValue lowerShuffleAsLanePermuteAndPermute(
14288 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
14289 SelectionDAG &DAG, const X86Subtarget &Subtarget) {
14290 int NumElts = VT.getVectorNumElements();
14291 int NumLanes = VT.getSizeInBits() / 128;
14292 int NumEltsPerLane = NumElts / NumLanes;
14293
14294 SmallVector<int, 4> SrcLaneMask(NumLanes, SM_SentinelUndef);
14295 SmallVector<int, 16> PermMask(NumElts, SM_SentinelUndef);
14296
14297 for (int i = 0; i != NumElts; ++i) {
14298 int M = Mask[i];
14299 if (M < 0)
14300 continue;
14301
14302 // Ensure that each lane comes from a single source lane.
14303 int SrcLane = M / NumEltsPerLane;
14304 int DstLane = i / NumEltsPerLane;
14305 if (!isUndefOrEqual(SrcLaneMask[DstLane], SrcLane))
14306 return SDValue();
14307 SrcLaneMask[DstLane] = SrcLane;
14308
14309 PermMask[i] = (DstLane * NumEltsPerLane) + (M % NumEltsPerLane);
14310 }
14311
14312 // Make sure we set all elements of the lane mask, to avoid undef propagation.
14313 SmallVector<int, 16> LaneMask(NumElts, SM_SentinelUndef);
14314 for (int DstLane = 0; DstLane != NumLanes; ++DstLane) {
14315 int SrcLane = SrcLaneMask[DstLane];
14316 if (0 <= SrcLane)
14317 for (int j = 0; j != NumEltsPerLane; ++j) {
14318 LaneMask[(DstLane * NumEltsPerLane) + j] =
14319 (SrcLane * NumEltsPerLane) + j;
14320 }
14321 }
14322
14323 // If we're only shuffling a single lowest lane and the rest are identity
14324 // then don't bother.
14325 // TODO - isShuffleMaskInputInPlace could be extended to something like this.
14326 int NumIdentityLanes = 0;
14327 bool OnlyShuffleLowestLane = true;
14328 for (int i = 0; i != NumLanes; ++i) {
14329 if (isSequentialOrUndefInRange(PermMask, i * NumEltsPerLane, NumEltsPerLane,
14330 i * NumEltsPerLane))
14331 NumIdentityLanes++;
14332 else if (SrcLaneMask[i] != 0 && SrcLaneMask[i] != NumLanes)
14333 OnlyShuffleLowestLane = false;
14334 }
14335 if (OnlyShuffleLowestLane && NumIdentityLanes == (NumLanes - 1))
14336 return SDValue();
14337
14338 SDValue LanePermute = DAG.getVectorShuffle(VT, DL, V1, V2, LaneMask);
14339 return DAG.getVectorShuffle(VT, DL, LanePermute, DAG.getUNDEF(VT), PermMask);
14340}
14341
14342/// Lower a vector shuffle crossing multiple 128-bit lanes as
14343/// a permutation and blend of those lanes.
14344///
14345/// This essentially blends the out-of-lane inputs to each lane into the lane
14346/// from a permuted copy of the vector. This lowering strategy results in four
14347/// instructions in the worst case for a single-input cross lane shuffle which
14348/// is lower than any other fully general cross-lane shuffle strategy I'm aware
14349/// of. Special cases for each particular shuffle pattern should be handled
14350/// prior to trying this lowering.
14351static SDValue lowerShuffleAsLanePermuteAndBlend(
14352 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
14353 SelectionDAG &DAG, const X86Subtarget &Subtarget) {
14354 // FIXME: This should probably be generalized for 512-bit vectors as well.
14355 assert(VT.is256BitVector() && "Only for 256-bit vector shuffles!")((VT.is256BitVector() && "Only for 256-bit vector shuffles!"
) ? static_cast<void> (0) : __assert_fail ("VT.is256BitVector() && \"Only for 256-bit vector shuffles!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 14355, __PRETTY_FUNCTION__))
;
18
'?' condition is true
14356 int Size = Mask.size();
14357 int LaneSize = Size / 2;
14358
14359 // If there are only inputs from one 128-bit lane, splitting will in fact be
14360 // less expensive. The flags track whether the given lane contains an element
14361 // that crosses to another lane.
14362 if (!Subtarget.hasAVX2()) {
19
Taking true branch
14363 bool LaneCrossing[2] = {false, false};
14364 for (int i = 0; i < Size; ++i)
20
Assuming 'i' is < 'Size'
21
Loop condition is true. Entering loop body
25
Assuming 'i' is >= 'Size'
26
Loop condition is false. Execution continues on line 14367
14365 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
22
Assuming the condition is true
23
Assuming the condition is true
24
Taking true branch
14366 LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
14367 if (!LaneCrossing[0] || !LaneCrossing[1])
27
Assuming the condition is false
28
Assuming the condition is false
29
Taking false branch
14368 return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG);
14369 } else {
14370 bool LaneUsed[2] = {false, false};
14371 for (int i = 0; i < Size; ++i)
14372 if (Mask[i] >= 0)
14373 LaneUsed[(Mask[i] / LaneSize)] = true;
14374 if (!LaneUsed[0] || !LaneUsed[1])
14375 return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG);
14376 }
14377
14378 assert(V2.isUndef() &&((V2.isUndef() && "This last part of this routine only works on single input shuffles"
) ? static_cast<void> (0) : __assert_fail ("V2.isUndef() && \"This last part of this routine only works on single input shuffles\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 14379, __PRETTY_FUNCTION__))
30
'?' condition is true
14379 "This last part of this routine only works on single input shuffles")((V2.isUndef() && "This last part of this routine only works on single input shuffles"
) ? static_cast<void> (0) : __assert_fail ("V2.isUndef() && \"This last part of this routine only works on single input shuffles\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 14379, __PRETTY_FUNCTION__))
;
14380
14381 SmallVector<int, 32> FlippedBlendMask(Size);
14382 for (int i = 0; i < Size; ++i)
31
Loop condition is true. Entering loop body
14383 FlippedBlendMask[i] =
14384 Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
32
Assuming the condition is false
33
'?' condition is false
34
The result of the '/' expression is undefined
14385 ? Mask[i]
14386 : Mask[i] % LaneSize +
14387 (i / LaneSize) * LaneSize + Size);
14388
14389 // Flip the vector, and blend the results which should now be in-lane.
14390 MVT PVT = VT.isFloatingPoint() ? MVT::v4f64 : MVT::v4i64;
14391 SDValue Flipped = DAG.getBitcast(PVT, V1);
14392 Flipped = DAG.getVectorShuffle(PVT, DL, Flipped, DAG.getUNDEF(PVT),
14393 { 2, 3, 0, 1 });
14394 Flipped = DAG.getBitcast(VT, Flipped);
14395 return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
14396}
14397
14398/// Handle lowering 2-lane 128-bit shuffles.
14399static SDValue lowerV2X128Shuffle(const SDLoc &DL, MVT VT, SDValue V1,
14400 SDValue V2, ArrayRef<int> Mask,
14401 const APInt &Zeroable,
14402 const X86Subtarget &Subtarget,
14403 SelectionDAG &DAG) {
14404 // With AVX2, use VPERMQ/VPERMPD for unary shuffles to allow memory folding.
14405 if (Subtarget.hasAVX2() && V2.isUndef())
14406 return SDValue();
14407
14408 SmallVector<int, 4> WidenedMask;
14409 if (!canWidenShuffleElements(Mask, Zeroable, WidenedMask))
14410 return SDValue();
14411
14412 bool IsLowZero = (Zeroable & 0x3) == 0x3;
14413 bool IsHighZero = (Zeroable & 0xc) == 0xc;
14414
14415 // Try to use an insert into a zero vector.
14416 if (WidenedMask[0] == 0 && IsHighZero) {
14417 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), 2);
14418 SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
14419 DAG.getIntPtrConstant(0, DL));
14420 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
14421 getZeroVector(VT, Subtarget, DAG, DL), LoV,
14422 DAG.getIntPtrConstant(0, DL));
14423 }
14424
14425 // TODO: If minimizing size and one of the inputs is a zero vector and the
14426 // the zero vector has only one use, we could use a VPERM2X128 to save the
14427 // instruction bytes needed to explicitly generate the zero vector.
14428
14429 // Blends are faster and handle all the non-lane-crossing cases.
14430 if (SDValue Blend = lowerShuffleAsBlend(DL, VT, V1, V2, Mask, Zeroable,
14431 Subtarget, DAG))
14432 return Blend;
14433
14434 // If either input operand is a zero vector, use VPERM2X128 because its mask
14435 // allows us to replace the zero input with an implicit zero.
14436 if (!IsLowZero && !IsHighZero) {
14437 // Check for patterns which can be matched with a single insert of a 128-bit
14438 // subvector.
14439 bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
14440 if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
14441
14442 // With AVX1, use vperm2f128 (below) to allow load folding. Otherwise,
14443 // this will likely become vinsertf128 which can't fold a 256-bit memop.
14444 if (!isa<LoadSDNode>(peekThroughBitcasts(V1))) {
14445 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), 2);
14446 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
14447 OnlyUsesV1 ? V1 : V2,
14448 DAG.getIntPtrConstant(0, DL));
14449 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, V1, SubVec,
14450 DAG.getIntPtrConstant(2, DL));
14451 }
14452 }
14453
14454 // Try to use SHUF128 if possible.
14455 if (Subtarget.hasVLX()) {
14456 if (WidenedMask[0] < 2 && WidenedMask[1] >= 2) {
14457 unsigned PermMask = ((WidenedMask[0] % 2) << 0) |
14458 ((WidenedMask[1] % 2) << 1);
14459 return DAG.getNode(X86ISD::SHUF128, DL, VT, V1, V2,
14460 DAG.getConstant(PermMask, DL, MVT::i8));
14461 }
14462 }
14463 }
14464
14465 // Otherwise form a 128-bit permutation. After accounting for undefs,
14466 // convert the 64-bit shuffle mask selection values into 128-bit
14467 // selection bits by dividing the indexes by 2 and shifting into positions
14468 // defined by a vperm2*128 instruction's immediate control byte.
14469
14470 // The immediate permute control byte looks like this:
14471 // [1:0] - select 128 bits from sources for low half of destination
14472 // [2] - ignore
14473 // [3] - zero low half of destination
14474 // [5:4] - select 128 bits from sources for high half of destination
14475 // [6] - ignore
14476 // [7] - zero high half of destination
14477
14478 assert((WidenedMask[0] >= 0 || IsLowZero) &&(((WidenedMask[0] >= 0 || IsLowZero) && (WidenedMask
[1] >= 0 || IsHighZero) && "Undef half?") ? static_cast
<void> (0) : __assert_fail ("(WidenedMask[0] >= 0 || IsLowZero) && (WidenedMask[1] >= 0 || IsHighZero) && \"Undef half?\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 14479, __PRETTY_FUNCTION__))
14479 (WidenedMask[1] >= 0 || IsHighZero) && "Undef half?")(((WidenedMask[0] >= 0 || IsLowZero) && (WidenedMask
[1] >= 0 || IsHighZero) && "Undef half?") ? static_cast
<void> (0) : __assert_fail ("(WidenedMask[0] >= 0 || IsLowZero) && (WidenedMask[1] >= 0 || IsHighZero) && \"Undef half?\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 14479, __PRETTY_FUNCTION__))
;
14480
14481 unsigned PermMask = 0;
14482 PermMask |= IsLowZero ? 0x08 : (WidenedMask[0] << 0);
14483 PermMask |= IsHighZero ? 0x80 : (WidenedMask[1] << 4);
14484
14485 // Check the immediate mask and replace unused sources with undef.
14486 if ((PermMask & 0x0a) != 0x00 && (PermMask & 0xa0) != 0x00)
14487 V1 = DAG.getUNDEF(VT);
14488 if ((PermMask & 0x0a) != 0x02 && (PermMask & 0xa0) != 0x20)
14489 V2 = DAG.getUNDEF(VT);
14490
14491 return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
14492 DAG.getConstant(PermMask, DL, MVT::i8));
14493}
14494
14495/// Lower a vector shuffle by first fixing the 128-bit lanes and then
14496/// shuffling each lane.
14497///
14498/// This attempts to create a repeated lane shuffle where each lane uses one
14499/// or two of the lanes of the inputs. The lanes of the input vectors are
14500/// shuffled in one or two independent shuffles to get the lanes into the
14501/// position needed by the final shuffle.
14502static SDValue lowerShuffleAsLanePermuteAndRepeatedMask(
14503 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
14504 const X86Subtarget &Subtarget, SelectionDAG &DAG) {
14505 assert(!V2.isUndef() && "This is only useful with multiple inputs.")((!V2.isUndef() && "This is only useful with multiple inputs."
) ? static_cast<void> (0) : __assert_fail ("!V2.isUndef() && \"This is only useful with multiple inputs.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 14505, __PRETTY_FUNCTION__))
;
14506
14507 if (is128BitLaneRepeatedShuffleMask(VT, Mask))
14508 return SDValue();
14509
14510 int Size = Mask.size();
14511 int NumLanes = VT.getSizeInBits() / 128;
14512 int LaneSize = 128 / VT.getScalarSizeInBits();
14513 SmallVector<int, 16> RepeatMask(LaneSize, -1);
14514 SmallVector<std::array<int, 2>, 2> LaneSrcs(NumLanes, {{-1, -1}});
14515
14516 // First pass will try to fill in the RepeatMask from lanes that need two
14517 // sources.
14518 for (int Lane = 0; Lane != NumLanes; ++Lane) {
14519 int Srcs[2] = { -1, -1 };
14520 SmallVector<int, 16> InLaneMask(LaneSize, -1);
14521 for (int i = 0; i != LaneSize; ++i) {
14522 int M = Mask[(Lane * LaneSize) + i];
14523 if (M < 0)
14524 continue;
14525 // Determine which of the possible input lanes (NumLanes from each source)
14526 // this element comes from. Assign that as one of the sources for this
14527 // lane. We can assign up to 2 sources for this lane. If we run out
14528 // sources we can't do anything.
14529 int LaneSrc = M / LaneSize;
14530 int Src;
14531 if (Srcs[0] < 0 || Srcs[0] == LaneSrc)
14532 Src = 0;
14533 else if (Srcs[1] < 0 || Srcs[1] == LaneSrc)
14534 Src = 1;
14535 else
14536 return SDValue();
14537
14538 Srcs[Src] = LaneSrc;
14539 InLaneMask[i] = (M % LaneSize) + Src * Size;
14540 }
14541
14542 // If this lane has two sources, see if it fits with the repeat mask so far.
14543 if (Srcs[1] < 0)
14544 continue;
14545
14546 LaneSrcs[Lane][0] = Srcs[0];
14547 LaneSrcs[Lane][1] = Srcs[1];
14548
14549 auto MatchMasks = [](ArrayRef<int> M1, ArrayRef<int> M2) {
14550 assert(M1.size() == M2.size() && "Unexpected mask size")((M1.size() == M2.size() && "Unexpected mask size") ?
static_cast<void> (0) : __assert_fail ("M1.size() == M2.size() && \"Unexpected mask size\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 14550, __PRETTY_FUNCTION__))
;
14551 for (int i = 0, e = M1.size(); i != e; ++i)
14552 if (M1[i] >= 0 && M2[i] >= 0 && M1[i] != M2[i])
14553 return false;
14554 return true;
14555 };
14556
14557 auto MergeMasks = [](ArrayRef<int> Mask, MutableArrayRef<int> MergedMask) {
14558 assert(Mask.size() == MergedMask.size() && "Unexpected mask size")((Mask.size() == MergedMask.size() && "Unexpected mask size"
) ? static_cast<void> (0) : __assert_fail ("Mask.size() == MergedMask.size() && \"Unexpected mask size\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 14558, __PRETTY_FUNCTION__))
;
14559 for (int i = 0, e = MergedMask.size(); i != e; ++i) {
14560 int M = Mask[i];
14561 if (M < 0)
14562 continue;
14563 assert((MergedMask[i] < 0 || MergedMask[i] == M) &&(((MergedMask[i] < 0 || MergedMask[i] == M) && "Unexpected mask element"
) ? static_cast<void> (0) : __assert_fail ("(MergedMask[i] < 0 || MergedMask[i] == M) && \"Unexpected mask element\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 14564, __PRETTY_FUNCTION__))
14564 "Unexpected mask element")(((MergedMask[i] < 0 || MergedMask[i] == M) && "Unexpected mask element"
) ? static_cast<void> (0) : __assert_fail ("(MergedMask[i] < 0 || MergedMask[i] == M) && \"Unexpected mask element\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 14564, __PRETTY_FUNCTION__))
;
14565 MergedMask[i] = M;
14566 }
14567 };
14568
14569 if (MatchMasks(InLaneMask, RepeatMask)) {
14570 // Merge this lane mask into the final repeat mask.
14571 MergeMasks(InLaneMask, RepeatMask);
14572 continue;
14573 }
14574
14575 // Didn't find a match. Swap the operands and try again.
14576 std::swap(LaneSrcs[Lane][0], LaneSrcs[Lane][1]);
14577 ShuffleVectorSDNode::commuteMask(InLaneMask);
14578
14579 if (MatchMasks(InLaneMask, RepeatMask)) {
14580 // Merge this lane mask into the final repeat mask.
14581 MergeMasks(InLaneMask, RepeatMask);
14582 continue;
14583 }
14584
14585 // Couldn't find a match with the operands in either order.
14586 return SDValue();
14587 }
14588
14589 // Now handle any lanes with only one source.
14590 for (int Lane = 0; Lane != NumLanes; ++Lane) {
14591 // If this lane has already been processed, skip it.
14592 if (LaneSrcs[Lane][0] >= 0)
14593 continue;
14594
14595 for (int i = 0; i != LaneSize; ++i) {
14596 int M = Mask[(Lane * LaneSize) + i];
14597 if (M < 0)
14598 continue;
14599
14600 // If RepeatMask isn't defined yet we can define it ourself.
14601 if (RepeatMask[i] < 0)
14602 RepeatMask[i] = M % LaneSize;
14603
14604 if (RepeatMask[i] < Size) {
14605 if (RepeatMask[i] != M % LaneSize)
14606 return SDValue();
14607 LaneSrcs[Lane][0] = M / LaneSize;
14608 } else {
14609 if (RepeatMask[i] != ((M % LaneSize) + Size))
14610 return SDValue();
14611 LaneSrcs[Lane][1] = M / LaneSize;
14612 }
14613 }
14614
14615 if (LaneSrcs[Lane][0] < 0 && LaneSrcs[Lane][1] < 0)
14616 return SDValue();
14617 }
14618
14619 SmallVector<int, 16> NewMask(Size, -1);
14620 for (int Lane = 0; Lane != NumLanes; ++Lane) {
14621 int Src = LaneSrcs[Lane][0];
14622 for (int i = 0; i != LaneSize; ++i) {
14623 int M = -1;
14624 if (Src >= 0)
14625 M = Src * LaneSize + i;
14626 NewMask[Lane * LaneSize + i] = M;
14627 }
14628 }
14629 SDValue NewV1 = DAG.getVectorShuffle(VT, DL, V1, V2, NewMask);
14630 // Ensure we didn't get back the shuffle we started with.
14631 // FIXME: This is a hack to make up for some splat handling code in
14632 // getVectorShuffle.
14633 if (isa<ShuffleVectorSDNode>(NewV1) &&
14634 cast<ShuffleVectorSDNode>(NewV1)->getMask() == Mask)
14635 return SDValue();
14636
14637 for (int Lane = 0; Lane != NumLanes; ++Lane) {
14638 int Src = LaneSrcs[Lane][1];
14639 for (int i = 0; i != LaneSize; ++i) {
14640 int M = -1;
14641 if (Src >= 0)
14642 M = Src * LaneSize + i;
14643 NewMask[Lane * LaneSize + i] = M;
14644 }
14645 }
14646 SDValue NewV2 = DAG.getVectorShuffle(VT, DL, V1, V2, NewMask);
14647 // Ensure we didn't get back the shuffle we started with.
14648 // FIXME: This is a hack to make up for some splat handling code in
14649 // getVectorShuffle.
14650 if (isa<ShuffleVectorSDNode>(NewV2) &&
14651 cast<ShuffleVectorSDNode>(NewV2)->getMask() == Mask)
14652 return SDValue();
14653
14654 for (int i = 0; i != Size; ++i) {
14655 NewMask[i] = RepeatMask[i % LaneSize];
14656 if (NewMask[i] < 0)
14657 continue;
14658
14659 NewMask[i] += (i / LaneSize) * LaneSize;
14660 }
14661 return DAG.getVectorShuffle(VT, DL, NewV1, NewV2, NewMask);
14662}
14663
14664/// If the input shuffle mask results in a vector that is undefined in all upper
14665/// or lower half elements and that mask accesses only 2 halves of the
14666/// shuffle's operands, return true. A mask of half the width with mask indexes
14667/// adjusted to access the extracted halves of the original shuffle operands is
14668/// returned in HalfMask. HalfIdx1 and HalfIdx2 return whether the upper or
14669/// lower half of each input operand is accessed.
14670static bool
14671getHalfShuffleMask(ArrayRef<int> Mask, MutableArrayRef<int> HalfMask,
14672 int &HalfIdx1, int &HalfIdx2) {
14673 assert((Mask.size() == HalfMask.size() * 2) &&(((Mask.size() == HalfMask.size() * 2) && "Expected input mask to be twice as long as output"
) ? static_cast<void> (0) : __assert_fail ("(Mask.size() == HalfMask.size() * 2) && \"Expected input mask to be twice as long as output\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 14674, __PRETTY_FUNCTION__))
14674 "Expected input mask to be twice as long as output")(((Mask.size() == HalfMask.size() * 2) && "Expected input mask to be twice as long as output"
) ? static_cast<void> (0) : __assert_fail ("(Mask.size() == HalfMask.size() * 2) && \"Expected input mask to be twice as long as output\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 14674, __PRETTY_FUNCTION__))
;
14675
14676 // Exactly one half of the result must be undef to allow narrowing.
14677 bool UndefLower = isUndefLowerHalf(Mask);
14678 bool UndefUpper = isUndefUpperHalf(Mask);
14679 if (UndefLower == UndefUpper)
14680 return false;
14681
14682 unsigned HalfNumElts = HalfMask.size();
14683 unsigned MaskIndexOffset = UndefLower ? HalfNumElts : 0;
14684 HalfIdx1 = -1;
14685 HalfIdx2 = -1;
14686 for (unsigned i = 0; i != HalfNumElts; ++i) {
14687 int M = Mask[i + MaskIndexOffset];
14688 if (M < 0) {
14689 HalfMask[i] = M;
14690 continue;
14691 }
14692
14693 // Determine which of the 4 half vectors this element is from.
14694 // i.e. 0 = Lower V1, 1 = Upper V1, 2 = Lower V2, 3 = Upper V2.
14695 int HalfIdx = M / HalfNumElts;
14696
14697 // Determine the element index into its half vector source.
14698 int HalfElt = M % HalfNumElts;
14699
14700 // We can shuffle with up to 2 half vectors, set the new 'half'
14701 // shuffle mask accordingly.
14702 if (HalfIdx1 < 0 || HalfIdx1 == HalfIdx) {
14703 HalfMask[i] = HalfElt;
14704 HalfIdx1 = HalfIdx;
14705 continue;
14706 }
14707 if (HalfIdx2 < 0 || HalfIdx2 == HalfIdx) {
14708 HalfMask[i] = HalfElt + HalfNumElts;
14709 HalfIdx2 = HalfIdx;
14710 continue;
14711 }
14712
14713 // Too many half vectors referenced.
14714 return false;
14715 }
14716
14717 return true;
14718}
14719
14720/// Given the output values from getHalfShuffleMask(), create a half width
14721/// shuffle of extracted vectors followed by an insert back to full width.
14722static SDValue getShuffleHalfVectors(const SDLoc &DL, SDValue V1, SDValue V2,
14723 ArrayRef<int> HalfMask, int HalfIdx1,
14724 int HalfIdx2, bool UndefLower,
14725 SelectionDAG &DAG) {
14726 assert(V1.getValueType() == V2.getValueType() && "Different sized vectors?")((V1.getValueType() == V2.getValueType() && "Different sized vectors?"
) ? static_cast<void> (0) : __assert_fail ("V1.getValueType() == V2.getValueType() && \"Different sized vectors?\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 14726, __PRETTY_FUNCTION__))
;
14727 assert(V1.getValueType().isSimple() && "Expecting only simple types")((V1.getValueType().isSimple() && "Expecting only simple types"
) ? static_cast<void> (0) : __assert_fail ("V1.getValueType().isSimple() && \"Expecting only simple types\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 14727, __PRETTY_FUNCTION__))
;
14728
14729 MVT VT = V1.getSimpleValueType();
14730 unsigned NumElts = VT.getVectorNumElements();
14731 unsigned HalfNumElts = NumElts / 2;
14732 MVT HalfVT = MVT::getVectorVT(VT.getVectorElementType(), HalfNumElts);
14733
14734 auto getHalfVector = [&](int HalfIdx) {
14735 if (HalfIdx < 0)
14736 return DAG.getUNDEF(HalfVT);
14737 SDValue V = (HalfIdx < 2 ? V1 : V2);
14738 HalfIdx = (HalfIdx % 2) * HalfNumElts;
14739 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V,
14740 DAG.getIntPtrConstant(HalfIdx, DL));
14741 };
14742
14743 // ins undef, (shuf (ext V1, HalfIdx1), (ext V2, HalfIdx2), HalfMask), Offset
14744 SDValue Half1 = getHalfVector(HalfIdx1);
14745 SDValue Half2 = getHalfVector(HalfIdx2);
14746 SDValue V = DAG.getVectorShuffle(HalfVT, DL, Half1, Half2, HalfMask);
14747 unsigned Offset = UndefLower ? HalfNumElts : 0;
14748 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V,
14749 DAG.getIntPtrConstant(Offset, DL));
14750}
14751
14752/// Lower shuffles where an entire half of a 256 or 512-bit vector is UNDEF.
14753/// This allows for fast cases such as subvector extraction/insertion
14754/// or shuffling smaller vector types which can lower more efficiently.
14755static SDValue lowerShuffleWithUndefHalf(const SDLoc &DL, MVT VT, SDValue V1,
14756 SDValue V2, ArrayRef<int> Mask,
14757 const X86Subtarget &Subtarget,
14758 SelectionDAG &DAG) {
14759 assert((VT.is256BitVector() || VT.is512BitVector()) &&(((VT.is256BitVector() || VT.is512BitVector()) && "Expected 256-bit or 512-bit vector"
) ? static_cast<void> (0) : __assert_fail ("(VT.is256BitVector() || VT.is512BitVector()) && \"Expected 256-bit or 512-bit vector\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 14760, __PRETTY_FUNCTION__))
14760 "Expected 256-bit or 512-bit vector")(((VT.is256BitVector() || VT.is512BitVector()) && "Expected 256-bit or 512-bit vector"
) ? static_cast<void> (0) : __assert_fail ("(VT.is256BitVector() || VT.is512BitVector()) && \"Expected 256-bit or 512-bit vector\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 14760, __PRETTY_FUNCTION__))
;
14761
14762 bool UndefLower = isUndefLowerHalf(Mask);
14763 if (!UndefLower && !isUndefUpperHalf(Mask))
14764 return SDValue();
14765
14766 assert((!UndefLower || !isUndefUpperHalf(Mask)) &&(((!UndefLower || !isUndefUpperHalf(Mask)) && "Completely undef shuffle mask should have been simplified already"
) ? static_cast<void> (0) : __assert_fail ("(!UndefLower || !isUndefUpperHalf(Mask)) && \"Completely undef shuffle mask should have been simplified already\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 14767, __PRETTY_FUNCTION__))
14767 "Completely undef shuffle mask should have been simplified already")(((!UndefLower || !isUndefUpperHalf(Mask)) && "Completely undef shuffle mask should have been simplified already"
) ? static_cast<void> (0) : __assert_fail ("(!UndefLower || !isUndefUpperHalf(Mask)) && \"Completely undef shuffle mask should have been simplified already\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 14767, __PRETTY_FUNCTION__))
;
14768
14769 // Upper half is undef and lower half is whole upper subvector.
14770 // e.g. vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
14771 unsigned NumElts = VT.getVectorNumElements();
14772 unsigned HalfNumElts = NumElts / 2;
14773 MVT HalfVT = MVT::getVectorVT(VT.getVectorElementType(), HalfNumElts);
14774 if (!UndefLower &&
14775 isSequentialOrUndefInRange(Mask, 0, HalfNumElts, HalfNumElts)) {
14776 SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
14777 DAG.getIntPtrConstant(HalfNumElts, DL));
14778 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), Hi,
14779 DAG.getIntPtrConstant(0, DL));
14780 }
14781
14782 // Lower half is undef and upper half is whole lower subvector.
14783 // e.g. vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
14784 if (UndefLower &&
14785 isSequentialOrUndefInRange(Mask, HalfNumElts, HalfNumElts, 0)) {
14786 SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
14787 DAG.getIntPtrConstant(0, DL));
14788 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), Hi,
14789 DAG.getIntPtrConstant(HalfNumElts, DL));
14790 }
14791
14792 int HalfIdx1, HalfIdx2;
14793 SmallVector<int, 8> HalfMask(HalfNumElts);
14794 if (!getHalfShuffleMask(Mask, HalfMask, HalfIdx1, HalfIdx2))
14795 return SDValue();
14796
14797 assert(HalfMask.size() == HalfNumElts && "Unexpected shuffle mask length")((HalfMask.size() == HalfNumElts && "Unexpected shuffle mask length"
) ? static_cast<void> (0) : __assert_fail ("HalfMask.size() == HalfNumElts && \"Unexpected shuffle mask length\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 14797, __PRETTY_FUNCTION__))
;
14798
14799 // Only shuffle the halves of the inputs when useful.
14800 unsigned NumLowerHalves =
14801 (HalfIdx1 == 0 || HalfIdx1 == 2) + (HalfIdx2 == 0 || HalfIdx2 == 2);
14802 unsigned NumUpperHalves =
14803 (HalfIdx1 == 1 || HalfIdx1 == 3) + (HalfIdx2 == 1 || HalfIdx2 == 3);
14804 assert(NumLowerHalves + NumUpperHalves <= 2 && "Only 1 or 2 halves allowed")((NumLowerHalves + NumUpperHalves <= 2 && "Only 1 or 2 halves allowed"
) ? static_cast<void> (0) : __assert_fail ("NumLowerHalves + NumUpperHalves <= 2 && \"Only 1 or 2 halves allowed\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 14804, __PRETTY_FUNCTION__))
;
14805
14806 // Determine the larger pattern of undef/halves, then decide if it's worth
14807 // splitting the shuffle based on subtarget capabilities and types.
14808 unsigned EltWidth = VT.getVectorElementType().getSizeInBits();
14809 if (!UndefLower) {
14810 // XXXXuuuu: no insert is needed.
14811 // Always extract lowers when setting lower - these are all free subreg ops.
14812 if (NumUpperHalves == 0)
14813 return getShuffleHalfVectors(DL, V1, V2, HalfMask, HalfIdx1, HalfIdx2,
14814 UndefLower, DAG);
14815
14816 if (NumUpperHalves == 1) {
14817 // AVX2 has efficient 32/64-bit element cross-lane shuffles.
14818 if (Subtarget.hasAVX2()) {
14819 // extract128 + vunpckhps/vshufps, is better than vblend + vpermps.
14820 if (EltWidth == 32 && NumLowerHalves && HalfVT.is128BitVector() &&
14821 !is128BitUnpackShuffleMask(HalfMask) &&
14822 (!isSingleSHUFPSMask(HalfMask) ||
14823 Subtarget.hasFastVariableShuffle()))
14824 return SDValue();
14825 // If this is a unary shuffle (assume that the 2nd operand is
14826 // canonicalized to undef), then we can use vpermpd. Otherwise, we
14827 // are better off extracting the upper half of 1 operand and using a
14828 // narrow shuffle.
14829 if (EltWidth == 64 && V2.isUndef())
14830 return SDValue();
14831 }
14832 // AVX512 has efficient cross-lane shuffles for all legal 512-bit types.
14833 if (Subtarget.hasAVX512() && VT.is512BitVector())
14834 return SDValue();
14835 // Extract + narrow shuffle is better than the wide alternative.
14836 return getShuffleHalfVectors(DL, V1, V2, HalfMask, HalfIdx1, HalfIdx2,
14837 UndefLower, DAG);
14838 }
14839
14840 // Don't extract both uppers, instead shuffle and then extract.
14841 assert(NumUpperHalves == 2 && "Half vector count went wrong")((NumUpperHalves == 2 && "Half vector count went wrong"
) ? static_cast<void> (0) : __assert_fail ("NumUpperHalves == 2 && \"Half vector count went wrong\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 14841, __PRETTY_FUNCTION__))
;
14842 return SDValue();
14843 }
14844
14845 // UndefLower - uuuuXXXX: an insert to high half is required if we split this.
14846 if (NumUpperHalves == 0) {
14847 // AVX2 has efficient 64-bit element cross-lane shuffles.
14848 // TODO: Refine to account for unary shuffle, splat, and other masks?
14849 if (Subtarget.hasAVX2() && EltWidth == 64)
14850 return SDValue();
14851 // AVX512 has efficient cross-lane shuffles for all legal 512-bit types.
14852 if (Subtarget.hasAVX512() && VT.is512BitVector())
14853 return SDValue();
14854 // Narrow shuffle + insert is better than the wide alternative.
14855 return getShuffleHalfVectors(DL, V1, V2, HalfMask, HalfIdx1, HalfIdx2,
14856 UndefLower, DAG);
14857 }
14858
14859 // NumUpperHalves != 0: don't bother with extract, shuffle, and then insert.
14860 return SDValue();
14861}
14862
14863/// Test whether the specified input (0 or 1) is in-place blended by the
14864/// given mask.
14865///
14866/// This returns true if the elements from a particular input are already in the
14867/// slot required by the given mask and require no permutation.
14868static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
14869 assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.")(((Input == 0 || Input == 1) && "Only two inputs to shuffles."
) ? static_cast<void> (0) : __assert_fail ("(Input == 0 || Input == 1) && \"Only two inputs to shuffles.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 14869, __PRETTY_FUNCTION__))
;
14870 int Size = Mask.size();
14871 for (int i = 0; i < Size; ++i)
14872 if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
14873 return false;
14874
14875 return true;
14876}
14877
14878/// Handle case where shuffle sources are coming from the same 128-bit lane and
14879/// every lane can be represented as the same repeating mask - allowing us to
14880/// shuffle the sources with the repeating shuffle and then permute the result
14881/// to the destination lanes.
14882static SDValue lowerShuffleAsRepeatedMaskAndLanePermute(
14883 const SDLoc &DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
14884 const X86Subtarget &Subtarget, SelectionDAG &DAG) {
14885 int NumElts = VT.getVectorNumElements();
14886 int NumLanes = VT.getSizeInBits() / 128;
14887 int NumLaneElts = NumElts / NumLanes;
14888
14889 // On AVX2 we may be able to just shuffle the lowest elements and then
14890 // broadcast the result.
14891 if (Subtarget.hasAVX2()) {
14892 for (unsigned BroadcastSize : {16, 32, 64}) {
14893 if (BroadcastSize <= VT.getScalarSizeInBits())
14894 continue;
14895 int NumBroadcastElts = BroadcastSize / VT.getScalarSizeInBits();
14896
14897 // Attempt to match a repeating pattern every NumBroadcastElts,
14898 // accounting for UNDEFs but only references the lowest 128-bit
14899 // lane of the inputs.
14900 auto FindRepeatingBroadcastMask = [&](SmallVectorImpl<int> &RepeatMask) {
14901 for (int i = 0; i != NumElts; i += NumBroadcastElts)
14902 for (int j = 0; j != NumBroadcastElts; ++j) {
14903 int M = Mask[i + j];
14904 if (M < 0)
14905 continue;
14906 int &R = RepeatMask[j];
14907 if (0 != ((M % NumElts) / NumLaneElts))
14908 return false;
14909 if (0 <= R && R != M)
14910 return false;
14911 R = M;
14912 }
14913 return true;
14914 };
14915
14916 SmallVector<int, 8> RepeatMask((unsigned)NumElts, -1);
14917 if (!FindRepeatingBroadcastMask(RepeatMask))
14918 continue;
14919
14920 // Shuffle the (lowest) repeated elements in place for broadcast.
14921 SDValue RepeatShuf = DAG.getVectorShuffle(VT, DL, V1, V2, RepeatMask);
14922
14923 // Shuffle the actual broadcast.
14924 SmallVector<int, 8> BroadcastMask((unsigned)NumElts, -1);
14925 for (int i = 0; i != NumElts; i += NumBroadcastElts)
14926 for (int j = 0; j != NumBroadcastElts; ++j)
14927 BroadcastMask[i + j] = j;
14928 return DAG.getVectorShuffle(VT, DL, RepeatShuf, DAG.getUNDEF(VT),
14929 BroadcastMask);
14930 }
14931 }
14932
14933 // Bail if the shuffle mask doesn't cross 128-bit lanes.
14934 if (!is128BitLaneCrossingShuffleMask(VT, Mask))
14935 return SDValue();
14936
14937 // Bail if we already have a repeated lane shuffle mask.
14938 SmallVector<int, 8> RepeatedShuffleMask;
14939 if (is128BitLaneRepeatedShuffleMask(VT, Mask, RepeatedShuffleMask))
14940 return SDValue();
14941
14942 // On AVX2 targets we can permute 256-bit vectors as 64-bit sub-lanes
14943 // (with PERMQ/PERMPD), otherwise we can only permute whole 128-bit lanes.
14944 int SubLaneScale = Subtarget.hasAVX2() && VT.is256BitVector() ? 2 : 1;
14945 int NumSubLanes = NumLanes * SubLaneScale;
14946 int NumSubLaneElts = NumLaneElts / SubLaneScale;
14947
14948 // Check that all the sources are coming from the same lane and see if we can
14949 // form a repeating shuffle mask (local to each sub-lane). At the same time,
14950 // determine the source sub-lane for each destination sub-lane.
14951 int TopSrcSubLane = -1;
14952 SmallVector<int, 8> Dst2SrcSubLanes((unsigned)NumSubLanes, -1);
14953 SmallVector<int, 8> RepeatedSubLaneMasks[2] = {
14954 SmallVector<int, 8>((unsigned)NumSubLaneElts, SM_SentinelUndef),
14955 SmallVector<int, 8>((unsigned)NumSubLaneElts, SM_SentinelUndef)};
14956
14957 for (int DstSubLane = 0; DstSubLane != NumSubLanes; ++DstSubLane) {
14958 // Extract the sub-lane mask, check that it all comes from the same lane
14959 // and normalize the mask entries to come from the first lane.
14960 int SrcLane = -1;
14961 SmallVector<int, 8> SubLaneMask((unsigned)NumSubLaneElts, -1);
14962 for (int Elt = 0; Elt != NumSubLaneElts; ++Elt) {
14963 int M = Mask[(DstSubLane * NumSubLaneElts) + Elt];
14964 if (M < 0)
14965 continue;
14966 int Lane = (M % NumElts) / NumLaneElts;
14967 if ((0 <= SrcLane) && (SrcLane != Lane))
14968 return SDValue();
14969 SrcLane = Lane;
14970 int LocalM = (M % NumLaneElts) + (M < NumElts ? 0 : NumElts);
14971 SubLaneMask[Elt] = LocalM;
14972 }
14973
14974 // Whole sub-lane is UNDEF.
14975 if (SrcLane < 0)
14976 continue;
14977
14978 // Attempt to match against the candidate repeated sub-lane masks.
14979 for (int SubLane = 0; SubLane != SubLaneScale; ++SubLane) {
14980 auto MatchMasks = [NumSubLaneElts](ArrayRef<int> M1, ArrayRef<int> M2) {
14981 for (int i = 0; i != NumSubLaneElts; ++i) {
14982 if (M1[i] < 0 || M2[i] < 0)
14983 continue;
14984 if (M1[i] != M2[i])
14985 return false;
14986 }
14987 return true;
14988 };
14989
14990 auto &RepeatedSubLaneMask = RepeatedSubLaneMasks[SubLane];
14991 if (!MatchMasks(SubLaneMask, RepeatedSubLaneMask))
14992 continue;
14993
14994 // Merge the sub-lane mask into the matching repeated sub-lane mask.
14995 for (int i = 0; i != NumSubLaneElts; ++i) {
14996 int M = SubLaneMask[i];
14997 if (M < 0)
14998 continue;
14999 assert((RepeatedSubLaneMask[i] < 0 || RepeatedSubLaneMask[i] == M) &&(((RepeatedSubLaneMask[i] < 0 || RepeatedSubLaneMask[i] ==
M) && "Unexpected mask element") ? static_cast<void
> (0) : __assert_fail ("(RepeatedSubLaneMask[i] < 0 || RepeatedSubLaneMask[i] == M) && \"Unexpected mask element\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 15000, __PRETTY_FUNCTION__))
15000 "Unexpected mask element")(((RepeatedSubLaneMask[i] < 0 || RepeatedSubLaneMask[i] ==
M) && "Unexpected mask element") ? static_cast<void
> (0) : __assert_fail ("(RepeatedSubLaneMask[i] < 0 || RepeatedSubLaneMask[i] == M) && \"Unexpected mask element\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 15000, __PRETTY_FUNCTION__))
;
15001 RepeatedSubLaneMask[i] = M;
15002 }
15003
15004 // Track the top most source sub-lane - by setting the remaining to UNDEF
15005 // we can greatly simplify shuffle matching.
15006 int SrcSubLane = (SrcLane * SubLaneScale) + SubLane;
15007 TopSrcSubLane = std::max(TopSrcSubLane, SrcSubLane);
15008 Dst2SrcSubLanes[DstSubLane] = SrcSubLane;
15009 break;
15010 }
15011
15012 // Bail if we failed to find a matching repeated sub-lane mask.
15013 if (Dst2SrcSubLanes[DstSubLane] < 0)
15014 return SDValue();
15015 }
15016 assert(0 <= TopSrcSubLane && TopSrcSubLane < NumSubLanes &&((0 <= TopSrcSubLane && TopSrcSubLane < NumSubLanes
&& "Unexpected source lane") ? static_cast<void>
(0) : __assert_fail ("0 <= TopSrcSubLane && TopSrcSubLane < NumSubLanes && \"Unexpected source lane\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 15017, __PRETTY_FUNCTION__))
15017 "Unexpected source lane")((0 <= TopSrcSubLane && TopSrcSubLane < NumSubLanes
&& "Unexpected source lane") ? static_cast<void>
(0) : __assert_fail ("0 <= TopSrcSubLane && TopSrcSubLane < NumSubLanes && \"Unexpected source lane\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 15017, __PRETTY_FUNCTION__))
;
15018
15019 // Create a repeating shuffle mask for the entire vector.
15020 SmallVector<int, 8> RepeatedMask((unsigned)NumElts, -1);
15021 for (int SubLane = 0; SubLane <= TopSrcSubLane; ++SubLane) {
15022 int Lane = SubLane / SubLaneScale;
15023 auto &RepeatedSubLaneMask = RepeatedSubLaneMasks[SubLane % SubLaneScale];
15024 for (int Elt = 0; Elt != NumSubLaneElts; ++Elt) {
15025 int M = RepeatedSubLaneMask[Elt];
15026 if (M < 0)
15027 continue;
15028 int Idx = (SubLane * NumSubLaneElts) + Elt;
15029 RepeatedMask[Idx] = M + (Lane * NumLaneElts);
15030 }
15031 }
15032 SDValue RepeatedShuffle = DAG.getVectorShuffle(VT, DL, V1, V2, RepeatedMask);
15033
15034 // Shuffle each source sub-lane to its destination.
15035 SmallVector<int, 8> SubLaneMask((unsigned)NumElts, -1);
15036 for (int i = 0; i != NumElts; i += NumSubLaneElts) {
15037 int SrcSubLane = Dst2SrcSubLanes[i / NumSubLaneElts];
15038 if (SrcSubLane < 0)
15039 continue;
15040 for (int j = 0; j != NumSubLaneElts; ++j)
15041 SubLaneMask[i + j] = j + (SrcSubLane * NumSubLaneElts);
15042 }
15043
15044 return DAG.getVectorShuffle(VT, DL, RepeatedShuffle, DAG.getUNDEF(VT),
15045 SubLaneMask);
15046}
15047
15048static bool matchShuffleWithSHUFPD(MVT VT, SDValue &V1, SDValue &V2,
15049 unsigned &ShuffleImm, ArrayRef<int> Mask) {
15050 int NumElts = VT.getVectorNumElements();
15051 assert(VT.getScalarSizeInBits() == 64 &&((VT.getScalarSizeInBits() == 64 && (NumElts == 2 || NumElts
== 4 || NumElts == 8) && "Unexpected data type for VSHUFPD"
) ? static_cast<void> (0) : __assert_fail ("VT.getScalarSizeInBits() == 64 && (NumElts == 2 || NumElts == 4 || NumElts == 8) && \"Unexpected data type for VSHUFPD\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 15053, __PRETTY_FUNCTION__))
15052 (NumElts == 2 || NumElts == 4 || NumElts == 8) &&((VT.getScalarSizeInBits() == 64 && (NumElts == 2 || NumElts
== 4 || NumElts == 8) && "Unexpected data type for VSHUFPD"
) ? static_cast<void> (0) : __assert_fail ("VT.getScalarSizeInBits() == 64 && (NumElts == 2 || NumElts == 4 || NumElts == 8) && \"Unexpected data type for VSHUFPD\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 15053, __PRETTY_FUNCTION__))
15053 "Unexpected data type for VSHUFPD")((VT.getScalarSizeInBits() == 64 && (NumElts == 2 || NumElts
== 4 || NumElts == 8) && "Unexpected data type for VSHUFPD"
) ? static_cast<void> (0) : __assert_fail ("VT.getScalarSizeInBits() == 64 && (NumElts == 2 || NumElts == 4 || NumElts == 8) && \"Unexpected data type for VSHUFPD\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 15053, __PRETTY_FUNCTION__))
;
15054
15055 // Mask for V8F64: 0/1, 8/9, 2/3, 10/11, 4/5, ..
15056 // Mask for V4F64; 0/1, 4/5, 2/3, 6/7..
15057 ShuffleImm = 0;
15058 bool ShufpdMask = true;
15059 bool CommutableMask = true;
15060 for (int i = 0; i < NumElts; ++i) {
15061 if (Mask[i] == SM_SentinelUndef)
15062 continue;
15063 if (Mask[i] < 0)
15064 return false;
15065 int Val = (i & 6) + NumElts * (i & 1);
15066 int CommutVal = (i & 0xe) + NumElts * ((i & 1) ^ 1);
15067 if (Mask[i] < Val || Mask[i] > Val + 1)
15068 ShufpdMask = false;
15069 if (Mask[i] < CommutVal || Mask[i] > CommutVal + 1)
15070 CommutableMask = false;
15071 ShuffleImm |= (Mask[i] % 2) << i;
15072 }
15073
15074 if (ShufpdMask)
15075 return true;
15076 if (CommutableMask) {
15077 std::swap(V1, V2);
15078 return true;
15079 }
15080
15081 return false;
15082}
15083
15084static SDValue lowerShuffleWithSHUFPD(const SDLoc &DL, MVT VT,
15085 ArrayRef<int> Mask, SDValue V1,
15086 SDValue V2, SelectionDAG &DAG) {
15087 assert((VT == MVT::v2f64 || VT == MVT::v4f64 || VT == MVT::v8f64)&&(((VT == MVT::v2f64 || VT == MVT::v4f64 || VT == MVT::v8f64)&&
"Unexpected data type for VSHUFPD") ? static_cast<void>
(0) : __assert_fail ("(VT == MVT::v2f64 || VT == MVT::v4f64 || VT == MVT::v8f64)&& \"Unexpected data type for VSHUFPD\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 15088, __PRETTY_FUNCTION__))
15088 "Unexpected data type for VSHUFPD")(((VT == MVT::v2f64 || VT == MVT::v4f64 || VT == MVT::v8f64)&&
"Unexpected data type for VSHUFPD") ? static_cast<void>
(0) : __assert_fail ("(VT == MVT::v2f64 || VT == MVT::v4f64 || VT == MVT::v8f64)&& \"Unexpected data type for VSHUFPD\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 15088, __PRETTY_FUNCTION__))
;
15089
15090 unsigned Immediate = 0;
15091 if (!matchShuffleWithSHUFPD(VT, V1, V2, Immediate, Mask))
15092 return SDValue();
15093
15094 return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
15095 DAG.getConstant(Immediate, DL, MVT::i8));
15096}
15097
15098/// Handle lowering of 4-lane 64-bit floating point shuffles.
15099///
15100/// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
15101/// isn't available.
15102static SDValue lowerV4F64Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
15103 const APInt &Zeroable, SDValue V1, SDValue V2,
15104 const X86Subtarget &Subtarget,
15105 SelectionDAG &DAG) {
15106 assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!")((V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!"
) ? static_cast<void> (0) : __assert_fail ("V1.getSimpleValueType() == MVT::v4f64 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 15106, __PRETTY_FUNCTION__))
;
15107 assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!")((V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!"
) ? static_cast<void> (0) : __assert_fail ("V2.getSimpleValueType() == MVT::v4f64 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 15107, __PRETTY_FUNCTION__))
;
15108 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!")((Mask.size() == 4 && "Unexpected mask size for v4 shuffle!"
) ? static_cast<void> (0) : __assert_fail ("Mask.size() == 4 && \"Unexpected mask size for v4 shuffle!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 15108, __PRETTY_FUNCTION__))
;
15109
15110 if (SDValue V = lowerV2X128Shuffle(DL, MVT::v4f64, V1, V2, Mask, Zeroable,
15111 Subtarget, DAG))
15112 return V;
15113
15114 if (V2.isUndef()) {
15115 // Check for being able to broadcast a single element.
15116 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v4f64, V1, V2,
15117 Mask, Subtarget, DAG))
15118 return Broadcast;
15119
15120 // Use low duplicate instructions for masks that match their pattern.
15121 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
15122 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
15123
15124 if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
15125 // Non-half-crossing single input shuffles can be lowered with an
15126 // interleaved permutation.
15127 unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
15128 ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
15129 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
15130 DAG.getConstant(VPERMILPMask, DL, MVT::i8));
15131 }
15132
15133 // With AVX2 we have direct support for this permutation.
15134 if (Subtarget.hasAVX2())
15135 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
15136 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
15137
15138 // Try to create an in-lane repeating shuffle mask and then shuffle the
15139 // results into the target lanes.
15140 if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
15141 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
15142 return V;
15143
15144 // Try to permute the lanes and then use a per-lane permute.
15145 if (SDValue V = lowerShuffleAsLanePermuteAndPermute(DL, MVT::v4f64, V1, V2,
15146 Mask, DAG, Subtarget))
15147 return V;
15148
15149 // Otherwise, fall back.
15150 return lowerShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask, DAG,
15151 Subtarget);
15152 }
15153
15154 // Use dedicated unpack instructions for masks that match their pattern.
15155 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v4f64, Mask, V1, V2, DAG))
15156 return V;
15157
15158 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
15159 Zeroable, Subtarget, DAG))
15160 return Blend;
15161
15162 // Check if the blend happens to exactly fit that of SHUFPD.
15163 if (SDValue Op = lowerShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
15164 return Op;
15165
15166 // If we have one input in place, then we can permute the other input and
15167 // blend the result.
15168 if (isShuffleMaskInputInPlace(0, Mask) || isShuffleMaskInputInPlace(1, Mask))
15169 return lowerShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2, Mask,
15170 Subtarget, DAG);
15171
15172 // Try to create an in-lane repeating shuffle mask and then shuffle the
15173 // results into the target lanes.
15174 if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
15175 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
15176 return V;
15177
15178 // Try to simplify this by merging 128-bit lanes to enable a lane-based
15179 // shuffle. However, if we have AVX2 and either inputs are already in place,
15180 // we will be able to shuffle even across lanes the other input in a single
15181 // instruction so skip this pattern.
15182 if (!(Subtarget.hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
15183 isShuffleMaskInputInPlace(1, Mask))))
15184 if (SDValue V = lowerShuffleAsLanePermuteAndRepeatedMask(
15185 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
15186 return V;
15187
15188 // If we have VLX support, we can use VEXPAND.
15189 if (Subtarget.hasVLX())
15190 if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v4f64, Zeroable, Mask, V1, V2,
15191 DAG, Subtarget))
15192 return V;
15193
15194 // If we have AVX2 then we always want to lower with a blend because an v4 we
15195 // can fully permute the elements.
15196 if (Subtarget.hasAVX2())
15197 return lowerShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2, Mask,
15198 Subtarget, DAG);
15199
15200 // Otherwise fall back on generic lowering.
15201 return lowerShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask,
15202 Subtarget, DAG);
15203}
15204
15205/// Handle lowering of 4-lane 64-bit integer shuffles.
15206///
15207/// This routine is only called when we have AVX2 and thus a reasonable
15208/// instruction set for v4i64 shuffling..
15209static SDValue lowerV4I64Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
15210 const APInt &Zeroable, SDValue V1, SDValue V2,
15211 const X86Subtarget &Subtarget,
15212 SelectionDAG &DAG) {
15213 assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!")((V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!"
) ? static_cast<void> (0) : __assert_fail ("V1.getSimpleValueType() == MVT::v4i64 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 15213, __PRETTY_FUNCTION__))
;
15214 assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!")((V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!"
) ? static_cast<void> (0) : __assert_fail ("V2.getSimpleValueType() == MVT::v4i64 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 15214, __PRETTY_FUNCTION__))
;
15215 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!")((Mask.size() == 4 && "Unexpected mask size for v4 shuffle!"
) ? static_cast<void> (0) : __assert_fail ("Mask.size() == 4 && \"Unexpected mask size for v4 shuffle!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 15215, __PRETTY_FUNCTION__))
;
15216 assert(Subtarget.hasAVX2() && "We can only lower v4i64 with AVX2!")((Subtarget.hasAVX2() && "We can only lower v4i64 with AVX2!"
) ? static_cast<void> (0) : __assert_fail ("Subtarget.hasAVX2() && \"We can only lower v4i64 with AVX2!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 15216, __PRETTY_FUNCTION__))
;
15217
15218 if (SDValue V = lowerV2X128Shuffle(DL, MVT::v4i64, V1, V2, Mask, Zeroable,
15219 Subtarget, DAG))
15220 return V;
15221
15222 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
15223 Zeroable, Subtarget, DAG))
15224 return Blend;
15225
15226 // Check for being able to broadcast a single element.
15227 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v4i64, V1, V2, Mask,
15228 Subtarget, DAG))
15229 return Broadcast;
15230
15231 if (V2.isUndef()) {
15232 // When the shuffle is mirrored between the 128-bit lanes of the unit, we
15233 // can use lower latency instructions that will operate on both lanes.
15234 SmallVector<int, 2> RepeatedMask;
15235 if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
15236 SmallVector<int, 4> PSHUFDMask;
15237 scaleShuffleMask<int>(2, RepeatedMask, PSHUFDMask);
15238 return DAG.getBitcast(
15239 MVT::v4i64,
15240 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
15241 DAG.getBitcast(MVT::v8i32, V1),
15242 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
15243 }
15244
15245 // AVX2 provides a direct instruction for permuting a single input across
15246 // lanes.
15247 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
15248 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
15249 }
15250
15251 // Try to use shift instructions.
15252 if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask,
15253 Zeroable, Subtarget, DAG))
15254 return Shift;
15255
15256 // If we have VLX support, we can use VALIGN or VEXPAND.
15257 if (Subtarget.hasVLX()) {
15258 if (SDValue Rotate = lowerShuffleAsRotate(DL, MVT::v4i64, V1, V2, Mask,
15259 Subtarget, DAG))
15260 return Rotate;
15261
15262 if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v4i64, Zeroable, Mask, V1, V2,
15263 DAG, Subtarget))
15264 return V;
15265 }
15266
15267 // Try to use PALIGNR.
15268 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v4i64, V1, V2, Mask,
15269 Subtarget, DAG))
15270 return Rotate;
15271
15272 // Use dedicated unpack instructions for masks that match their pattern.
15273 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v4i64, Mask, V1, V2, DAG))
15274 return V;
15275
15276 // If we have one input in place, then we can permute the other input and
15277 // blend the result.
15278 if (isShuffleMaskInputInPlace(0, Mask) || isShuffleMaskInputInPlace(1, Mask))
15279 return lowerShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2, Mask,
15280 Subtarget, DAG);
15281
15282 // Try to create an in-lane repeating shuffle mask and then shuffle the
15283 // results into the target lanes.
15284 if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
15285 DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
15286 return V;
15287
15288 // Try to simplify this by merging 128-bit lanes to enable a lane-based
15289 // shuffle. However, if we have AVX2 and either inputs are already in place,
15290 // we will be able to shuffle even across lanes the other input in a single
15291 // instruction so skip this pattern.
15292 if (!isShuffleMaskInputInPlace(0, Mask) &&
15293 !isShuffleMaskInputInPlace(1, Mask))
15294 if (SDValue Result = lowerShuffleAsLanePermuteAndRepeatedMask(
15295 DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
15296 return Result;
15297
15298 // Otherwise fall back on generic blend lowering.
15299 return lowerShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2, Mask,
15300 Subtarget, DAG);
15301}
15302
15303/// Handle lowering of 8-lane 32-bit floating point shuffles.
15304///
15305/// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
15306/// isn't available.
15307static SDValue lowerV8F32Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
15308 const APInt &Zeroable, SDValue V1, SDValue V2,
15309 const X86Subtarget &Subtarget,
15310 SelectionDAG &DAG) {
15311 assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!")((V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!"
) ? static_cast<void> (0) : __assert_fail ("V1.getSimpleValueType() == MVT::v8f32 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 15311, __PRETTY_FUNCTION__))
;
15312 assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!")((V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!"
) ? static_cast<void> (0) : __assert_fail ("V2.getSimpleValueType() == MVT::v8f32 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 15312, __PRETTY_FUNCTION__))
;
15313 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!")((Mask.size() == 8 && "Unexpected mask size for v8 shuffle!"
) ? static_cast<void> (0) : __assert_fail ("Mask.size() == 8 && \"Unexpected mask size for v8 shuffle!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 15313, __PRETTY_FUNCTION__))
;
15314
15315 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
15316 Zeroable, Subtarget, DAG))
15317 return Blend;
15318
15319 // Check for being able to broadcast a single element.
15320 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v8f32, V1, V2, Mask,
15321 Subtarget, DAG))
15322 return Broadcast;
15323
15324 // If the shuffle mask is repeated in each 128-bit lane, we have many more
15325 // options to efficiently lower the shuffle.
15326 SmallVector<int, 4> RepeatedMask;
15327 if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
15328 assert(RepeatedMask.size() == 4 &&((RepeatedMask.size() == 4 && "Repeated masks must be half the mask width!"
) ? static_cast<void> (0) : __assert_fail ("RepeatedMask.size() == 4 && \"Repeated masks must be half the mask width!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 15329, __PRETTY_FUNCTION__))
15329 "Repeated masks must be half the mask width!")((RepeatedMask.size() == 4 && "Repeated masks must be half the mask width!"
) ? static_cast<void> (0) : __assert_fail ("RepeatedMask.size() == 4 && \"Repeated masks must be half the mask width!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 15329, __PRETTY_FUNCTION__))
;
15330
15331 // Use even/odd duplicate instructions for masks that match their pattern.
15332 if (isShuffleEquivalent(V1, V2, RepeatedMask, {0, 0, 2, 2}))
15333 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
15334 if (isShuffleEquivalent(V1, V2, RepeatedMask, {1, 1, 3, 3}))
15335 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
15336
15337 if (V2.isUndef())
15338 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
15339 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
15340
15341 // Use dedicated unpack instructions for masks that match their pattern.
15342 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v8f32, Mask, V1, V2, DAG))
15343 return V;
15344
15345 // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
15346 // have already handled any direct blends.
15347 return lowerShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
15348 }
15349
15350 // Try to create an in-lane repeating shuffle mask and then shuffle the
15351 // results into the target lanes.
15352 if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
15353 DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
15354 return V;
15355
15356 // If we have a single input shuffle with different shuffle patterns in the
15357 // two 128-bit lanes use the variable mask to VPERMILPS.
15358 if (V2.isUndef()) {
15359 SDValue VPermMask = getConstVector(Mask, MVT::v8i32, DAG, DL, true);
15360 if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
15361 return DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v8f32, V1, VPermMask);
15362
15363 if (Subtarget.hasAVX2())
15364 return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8f32, VPermMask, V1);
15365
15366 // Otherwise, fall back.
15367 return lowerShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
15368 DAG, Subtarget);
15369 }
15370
15371 // Try to simplify this by merging 128-bit lanes to enable a lane-based
15372 // shuffle.
15373 if (SDValue Result = lowerShuffleAsLanePermuteAndRepeatedMask(
15374 DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
15375 return Result;
15376
15377 // If we have VLX support, we can use VEXPAND.
15378 if (Subtarget.hasVLX())
15379 if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v8f32, Zeroable, Mask, V1, V2,
15380 DAG, Subtarget))
15381 return V;
15382
15383 // For non-AVX512 if the Mask is of 16bit elements in lane then try to split
15384 // since after split we get a more efficient code using vpunpcklwd and
15385 // vpunpckhwd instrs than vblend.
15386 if (!Subtarget.hasAVX512() && isUnpackWdShuffleMask(Mask, MVT::v8f32))
15387 if (SDValue V = lowerShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask,
15388 Subtarget, DAG))
15389 return V;
15390
15391 // If we have AVX2 then we always want to lower with a blend because at v8 we
15392 // can fully permute the elements.
15393 if (Subtarget.hasAVX2())
15394 return lowerShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2, Mask,
15395 Subtarget, DAG);
15396
15397 // Otherwise fall back on generic lowering.
15398 return lowerShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask,
15399 Subtarget, DAG);
15400}
15401
15402/// Handle lowering of 8-lane 32-bit integer shuffles.
15403///
15404/// This routine is only called when we have AVX2 and thus a reasonable
15405/// instruction set for v8i32 shuffling..
15406static SDValue lowerV8I32Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
15407 const APInt &Zeroable, SDValue V1, SDValue V2,
15408 const X86Subtarget &Subtarget,
15409 SelectionDAG &DAG) {
15410 assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!")((V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!"
) ? static_cast<void> (0) : __assert_fail ("V1.getSimpleValueType() == MVT::v8i32 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 15410, __PRETTY_FUNCTION__))
;
15411 assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!")((V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!"
) ? static_cast<void> (0) : __assert_fail ("V2.getSimpleValueType() == MVT::v8i32 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 15411, __PRETTY_FUNCTION__))
;
15412 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!")((Mask.size() == 8 && "Unexpected mask size for v8 shuffle!"
) ? static_cast<void> (0) : __assert_fail ("Mask.size() == 8 && \"Unexpected mask size for v8 shuffle!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 15412, __PRETTY_FUNCTION__))
;
15413 assert(Subtarget.hasAVX2() && "We can only lower v8i32 with AVX2!")((Subtarget.hasAVX2() && "We can only lower v8i32 with AVX2!"
) ? static_cast<void> (0) : __assert_fail ("Subtarget.hasAVX2() && \"We can only lower v8i32 with AVX2!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 15413, __PRETTY_FUNCTION__))
;
15414
15415 // Whenever we can lower this as a zext, that instruction is strictly faster
15416 // than any alternative. It also allows us to fold memory operands into the
15417 // shuffle in many cases.
15418 if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2, Mask,
15419 Zeroable, Subtarget, DAG))
15420 return ZExt;
15421
15422 // For non-AVX512 if the Mask is of 16bit elements in lane then try to split
15423 // since after split we get a more efficient code than vblend by using
15424 // vpunpcklwd and vpunpckhwd instrs.
15425 if (isUnpackWdShuffleMask(Mask, MVT::v8i32) && !V2.isUndef() &&
15426 !Subtarget.hasAVX512())
15427 if (SDValue V = lowerShuffleAsSplitOrBlend(DL, MVT::v8i32, V1, V2, Mask,
15428 Subtarget, DAG))
15429 return V;
15430
15431 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
15432 Zeroable, Subtarget, DAG))
15433 return Blend;
15434
15435 // Check for being able to broadcast a single element.
15436 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v8i32, V1, V2, Mask,
15437 Subtarget, DAG))
15438 return Broadcast;
15439
15440 // If the shuffle mask is repeated in each 128-bit lane we can use more
15441 // efficient instructions that mirror the shuffles across the two 128-bit
15442 // lanes.
15443 SmallVector<int, 4> RepeatedMask;
15444 bool Is128BitLaneRepeatedShuffle =
15445 is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask);
15446 if (Is128BitLaneRepeatedShuffle) {
15447 assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!")((RepeatedMask.size() == 4 && "Unexpected repeated mask size!"
) ? static_cast<void> (0) : __assert_fail ("RepeatedMask.size() == 4 && \"Unexpected repeated mask size!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 15447, __PRETTY_FUNCTION__))
;
15448 if (V2.isUndef())
15449 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
15450 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
15451
15452 // Use dedicated unpack instructions for masks that match their pattern.
15453 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v8i32, Mask, V1, V2, DAG))
15454 return V;
15455 }
15456
15457 // Try to use shift instructions.
15458 if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask,
15459 Zeroable, Subtarget, DAG))
15460 return Shift;
15461
15462 // If we have VLX support, we can use VALIGN or EXPAND.
15463 if (Subtarget.hasVLX()) {
15464 if (SDValue Rotate = lowerShuffleAsRotate(DL, MVT::v8i32, V1, V2, Mask,
15465 Subtarget, DAG))
15466 return Rotate;
15467
15468 if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v8i32, Zeroable, Mask, V1, V2,
15469 DAG, Subtarget))
15470 return V;
15471 }
15472
15473 // Try to use byte rotation instructions.
15474 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v8i32, V1, V2, Mask,
15475 Subtarget, DAG))
15476 return Rotate;
15477
15478 // Try to create an in-lane repeating shuffle mask and then shuffle the
15479 // results into the target lanes.
15480 if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
15481 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
15482 return V;
15483
15484 // If the shuffle patterns aren't repeated but it is a single input, directly
15485 // generate a cross-lane VPERMD instruction.
15486 if (V2.isUndef()) {
15487 SDValue VPermMask = getConstVector(Mask, MVT::v8i32, DAG, DL, true);
15488 return DAG.getNode(X86ISD::VPERMV, DL, MVT::v8i32, VPermMask, V1);
15489 }
15490
15491 // Assume that a single SHUFPS is faster than an alternative sequence of
15492 // multiple instructions (even if the CPU has a domain penalty).
15493 // If some CPU is harmed by the domain switch, we can fix it in a later pass.
15494 if (Is128BitLaneRepeatedShuffle && isSingleSHUFPSMask(RepeatedMask)) {
15495 SDValue CastV1 = DAG.getBitcast(MVT::v8f32, V1);
15496 SDValue CastV2 = DAG.getBitcast(MVT::v8f32, V2);
15497 SDValue ShufPS = lowerShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask,
15498 CastV1, CastV2, DAG);
15499 return DAG.getBitcast(MVT::v8i32, ShufPS);
15500 }
15501
15502 // Try to simplify this by merging 128-bit lanes to enable a lane-based
15503 // shuffle.
15504 if (SDValue Result = lowerShuffleAsLanePermuteAndRepeatedMask(
15505 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
15506 return Result;
15507
15508 // Otherwise fall back on generic blend lowering.
15509 return lowerShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2, Mask,
15510 Subtarget, DAG);
15511}
15512
15513/// Handle lowering of 16-lane 16-bit integer shuffles.
15514///
15515/// This routine is only called when we have AVX2 and thus a reasonable
15516/// instruction set for v16i16 shuffling..
15517static SDValue lowerV16I16Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
15518 const APInt &Zeroable, SDValue V1, SDValue V2,
15519 const X86Subtarget &Subtarget,
15520 SelectionDAG &DAG) {
15521 assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!")((V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!"
) ? static_cast<void> (0) : __assert_fail ("V1.getSimpleValueType() == MVT::v16i16 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 15521, __PRETTY_FUNCTION__))
;
15522 assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!")((V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!"
) ? static_cast<void> (0) : __assert_fail ("V2.getSimpleValueType() == MVT::v16i16 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 15522, __PRETTY_FUNCTION__))
;
15523 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!")((Mask.size() == 16 && "Unexpected mask size for v16 shuffle!"
) ? static_cast<void> (0) : __assert_fail ("Mask.size() == 16 && \"Unexpected mask size for v16 shuffle!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 15523, __PRETTY_FUNCTION__))
;
15524 assert(Subtarget.hasAVX2() && "We can only lower v16i16 with AVX2!")((Subtarget.hasAVX2() && "We can only lower v16i16 with AVX2!"
) ? static_cast<void> (0) : __assert_fail ("Subtarget.hasAVX2() && \"We can only lower v16i16 with AVX2!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 15524, __PRETTY_FUNCTION__))
;
15525
15526 // Whenever we can lower this as a zext, that instruction is strictly faster
15527 // than any alternative. It also allows us to fold memory operands into the
15528 // shuffle in many cases.
15529 if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(
15530 DL, MVT::v16i16, V1, V2, Mask, Zeroable, Subtarget, DAG))
15531 return ZExt;
15532
15533 // Check for being able to broadcast a single element.
15534 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v16i16, V1, V2, Mask,
15535 Subtarget, DAG))
15536 return Broadcast;
15537
15538 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
15539 Zeroable, Subtarget, DAG))
15540 return Blend;
15541
15542 // Use dedicated unpack instructions for masks that match their pattern.
15543 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16i16, Mask, V1, V2, DAG))
15544 return V;
15545
15546 // Use dedicated pack instructions for masks that match their pattern.
15547 if (SDValue V = lowerShuffleWithPACK(DL, MVT::v16i16, Mask, V1, V2, DAG,
15548 Subtarget))
15549 return V;
15550
15551 // Try to use shift instructions.
15552 if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask,
15553 Zeroable, Subtarget, DAG))
15554 return Shift;
15555
15556 // Try to use byte rotation instructions.
15557 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v16i16, V1, V2, Mask,
15558 Subtarget, DAG))
15559 return Rotate;
15560
15561 // Try to create an in-lane repeating shuffle mask and then shuffle the
15562 // results into the target lanes.
15563 if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
15564 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
15565 return V;
15566
15567 if (V2.isUndef()) {
15568 // There are no generalized cross-lane shuffle operations available on i16
15569 // element types.
15570 if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask)) {
15571 if (SDValue V = lowerShuffleAsLanePermuteAndPermute(
15572 DL, MVT::v16i16, V1, V2, Mask, DAG, Subtarget))
15573 return V;
15574
15575 return lowerShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2, Mask,
15576 DAG, Subtarget);
15577 }
15578
15579 SmallVector<int, 8> RepeatedMask;
15580 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
15581 // As this is a single-input shuffle, the repeated mask should be
15582 // a strictly valid v8i16 mask that we can pass through to the v8i16
15583 // lowering to handle even the v16 case.
15584 return lowerV8I16GeneralSingleInputShuffle(
15585 DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
15586 }
15587 }
15588
15589 if (SDValue PSHUFB = lowerShuffleWithPSHUFB(DL, MVT::v16i16, Mask, V1, V2,
15590 Zeroable, Subtarget, DAG))
15591 return PSHUFB;
15592
15593 // AVX512BWVL can lower to VPERMW.
15594 if (Subtarget.hasBWI() && Subtarget.hasVLX())
15595 return lowerShuffleWithPERMV(DL, MVT::v16i16, Mask, V1, V2, DAG);
15596
15597 // Try to simplify this by merging 128-bit lanes to enable a lane-based
15598 // shuffle.
15599 if (SDValue Result = lowerShuffleAsLanePermuteAndRepeatedMask(
15600 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
15601 return Result;
15602
15603 // Try to permute the lanes and then use a per-lane permute.
15604 if (SDValue V = lowerShuffleAsLanePermuteAndPermute(
15605 DL, MVT::v16i16, V1, V2, Mask, DAG, Subtarget))
15606 return V;
15607
15608 // Otherwise fall back on generic lowering.
15609 return lowerShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask,
15610 Subtarget, DAG);
15611}
15612
15613/// Handle lowering of 32-lane 8-bit integer shuffles.
15614///
15615/// This routine is only called when we have AVX2 and thus a reasonable
15616/// instruction set for v32i8 shuffling..
15617static SDValue lowerV32I8Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
15618 const APInt &Zeroable, SDValue V1, SDValue V2,
15619 const X86Subtarget &Subtarget,
15620 SelectionDAG &DAG) {
15621 assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!")((V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!"
) ? static_cast<void> (0) : __assert_fail ("V1.getSimpleValueType() == MVT::v32i8 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 15621, __PRETTY_FUNCTION__))
;
1
'?' condition is true
15622 assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!")((V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!"
) ? static_cast<void> (0) : __assert_fail ("V2.getSimpleValueType() == MVT::v32i8 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 15622, __PRETTY_FUNCTION__))
;
2
'?' condition is true
15623 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!")((Mask.size() == 32 && "Unexpected mask size for v32 shuffle!"
) ? static_cast<void> (0) : __assert_fail ("Mask.size() == 32 && \"Unexpected mask size for v32 shuffle!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 15623, __PRETTY_FUNCTION__))
;
3
Assuming the condition is true
4
'?' condition is true
15624 assert(Subtarget.hasAVX2() && "We can only lower v32i8 with AVX2!")((Subtarget.hasAVX2() && "We can only lower v32i8 with AVX2!"
) ? static_cast<void> (0) : __assert_fail ("Subtarget.hasAVX2() && \"We can only lower v32i8 with AVX2!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 15624, __PRETTY_FUNCTION__))
;
5
'?' condition is true
15625
15626 // Whenever we can lower this as a zext, that instruction is strictly faster
15627 // than any alternative. It also allows us to fold memory operands into the
15628 // shuffle in many cases.
15629 if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2, Mask,
6
Taking false branch
15630 Zeroable, Subtarget, DAG))
15631 return ZExt;
15632
15633 // Check for being able to broadcast a single element.
15634 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, MVT::v32i8, V1, V2, Mask,
7
Taking false branch
15635 Subtarget, DAG))
15636 return Broadcast;
15637
15638 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
8
Taking false branch
15639 Zeroable, Subtarget, DAG))
15640 return Blend;
15641
15642 // Use dedicated unpack instructions for masks that match their pattern.
15643 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v32i8, Mask, V1, V2, DAG))
9
Taking false branch
15644 return V;
15645
15646 // Use dedicated pack instructions for masks that match their pattern.
15647 if (SDValue V = lowerShuffleWithPACK(DL, MVT::v32i8, Mask, V1, V2, DAG,
10
Taking false branch
15648 Subtarget))
15649 return V;
15650
15651 // Try to use shift instructions.
15652 if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask,
11
Taking false branch
15653 Zeroable, Subtarget, DAG))
15654 return Shift;
15655
15656 // Try to use byte rotation instructions.
15657 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v32i8, V1, V2, Mask,
12
Taking false branch
15658 Subtarget, DAG))
15659 return Rotate;
15660
15661 // Try to create an in-lane repeating shuffle mask and then shuffle the
15662 // results into the target lanes.
15663 if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
13
Taking false branch
15664 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
15665 return V;
15666
15667 // There are no generalized cross-lane shuffle operations available on i8
15668 // element types.
15669 if (V2.isUndef() && is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask)) {
14
Assuming the condition is true
15
Taking true branch
15670 if (SDValue V = lowerShuffleAsLanePermuteAndPermute(
16
Taking false branch
15671 DL, MVT::v32i8, V1, V2, Mask, DAG, Subtarget))
15672 return V;
15673
15674 return lowerShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2, Mask, DAG,
17
Calling 'lowerShuffleAsLanePermuteAndBlend'
15675 Subtarget);
15676 }
15677
15678 if (SDValue PSHUFB = lowerShuffleWithPSHUFB(DL, MVT::v32i8, Mask, V1, V2,
15679 Zeroable, Subtarget, DAG))
15680 return PSHUFB;
15681
15682 // AVX512VBMIVL can lower to VPERMB.
15683 if (Subtarget.hasVBMI() && Subtarget.hasVLX())
15684 return lowerShuffleWithPERMV(DL, MVT::v32i8, Mask, V1, V2, DAG);
15685
15686 // Try to simplify this by merging 128-bit lanes to enable a lane-based
15687 // shuffle.
15688 if (SDValue Result = lowerShuffleAsLanePermuteAndRepeatedMask(
15689 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
15690 return Result;
15691
15692 // Try to permute the lanes and then use a per-lane permute.
15693 if (SDValue V = lowerShuffleAsLanePermuteAndPermute(
15694 DL, MVT::v32i8, V1, V2, Mask, DAG, Subtarget))
15695 return V;
15696
15697 // Otherwise fall back on generic lowering.
15698 return lowerShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask,
15699 Subtarget, DAG);
15700}
15701
15702/// High-level routine to lower various 256-bit x86 vector shuffles.
15703///
15704/// This routine either breaks down the specific type of a 256-bit x86 vector
15705/// shuffle or splits it into two 128-bit shuffles and fuses the results back
15706/// together based on the available instructions.
15707static SDValue lower256BitShuffle(const SDLoc &DL, ArrayRef<int> Mask, MVT VT,
15708 SDValue V1, SDValue V2, const APInt &Zeroable,
15709 const X86Subtarget &Subtarget,
15710 SelectionDAG &DAG) {
15711 // If we have a single input to the zero element, insert that into V1 if we
15712 // can do so cheaply.
15713 int NumElts = VT.getVectorNumElements();
15714 int NumV2Elements = count_if(Mask, [NumElts](int M) { return M >= NumElts; });
15715
15716 if (NumV2Elements == 1 && Mask[0] >= NumElts)
15717 if (SDValue Insertion = lowerShuffleAsElementInsertion(
15718 DL, VT, V1, V2, Mask, Zeroable, Subtarget, DAG))
15719 return Insertion;
15720
15721 // Handle special cases where the lower or upper half is UNDEF.
15722 if (SDValue V =
15723 lowerShuffleWithUndefHalf(DL, VT, V1, V2, Mask, Subtarget, DAG))
15724 return V;
15725
15726 // There is a really nice hard cut-over between AVX1 and AVX2 that means we
15727 // can check for those subtargets here and avoid much of the subtarget
15728 // querying in the per-vector-type lowering routines. With AVX1 we have
15729 // essentially *zero* ability to manipulate a 256-bit vector with integer
15730 // types. Since we'll use floating point types there eventually, just
15731 // immediately cast everything to a float and operate entirely in that domain.
15732 if (VT.isInteger() && !Subtarget.hasAVX2()) {
15733 int ElementBits = VT.getScalarSizeInBits();
15734 if (ElementBits < 32) {
15735 // No floating point type available, if we can't use the bit operations
15736 // for masking/blending then decompose into 128-bit vectors.
15737 if (SDValue V = lowerShuffleAsBitMask(DL, VT, V1, V2, Mask, Zeroable,
15738 Subtarget, DAG))
15739 return V;
15740 if (SDValue V = lowerShuffleAsBitBlend(DL, VT, V1, V2, Mask, DAG))
15741 return V;
15742 return splitAndLowerShuffle(DL, VT, V1, V2, Mask, DAG);
15743 }
15744
15745 MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
15746 VT.getVectorNumElements());
15747 V1 = DAG.getBitcast(FpVT, V1);
15748 V2 = DAG.getBitcast(FpVT, V2);
15749 return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
15750 }
15751
15752 switch (VT.SimpleTy) {
15753 case MVT::v4f64:
15754 return lowerV4F64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
15755 case MVT::v4i64:
15756 return lowerV4I64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
15757 case MVT::v8f32:
15758 return lowerV8F32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
15759 case MVT::v8i32:
15760 return lowerV8I32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
15761 case MVT::v16i16:
15762 return lowerV16I16Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
15763 case MVT::v32i8:
15764 return lowerV32I8Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
15765
15766 default:
15767 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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 15767)
;
15768 }
15769}
15770
15771/// Try to lower a vector shuffle as a 128-bit shuffles.
15772static SDValue lowerV4X128Shuffle(const SDLoc &DL, MVT VT, ArrayRef<int> Mask,
15773 const APInt &Zeroable, SDValue V1, SDValue V2,
15774 const X86Subtarget &Subtarget,
15775 SelectionDAG &DAG) {
15776 assert(VT.getScalarSizeInBits() == 64 &&((VT.getScalarSizeInBits() == 64 && "Unexpected element type size for 128bit shuffle."
) ? static_cast<void> (0) : __assert_fail ("VT.getScalarSizeInBits() == 64 && \"Unexpected element type size for 128bit shuffle.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 15777, __PRETTY_FUNCTION__))
15777 "Unexpected element type size for 128bit shuffle.")((VT.getScalarSizeInBits() == 64 && "Unexpected element type size for 128bit shuffle."
) ? static_cast<void> (0) : __assert_fail ("VT.getScalarSizeInBits() == 64 && \"Unexpected element type size for 128bit shuffle.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 15777, __PRETTY_FUNCTION__))
;
15778
15779 // To handle 256 bit vector requires VLX and most probably
15780 // function lowerV2X128VectorShuffle() is better solution.
15781 assert(VT.is512BitVector() && "Unexpected vector size for 512bit shuffle.")((VT.is512BitVector() && "Unexpected vector size for 512bit shuffle."
) ? static_cast<void> (0) : __assert_fail ("VT.is512BitVector() && \"Unexpected vector size for 512bit shuffle.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 15781, __PRETTY_FUNCTION__))
;
15782
15783 // TODO - use Zeroable like we do for lowerV2X128VectorShuffle?
15784 SmallVector<int, 4> WidenedMask;
15785 if (!canWidenShuffleElements(Mask, WidenedMask))
15786 return SDValue();
15787
15788 // Try to use an insert into a zero vector.
15789 if (WidenedMask[0] == 0 && (Zeroable & 0xf0) == 0xf0 &&
15790 (WidenedMask[1] == 1 || (Zeroable & 0x0c) == 0x0c)) {
15791 unsigned NumElts = ((Zeroable & 0x0c) == 0x0c) ? 2 : 4;
15792 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), NumElts);
15793 SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
15794 DAG.getIntPtrConstant(0, DL));
15795 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
15796 getZeroVector(VT, Subtarget, DAG, DL), LoV,
15797 DAG.getIntPtrConstant(0, DL));
15798 }
15799
15800 // Check for patterns which can be matched with a single insert of a 256-bit
15801 // subvector.
15802 bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask,
15803 {0, 1, 2, 3, 0, 1, 2, 3});
15804 if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask,
15805 {0, 1, 2, 3, 8, 9, 10, 11})) {
15806 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), 4);
15807 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
15808 OnlyUsesV1 ? V1 : V2,
15809 DAG.getIntPtrConstant(0, DL));
15810 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, V1, SubVec,
15811 DAG.getIntPtrConstant(4, DL));
15812 }
15813
15814 assert(WidenedMask.size() == 4)((WidenedMask.size() == 4) ? static_cast<void> (0) : __assert_fail
("WidenedMask.size() == 4", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 15814, __PRETTY_FUNCTION__))
;
15815
15816 // See if this is an insertion of the lower 128-bits of V2 into V1.
15817 bool IsInsert = true;
15818 int V2Index = -1;
15819 for (int i = 0; i < 4; ++i) {
15820 assert(WidenedMask[i] >= -1)((WidenedMask[i] >= -1) ? static_cast<void> (0) : __assert_fail
("WidenedMask[i] >= -1", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 15820, __PRETTY_FUNCTION__))
;
15821 if (WidenedMask[i] < 0)
15822 continue;
15823
15824 // Make sure all V1 subvectors are in place.
15825 if (WidenedMask[i] < 4) {
15826 if (WidenedMask[i] != i) {
15827 IsInsert = false;
15828 break;
15829 }
15830 } else {
15831 // Make sure we only have a single V2 index and its the lowest 128-bits.
15832 if (V2Index >= 0 || WidenedMask[i] != 4) {
15833 IsInsert = false;
15834 break;
15835 }
15836 V2Index = i;
15837 }
15838 }
15839 if (IsInsert && V2Index >= 0) {
15840 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(), 2);
15841 SDValue Subvec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V2,
15842 DAG.getIntPtrConstant(0, DL));
15843 return insert128BitVector(V1, Subvec, V2Index * 2, DAG, DL);
15844 }
15845
15846 // Try to lower to vshuf64x2/vshuf32x4.
15847 SDValue Ops[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT)};
15848 unsigned PermMask = 0;
15849 // Insure elements came from the same Op.
15850 for (int i = 0; i < 4; ++i) {
15851 assert(WidenedMask[i] >= -1)((WidenedMask[i] >= -1) ? static_cast<void> (0) : __assert_fail
("WidenedMask[i] >= -1", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 15851, __PRETTY_FUNCTION__))
;
15852 if (WidenedMask[i] < 0)
15853 continue;
15854
15855 SDValue Op = WidenedMask[i] >= 4 ? V2 : V1;
15856 unsigned OpIndex = i / 2;
15857 if (Ops[OpIndex].isUndef())
15858 Ops[OpIndex] = Op;
15859 else if (Ops[OpIndex] != Op)
15860 return SDValue();
15861
15862 // Convert the 128-bit shuffle mask selection values into 128-bit selection
15863 // bits defined by a vshuf64x2 instruction's immediate control byte.
15864 PermMask |= (WidenedMask[i] % 4) << (i * 2);
15865 }
15866
15867 return DAG.getNode(X86ISD::SHUF128, DL, VT, Ops[0], Ops[1],
15868 DAG.getConstant(PermMask, DL, MVT::i8));
15869}
15870
15871/// Handle lowering of 8-lane 64-bit floating point shuffles.
15872static SDValue lowerV8F64Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
15873 const APInt &Zeroable, SDValue V1, SDValue V2,
15874 const X86Subtarget &Subtarget,
15875 SelectionDAG &DAG) {
15876 assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!")((V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!"
) ? static_cast<void> (0) : __assert_fail ("V1.getSimpleValueType() == MVT::v8f64 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 15876, __PRETTY_FUNCTION__))
;
15877 assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!")((V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!"
) ? static_cast<void> (0) : __assert_fail ("V2.getSimpleValueType() == MVT::v8f64 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 15877, __PRETTY_FUNCTION__))
;
15878 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!")((Mask.size() == 8 && "Unexpected mask size for v8 shuffle!"
) ? static_cast<void> (0) : __assert_fail ("Mask.size() == 8 && \"Unexpected mask size for v8 shuffle!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 15878, __PRETTY_FUNCTION__))
;
15879
15880 if (V2.isUndef()) {
15881 // Use low duplicate instructions for masks that match their pattern.
15882 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
15883 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v8f64, V1);
15884
15885 if (!is128BitLaneCrossingShuffleMask(MVT::v8f64, Mask)) {
15886 // Non-half-crossing single input shuffles can be lowered with an
15887 // interleaved permutation.
15888 unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
15889 ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3) |
15890 ((Mask[4] == 5) << 4) | ((Mask[5] == 5) << 5) |
15891 ((Mask[6] == 7) << 6) | ((Mask[7] == 7) << 7);
15892 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f64, V1,
15893 DAG.getConstant(VPERMILPMask, DL, MVT::i8));
15894 }
15895
15896 SmallVector<int, 4> RepeatedMask;
15897 if (is256BitLaneRepeatedShuffleMask(MVT::v8f64, Mask, RepeatedMask))
15898 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v8f64, V1,
15899 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
15900 }
15901
15902 if (SDValue Shuf128 = lowerV4X128Shuffle(DL, MVT::v8f64, Mask, Zeroable, V1,
15903 V2, Subtarget, DAG))
15904 return Shuf128;
15905
15906 if (SDValue Unpck = lowerShuffleWithUNPCK(DL, MVT::v8f64, Mask, V1, V2, DAG))
15907 return Unpck;
15908
15909 // Check if the blend happens to exactly fit that of SHUFPD.
15910 if (SDValue Op = lowerShuffleWithSHUFPD(DL, MVT::v8f64, Mask, V1, V2, DAG))
15911 return Op;
15912
15913 if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v8f64, Zeroable, Mask, V1, V2,
15914 DAG, Subtarget))
15915 return V;
15916
15917 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8f64, V1, V2, Mask,
15918 Zeroable, Subtarget, DAG))
15919 return Blend;
15920
15921 return lowerShuffleWithPERMV(DL, MVT::v8f64, Mask, V1, V2, DAG);
15922}
15923
15924/// Handle lowering of 16-lane 32-bit floating point shuffles.
15925static SDValue lowerV16F32Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
15926 const APInt &Zeroable, SDValue V1, SDValue V2,
15927 const X86Subtarget &Subtarget,
15928 SelectionDAG &DAG) {
15929 assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!")((V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!"
) ? static_cast<void> (0) : __assert_fail ("V1.getSimpleValueType() == MVT::v16f32 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 15929, __PRETTY_FUNCTION__))
;
15930 assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!")((V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!"
) ? static_cast<void> (0) : __assert_fail ("V2.getSimpleValueType() == MVT::v16f32 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 15930, __PRETTY_FUNCTION__))
;
15931 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!")((Mask.size() == 16 && "Unexpected mask size for v16 shuffle!"
) ? static_cast<void> (0) : __assert_fail ("Mask.size() == 16 && \"Unexpected mask size for v16 shuffle!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 15931, __PRETTY_FUNCTION__))
;
15932
15933 // If the shuffle mask is repeated in each 128-bit lane, we have many more
15934 // options to efficiently lower the shuffle.
15935 SmallVector<int, 4> RepeatedMask;
15936 if (is128BitLaneRepeatedShuffleMask(MVT::v16f32, Mask, RepeatedMask)) {
15937 assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!")((RepeatedMask.size() == 4 && "Unexpected repeated mask size!"
) ? static_cast<void> (0) : __assert_fail ("RepeatedMask.size() == 4 && \"Unexpected repeated mask size!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 15937, __PRETTY_FUNCTION__))
;
15938
15939 // Use even/odd duplicate instructions for masks that match their pattern.
15940 if (isShuffleEquivalent(V1, V2, RepeatedMask, {0, 0, 2, 2}))
15941 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v16f32, V1);
15942 if (isShuffleEquivalent(V1, V2, RepeatedMask, {1, 1, 3, 3}))
15943 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v16f32, V1);
15944
15945 if (V2.isUndef())
15946 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v16f32, V1,
15947 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
15948
15949 // Use dedicated unpack instructions for masks that match their pattern.
15950 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16f32, Mask, V1, V2, DAG))
15951 return V;
15952
15953 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v16f32, V1, V2, Mask,
15954 Zeroable, Subtarget, DAG))
15955 return Blend;
15956
15957 // Otherwise, fall back to a SHUFPS sequence.
15958 return lowerShuffleWithSHUFPS(DL, MVT::v16f32, RepeatedMask, V1, V2, DAG);
15959 }
15960
15961 // If we have a single input shuffle with different shuffle patterns in the
15962 // 128-bit lanes and don't lane cross, use variable mask VPERMILPS.
15963 if (V2.isUndef() &&
15964 !is128BitLaneCrossingShuffleMask(MVT::v16f32, Mask)) {
15965 SDValue VPermMask = getConstVector(Mask, MVT::v16i32, DAG, DL, true);
15966 return DAG.getNode(X86ISD::VPERMILPV, DL, MVT::v16f32, V1, VPermMask);
15967 }
15968
15969 // If we have AVX512F support, we can use VEXPAND.
15970 if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v16f32, Zeroable, Mask,
15971 V1, V2, DAG, Subtarget))
15972 return V;
15973
15974 return lowerShuffleWithPERMV(DL, MVT::v16f32, Mask, V1, V2, DAG);
15975}
15976
15977/// Handle lowering of 8-lane 64-bit integer shuffles.
15978static SDValue lowerV8I64Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
15979 const APInt &Zeroable, SDValue V1, SDValue V2,
15980 const X86Subtarget &Subtarget,
15981 SelectionDAG &DAG) {
15982 assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!")((V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!"
) ? static_cast<void> (0) : __assert_fail ("V1.getSimpleValueType() == MVT::v8i64 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 15982, __PRETTY_FUNCTION__))
;
15983 assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!")((V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!"
) ? static_cast<void> (0) : __assert_fail ("V2.getSimpleValueType() == MVT::v8i64 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 15983, __PRETTY_FUNCTION__))
;
15984 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!")((Mask.size() == 8 && "Unexpected mask size for v8 shuffle!"
) ? static_cast<void> (0) : __assert_fail ("Mask.size() == 8 && \"Unexpected mask size for v8 shuffle!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 15984, __PRETTY_FUNCTION__))
;
15985
15986 if (V2.isUndef()) {
15987 // When the shuffle is mirrored between the 128-bit lanes of the unit, we
15988 // can use lower latency instructions that will operate on all four
15989 // 128-bit lanes.
15990 SmallVector<int, 2> Repeated128Mask;
15991 if (is128BitLaneRepeatedShuffleMask(MVT::v8i64, Mask, Repeated128Mask)) {
15992 SmallVector<int, 4> PSHUFDMask;
15993 scaleShuffleMask<int>(2, Repeated128Mask, PSHUFDMask);
15994 return DAG.getBitcast(
15995 MVT::v8i64,
15996 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v16i32,
15997 DAG.getBitcast(MVT::v16i32, V1),
15998 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
15999 }
16000
16001 SmallVector<int, 4> Repeated256Mask;
16002 if (is256BitLaneRepeatedShuffleMask(MVT::v8i64, Mask, Repeated256Mask))
16003 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v8i64, V1,
16004 getV4X86ShuffleImm8ForMask(Repeated256Mask, DL, DAG));
16005 }
16006
16007 if (SDValue Shuf128 = lowerV4X128Shuffle(DL, MVT::v8i64, Mask, Zeroable, V1,
16008 V2, Subtarget, DAG))
16009 return Shuf128;
16010
16011 // Try to use shift instructions.
16012 if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v8i64, V1, V2, Mask,
16013 Zeroable, Subtarget, DAG))
16014 return Shift;
16015
16016 // Try to use VALIGN.
16017 if (SDValue Rotate = lowerShuffleAsRotate(DL, MVT::v8i64, V1, V2, Mask,
16018 Subtarget, DAG))
16019 return Rotate;
16020
16021 // Try to use PALIGNR.
16022 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v8i64, V1, V2, Mask,
16023 Subtarget, DAG))
16024 return Rotate;
16025
16026 if (SDValue Unpck = lowerShuffleWithUNPCK(DL, MVT::v8i64, Mask, V1, V2, DAG))
16027 return Unpck;
16028 // If we have AVX512F support, we can use VEXPAND.
16029 if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v8i64, Zeroable, Mask, V1, V2,
16030 DAG, Subtarget))
16031 return V;
16032
16033 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v8i64, V1, V2, Mask,
16034 Zeroable, Subtarget, DAG))
16035 return Blend;
16036
16037 return lowerShuffleWithPERMV(DL, MVT::v8i64, Mask, V1, V2, DAG);
16038}
16039
16040/// Handle lowering of 16-lane 32-bit integer shuffles.
16041static SDValue lowerV16I32Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
16042 const APInt &Zeroable, SDValue V1, SDValue V2,
16043 const X86Subtarget &Subtarget,
16044 SelectionDAG &DAG) {
16045 assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!")((V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!"
) ? static_cast<void> (0) : __assert_fail ("V1.getSimpleValueType() == MVT::v16i32 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 16045, __PRETTY_FUNCTION__))
;
16046 assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!")((V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!"
) ? static_cast<void> (0) : __assert_fail ("V2.getSimpleValueType() == MVT::v16i32 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 16046, __PRETTY_FUNCTION__))
;
16047 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!")((Mask.size() == 16 && "Unexpected mask size for v16 shuffle!"
) ? static_cast<void> (0) : __assert_fail ("Mask.size() == 16 && \"Unexpected mask size for v16 shuffle!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 16047, __PRETTY_FUNCTION__))
;
16048
16049 // Whenever we can lower this as a zext, that instruction is strictly faster
16050 // than any alternative. It also allows us to fold memory operands into the
16051 // shuffle in many cases.
16052 if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(
16053 DL, MVT::v16i32, V1, V2, Mask, Zeroable, Subtarget, DAG))
16054 return ZExt;
16055
16056 // If the shuffle mask is repeated in each 128-bit lane we can use more
16057 // efficient instructions that mirror the shuffles across the four 128-bit
16058 // lanes.
16059 SmallVector<int, 4> RepeatedMask;
16060 bool Is128BitLaneRepeatedShuffle =
16061 is128BitLaneRepeatedShuffleMask(MVT::v16i32, Mask, RepeatedMask);
16062 if (Is128BitLaneRepeatedShuffle) {
16063 assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!")((RepeatedMask.size() == 4 && "Unexpected repeated mask size!"
) ? static_cast<void> (0) : __assert_fail ("RepeatedMask.size() == 4 && \"Unexpected repeated mask size!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 16063, __PRETTY_FUNCTION__))
;
16064 if (V2.isUndef())
16065 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v16i32, V1,
16066 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
16067
16068 // Use dedicated unpack instructions for masks that match their pattern.
16069 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v16i32, Mask, V1, V2, DAG))
16070 return V;
16071 }
16072
16073 // Try to use shift instructions.
16074 if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v16i32, V1, V2, Mask,
16075 Zeroable, Subtarget, DAG))
16076 return Shift;
16077
16078 // Try to use VALIGN.
16079 if (SDValue Rotate = lowerShuffleAsRotate(DL, MVT::v16i32, V1, V2, Mask,
16080 Subtarget, DAG))
16081 return Rotate;
16082
16083 // Try to use byte rotation instructions.
16084 if (Subtarget.hasBWI())
16085 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v16i32, V1, V2, Mask,
16086 Subtarget, DAG))
16087 return Rotate;
16088
16089 // Assume that a single SHUFPS is faster than using a permv shuffle.
16090 // If some CPU is harmed by the domain switch, we can fix it in a later pass.
16091 if (Is128BitLaneRepeatedShuffle && isSingleSHUFPSMask(RepeatedMask)) {
16092 SDValue CastV1 = DAG.getBitcast(MVT::v16f32, V1);
16093 SDValue CastV2 = DAG.getBitcast(MVT::v16f32, V2);
16094 SDValue ShufPS = lowerShuffleWithSHUFPS(DL, MVT::v16f32, RepeatedMask,
16095 CastV1, CastV2, DAG);
16096 return DAG.getBitcast(MVT::v16i32, ShufPS);
16097 }
16098 // If we have AVX512F support, we can use VEXPAND.
16099 if (SDValue V = lowerShuffleToEXPAND(DL, MVT::v16i32, Zeroable, Mask, V1, V2,
16100 DAG, Subtarget))
16101 return V;
16102
16103 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v16i32, V1, V2, Mask,
16104 Zeroable, Subtarget, DAG))
16105 return Blend;
16106 return lowerShuffleWithPERMV(DL, MVT::v16i32, Mask, V1, V2, DAG);
16107}
16108
16109/// Handle lowering of 32-lane 16-bit integer shuffles.
16110static SDValue lowerV32I16Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
16111 const APInt &Zeroable, SDValue V1, SDValue V2,
16112 const X86Subtarget &Subtarget,
16113 SelectionDAG &DAG) {
16114 assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!")((V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!"
) ? static_cast<void> (0) : __assert_fail ("V1.getSimpleValueType() == MVT::v32i16 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 16114, __PRETTY_FUNCTION__))
;
16115 assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!")((V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!"
) ? static_cast<void> (0) : __assert_fail ("V2.getSimpleValueType() == MVT::v32i16 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 16115, __PRETTY_FUNCTION__))
;
16116 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!")((Mask.size() == 32 && "Unexpected mask size for v32 shuffle!"
) ? static_cast<void> (0) : __assert_fail ("Mask.size() == 32 && \"Unexpected mask size for v32 shuffle!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 16116, __PRETTY_FUNCTION__))
;
16117 assert(Subtarget.hasBWI() && "We can only lower v32i16 with AVX-512-BWI!")((Subtarget.hasBWI() && "We can only lower v32i16 with AVX-512-BWI!"
) ? static_cast<void> (0) : __assert_fail ("Subtarget.hasBWI() && \"We can only lower v32i16 with AVX-512-BWI!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 16117, __PRETTY_FUNCTION__))
;
16118
16119 // Whenever we can lower this as a zext, that instruction is strictly faster
16120 // than any alternative. It also allows us to fold memory operands into the
16121 // shuffle in many cases.
16122 if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(
16123 DL, MVT::v32i16, V1, V2, Mask, Zeroable, Subtarget, DAG))
16124 return ZExt;
16125
16126 // Use dedicated unpack instructions for masks that match their pattern.
16127 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v32i16, Mask, V1, V2, DAG))
16128 return V;
16129
16130 // Try to use shift instructions.
16131 if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v32i16, V1, V2, Mask,
16132 Zeroable, Subtarget, DAG))
16133 return Shift;
16134
16135 // Try to use byte rotation instructions.
16136 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v32i16, V1, V2, Mask,
16137 Subtarget, DAG))
16138 return Rotate;
16139
16140 if (V2.isUndef()) {
16141 SmallVector<int, 8> RepeatedMask;
16142 if (is128BitLaneRepeatedShuffleMask(MVT::v32i16, Mask, RepeatedMask)) {
16143 // As this is a single-input shuffle, the repeated mask should be
16144 // a strictly valid v8i16 mask that we can pass through to the v8i16
16145 // lowering to handle even the v32 case.
16146 return lowerV8I16GeneralSingleInputShuffle(
16147 DL, MVT::v32i16, V1, RepeatedMask, Subtarget, DAG);
16148 }
16149 }
16150
16151 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v32i16, V1, V2, Mask,
16152 Zeroable, Subtarget, DAG))
16153 return Blend;
16154
16155 if (SDValue PSHUFB = lowerShuffleWithPSHUFB(DL, MVT::v32i16, Mask, V1, V2,
16156 Zeroable, Subtarget, DAG))
16157 return PSHUFB;
16158
16159 return lowerShuffleWithPERMV(DL, MVT::v32i16, Mask, V1, V2, DAG);
16160}
16161
16162/// Handle lowering of 64-lane 8-bit integer shuffles.
16163static SDValue lowerV64I8Shuffle(const SDLoc &DL, ArrayRef<int> Mask,
16164 const APInt &Zeroable, SDValue V1, SDValue V2,
16165 const X86Subtarget &Subtarget,
16166 SelectionDAG &DAG) {
16167 assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!")((V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!"
) ? static_cast<void> (0) : __assert_fail ("V1.getSimpleValueType() == MVT::v64i8 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 16167, __PRETTY_FUNCTION__))
;
16168 assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!")((V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!"
) ? static_cast<void> (0) : __assert_fail ("V2.getSimpleValueType() == MVT::v64i8 && \"Bad operand type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 16168, __PRETTY_FUNCTION__))
;
16169 assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!")((Mask.size() == 64 && "Unexpected mask size for v64 shuffle!"
) ? static_cast<void> (0) : __assert_fail ("Mask.size() == 64 && \"Unexpected mask size for v64 shuffle!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 16169, __PRETTY_FUNCTION__))
;
16170 assert(Subtarget.hasBWI() && "We can only lower v64i8 with AVX-512-BWI!")((Subtarget.hasBWI() && "We can only lower v64i8 with AVX-512-BWI!"
) ? static_cast<void> (0) : __assert_fail ("Subtarget.hasBWI() && \"We can only lower v64i8 with AVX-512-BWI!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 16170, __PRETTY_FUNCTION__))
;
16171
16172 // Whenever we can lower this as a zext, that instruction is strictly faster
16173 // than any alternative. It also allows us to fold memory operands into the
16174 // shuffle in many cases.
16175 if (SDValue ZExt = lowerShuffleAsZeroOrAnyExtend(
16176 DL, MVT::v64i8, V1, V2, Mask, Zeroable, Subtarget, DAG))
16177 return ZExt;
16178
16179 // Use dedicated unpack instructions for masks that match their pattern.
16180 if (SDValue V = lowerShuffleWithUNPCK(DL, MVT::v64i8, Mask, V1, V2, DAG))
16181 return V;
16182
16183 // Use dedicated pack instructions for masks that match their pattern.
16184 if (SDValue V = lowerShuffleWithPACK(DL, MVT::v64i8, Mask, V1, V2, DAG,
16185 Subtarget))
16186 return V;
16187
16188 // Try to use shift instructions.
16189 if (SDValue Shift = lowerShuffleAsShift(DL, MVT::v64i8, V1, V2, Mask,
16190 Zeroable, Subtarget, DAG))
16191 return Shift;
16192
16193 // Try to use byte rotation instructions.
16194 if (SDValue Rotate = lowerShuffleAsByteRotate(DL, MVT::v64i8, V1, V2, Mask,
16195 Subtarget, DAG))
16196 return Rotate;
16197
16198 if (SDValue PSHUFB = lowerShuffleWithPSHUFB(DL, MVT::v64i8, Mask, V1, V2,
16199 Zeroable, Subtarget, DAG))
16200 return PSHUFB;
16201
16202 // VBMI can use VPERMV/VPERMV3 byte shuffles.
16203 if (Subtarget.hasVBMI())
16204 return lowerShuffleWithPERMV(DL, MVT::v64i8, Mask, V1, V2, DAG);
16205
16206 // Try to create an in-lane repeating shuffle mask and then shuffle the
16207 // results into the target lanes.
16208 if (SDValue V = lowerShuffleAsRepeatedMaskAndLanePermute(
16209 DL, MVT::v64i8, V1, V2, Mask, Subtarget, DAG))
16210 return V;
16211
16212 if (SDValue Blend = lowerShuffleAsBlend(DL, MVT::v64i8, V1, V2, Mask,
16213 Zeroable, Subtarget, DAG))
16214 return Blend;
16215
16216 // Try to simplify this by merging 128-bit lanes to enable a lane-based
16217 // shuffle.
16218 if (!V2.isUndef())
16219 if (SDValue Result = lowerShuffleAsLanePermuteAndRepeatedMask(
16220 DL, MVT::v64i8, V1, V2, Mask, Subtarget, DAG))
16221 return Result;
16222
16223 // FIXME: Implement direct support for this type!
16224 return splitAndLowerShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
16225}
16226
16227/// High-level routine to lower various 512-bit x86 vector shuffles.
16228///
16229/// This routine either breaks down the specific type of a 512-bit x86 vector
16230/// shuffle or splits it into two 256-bit shuffles and fuses the results back
16231/// together based on the available instructions.
16232static SDValue lower512BitShuffle(const SDLoc &DL, ArrayRef<int> Mask,
16233 MVT VT, SDValue V1, SDValue V2,
16234 const APInt &Zeroable,
16235 const X86Subtarget &Subtarget,
16236 SelectionDAG &DAG) {
16237 assert(Subtarget.hasAVX512() &&((Subtarget.hasAVX512() && "Cannot lower 512-bit vectors w/ basic ISA!"
) ? static_cast<void> (0) : __assert_fail ("Subtarget.hasAVX512() && \"Cannot lower 512-bit vectors w/ basic ISA!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 16238, __PRETTY_FUNCTION__))
16238 "Cannot lower 512-bit vectors w/ basic ISA!")((Subtarget.hasAVX512() && "Cannot lower 512-bit vectors w/ basic ISA!"
) ? static_cast<void> (0) : __assert_fail ("Subtarget.hasAVX512() && \"Cannot lower 512-bit vectors w/ basic ISA!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 16238, __PRETTY_FUNCTION__))
;
16239
16240 // If we have a single input to the zero element, insert that into V1 if we
16241 // can do so cheaply.
16242 int NumElts = Mask.size();
16243 int NumV2Elements = count_if(Mask, [NumElts](int M) { return M >= NumElts; });
16244
16245 if (NumV2Elements == 1 && Mask[0] >= NumElts)
16246 if (SDValue Insertion = lowerShuffleAsElementInsertion(
16247 DL, VT, V1, V2, Mask, Zeroable, Subtarget, DAG))
16248 return Insertion;
16249
16250 // Handle special cases where the lower or upper half is UNDEF.
16251 if (SDValue V =
16252 lowerShuffleWithUndefHalf(DL, VT, V1, V2, Mask, Subtarget, DAG))
16253 return V;
16254
16255 // Check for being able to broadcast a single element.
16256 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, VT, V1, V2, Mask,
16257 Subtarget, DAG))
16258 return Broadcast;
16259
16260 // Dispatch to each element type for lowering. If we don't have support for
16261 // specific element type shuffles at 512 bits, immediately split them and
16262 // lower them. Each lowering routine of a given type is allowed to assume that
16263 // the requisite ISA extensions for that element type are available.
16264 switch (VT.SimpleTy) {
16265 case MVT::v8f64:
16266 return lowerV8F64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
16267 case MVT::v16f32:
16268 return lowerV16F32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
16269 case MVT::v8i64:
16270 return lowerV8I64Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
16271 case MVT::v16i32:
16272 return lowerV16I32Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
16273 case MVT::v32i16:
16274 return lowerV32I16Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
16275 case MVT::v64i8:
16276 return lowerV64I8Shuffle(DL, Mask, Zeroable, V1, V2, Subtarget, DAG);
16277
16278 default:
16279 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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 16279)
;
16280 }
16281}
16282
16283// Determine if this shuffle can be implemented with a KSHIFT instruction.
16284// Returns the shift amount if possible or -1 if not. This is a simplified
16285// version of matchShuffleAsShift.
16286static int match1BitShuffleAsKSHIFT(unsigned &Opcode, ArrayRef<int> Mask,
16287 int MaskOffset, const APInt &Zeroable) {
16288 int Size = Mask.size();
16289
16290 auto CheckZeros = [&](int Shift, bool Left) {
16291 for (int j = 0; j < Shift; ++j)
16292 if (!Zeroable[j + (Left ? 0 : (Size - Shift))])
16293 return false;
16294
16295 return true;
16296 };
16297
16298 auto MatchShift = [&](int Shift, bool Left) {
16299 unsigned Pos = Left ? Shift : 0;
16300 unsigned Low = Left ? 0 : Shift;
16301 unsigned Len = Size - Shift;
16302 return isSequentialOrUndefInRange(Mask, Pos, Len, Low + MaskOffset);
16303 };
16304
16305 for (int Shift = 1; Shift != Size; ++Shift)
16306 for (bool Left : {true, false})
16307 if (CheckZeros(Shift, Left) && MatchShift(Shift, Left)) {
16308 Opcode = Left ? X86ISD::KSHIFTL : X86ISD::KSHIFTR;
16309 return Shift;
16310 }
16311
16312 return -1;
16313}
16314
16315
16316// Lower vXi1 vector shuffles.
16317// There is no a dedicated instruction on AVX-512 that shuffles the masks.
16318// The only way to shuffle bits is to sign-extend the mask vector to SIMD
16319// vector, shuffle and then truncate it back.
16320static SDValue lower1BitShuffle(const SDLoc &DL, ArrayRef<int> Mask,
16321 MVT VT, SDValue V1, SDValue V2,
16322 const APInt &Zeroable,
16323 const X86Subtarget &Subtarget,
16324 SelectionDAG &DAG) {
16325 assert(Subtarget.hasAVX512() &&((Subtarget.hasAVX512() && "Cannot lower 512-bit vectors w/o basic ISA!"
) ? static_cast<void> (0) : __assert_fail ("Subtarget.hasAVX512() && \"Cannot lower 512-bit vectors w/o basic ISA!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 16326, __PRETTY_FUNCTION__))
16326 "Cannot lower 512-bit vectors w/o basic ISA!")((Subtarget.hasAVX512() && "Cannot lower 512-bit vectors w/o basic ISA!"
) ? static_cast<void> (0) : __assert_fail ("Subtarget.hasAVX512() && \"Cannot lower 512-bit vectors w/o basic ISA!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 16326, __PRETTY_FUNCTION__))
;
16327
16328 unsigned NumElts = Mask.size();
16329
16330 // Try to recognize shuffles that are just padding a subvector with zeros.
16331 unsigned SubvecElts = 0;
16332 for (int i = 0; i != (int)NumElts; ++i) {
16333 if (Mask[i] >= 0 && Mask[i] != i)
16334 break;
16335
16336 ++SubvecElts;
16337 }
16338 assert(SubvecElts != NumElts && "Identity shuffle?")((SubvecElts != NumElts && "Identity shuffle?") ? static_cast
<void> (0) : __assert_fail ("SubvecElts != NumElts && \"Identity shuffle?\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 16338, __PRETTY_FUNCTION__))
;
16339
16340 // Clip to a power 2.
16341 SubvecElts = PowerOf2Floor(SubvecElts);
16342
16343 // Make sure the number of zeroable bits in the top at least covers the bits
16344 // not covered by the subvector.
16345 if (Zeroable.countLeadingOnes() >= (NumElts - SubvecElts)) {
16346 MVT ExtractVT = MVT::getVectorVT(MVT::i1, SubvecElts);
16347 SDValue Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtractVT,
16348 V1, DAG.getIntPtrConstant(0, DL));
16349 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
16350 getZeroVector(VT, Subtarget, DAG, DL),
16351 Extract, DAG.getIntPtrConstant(0, DL));
16352 }
16353
16354 // Try to match KSHIFTs.
16355 // TODO: Support narrower than legal shifts by widening and extracting.
16356 if (NumElts >= 16 || (Subtarget.hasDQI() && NumElts == 8)) {
16357 unsigned Offset = 0;
16358 for (SDValue V : { V1, V2 }) {
16359 unsigned Opcode;
16360 int ShiftAmt = match1BitShuffleAsKSHIFT(Opcode, Mask, Offset, Zeroable);
16361 if (ShiftAmt >= 0)
16362 return DAG.getNode(Opcode, DL, VT, V,
16363 DAG.getConstant(ShiftAmt, DL, MVT::i8));
16364 Offset += NumElts; // Increment for next iteration.
16365 }
16366 }
16367
16368
16369 MVT ExtVT;
16370 switch (VT.SimpleTy) {
16371 default:
16372 llvm_unreachable("Expected a vector of i1 elements")::llvm::llvm_unreachable_internal("Expected a vector of i1 elements"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 16372)
;
16373 case MVT::v2i1:
16374 ExtVT = MVT::v2i64;
16375 break;
16376 case MVT::v4i1:
16377 ExtVT = MVT::v4i32;
16378 break;
16379 case MVT::v8i1:
16380 // Take 512-bit type, more shuffles on KNL. If we have VLX use a 256-bit
16381 // shuffle.
16382 ExtVT = Subtarget.hasVLX() ? MVT::v8i32 : MVT::v8i64;
16383 break;
16384 case MVT::v16i1:
16385 // Take 512-bit type, unless we are avoiding 512-bit types and have the
16386 // 256-bit operation available.
16387 ExtVT = Subtarget.canExtendTo512DQ() ? MVT::v16i32 : MVT::v16i16;
16388 break;
16389 case MVT::v32i1:
16390 // Take 512-bit type, unless we are avoiding 512-bit types and have the
16391 // 256-bit operation available.
16392 assert(Subtarget.hasBWI() && "Expected AVX512BW support")((Subtarget.hasBWI() && "Expected AVX512BW support") ?
static_cast<void> (0) : __assert_fail ("Subtarget.hasBWI() && \"Expected AVX512BW support\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 16392, __PRETTY_FUNCTION__))
;
16393 ExtVT = Subtarget.canExtendTo512BW() ? MVT::v32i16 : MVT::v32i8;
16394 break;
16395 case MVT::v64i1:
16396 ExtVT = MVT::v64i8;
16397 break;
16398 }
16399
16400 V1 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V1);
16401 V2 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V2);
16402
16403 SDValue Shuffle = DAG.getVectorShuffle(ExtVT, DL, V1, V2, Mask);
16404 // i1 was sign extended we can use X86ISD::CVT2MASK.
16405 int NumElems = VT.getVectorNumElements();
16406 if ((Subtarget.hasBWI() && (NumElems >= 32)) ||
16407 (Subtarget.hasDQI() && (NumElems < 32)))
16408 return DAG.getSetCC(DL, VT, DAG.getConstant(0, DL, ExtVT),
16409 Shuffle, ISD::SETGT);
16410
16411 return DAG.getNode(ISD::TRUNCATE, DL, VT, Shuffle);
16412}
16413
16414/// Helper function that returns true if the shuffle mask should be
16415/// commuted to improve canonicalization.
16416static bool canonicalizeShuffleMaskWithCommute(ArrayRef<int> Mask) {
16417 int NumElements = Mask.size();
16418
16419 int NumV1Elements = 0, NumV2Elements = 0;
16420 for (int M : Mask)
16421 if (M < 0)
16422 continue;
16423 else if (M < NumElements)
16424 ++NumV1Elements;
16425 else
16426 ++NumV2Elements;
16427
16428 // Commute the shuffle as needed such that more elements come from V1 than
16429 // V2. This allows us to match the shuffle pattern strictly on how many
16430 // elements come from V1 without handling the symmetric cases.
16431 if (NumV2Elements > NumV1Elements)
16432 return true;
16433
16434 assert(NumV1Elements > 0 && "No V1 indices")((NumV1Elements > 0 && "No V1 indices") ? static_cast
<void> (0) : __assert_fail ("NumV1Elements > 0 && \"No V1 indices\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 16434, __PRETTY_FUNCTION__))
;
16435
16436 if (NumV2Elements == 0)
16437 return false;
16438
16439 // When the number of V1 and V2 elements are the same, try to minimize the
16440 // number of uses of V2 in the low half of the vector. When that is tied,
16441 // ensure that the sum of indices for V1 is equal to or lower than the sum
16442 // indices for V2. When those are equal, try to ensure that the number of odd
16443 // indices for V1 is lower than the number of odd indices for V2.
16444 if (NumV1Elements == NumV2Elements) {
16445 int LowV1Elements = 0, LowV2Elements = 0;
16446 for (int M : Mask.slice(0, NumElements / 2))
16447 if (M >= NumElements)
16448 ++LowV2Elements;
16449 else if (M >= 0)
16450 ++LowV1Elements;
16451 if (LowV2Elements > LowV1Elements)
16452 return true;
16453 if (LowV2Elements == LowV1Elements) {
16454 int SumV1Indices = 0, SumV2Indices = 0;
16455 for (int i = 0, Size = Mask.size(); i < Size; ++i)
16456 if (Mask[i] >= NumElements)
16457 SumV2Indices += i;
16458 else if (Mask[i] >= 0)
16459 SumV1Indices += i;
16460 if (SumV2Indices < SumV1Indices)
16461 return true;
16462 if (SumV2Indices == SumV1Indices) {
16463 int NumV1OddIndices = 0, NumV2OddIndices = 0;
16464 for (int i = 0, Size = Mask.size(); i < Size; ++i)
16465 if (Mask[i] >= NumElements)
16466 NumV2OddIndices += i % 2;
16467 else if (Mask[i] >= 0)
16468 NumV1OddIndices += i % 2;
16469 if (NumV2OddIndices < NumV1OddIndices)
16470 return true;
16471 }
16472 }
16473 }
16474
16475 return false;
16476}
16477
16478/// Top-level lowering for x86 vector shuffles.
16479///
16480/// This handles decomposition, canonicalization, and lowering of all x86
16481/// vector shuffles. Most of the specific lowering strategies are encapsulated
16482/// above in helper routines. The canonicalization attempts to widen shuffles
16483/// to involve fewer lanes of wider elements, consolidate symmetric patterns
16484/// s.t. only one of the two inputs needs to be tested, etc.
16485static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget &Subtarget,
16486 SelectionDAG &DAG) {
16487 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
16488 ArrayRef<int> Mask = SVOp->getMask();
16489 SDValue V1 = Op.getOperand(0);
16490 SDValue V2 = Op.getOperand(1);
16491 MVT VT = Op.getSimpleValueType();
16492 int NumElements = VT.getVectorNumElements();
16493 SDLoc DL(Op);
16494 bool Is1BitVector = (VT.getVectorElementType() == MVT::i1);
16495
16496 assert((VT.getSizeInBits() != 64 || Is1BitVector) &&(((VT.getSizeInBits() != 64 || Is1BitVector) && "Can't lower MMX shuffles"
) ? static_cast<void> (0) : __assert_fail ("(VT.getSizeInBits() != 64 || Is1BitVector) && \"Can't lower MMX shuffles\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 16497, __PRETTY_FUNCTION__))
16497 "Can't lower MMX shuffles")(((VT.getSizeInBits() != 64 || Is1BitVector) && "Can't lower MMX shuffles"
) ? static_cast<void> (0) : __assert_fail ("(VT.getSizeInBits() != 64 || Is1BitVector) && \"Can't lower MMX shuffles\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 16497, __PRETTY_FUNCTION__))
;
16498
16499 bool V1IsUndef = V1.isUndef();
16500 bool V2IsUndef = V2.isUndef();
16501 if (V1IsUndef && V2IsUndef)
16502 return DAG.getUNDEF(VT);
16503
16504 // When we create a shuffle node we put the UNDEF node to second operand,
16505 // but in some cases the first operand may be transformed to UNDEF.
16506 // In this case we should just commute the node.
16507 if (V1IsUndef)
16508 return DAG.getCommutedVectorShuffle(*SVOp);
16509
16510 // Check for non-undef masks pointing at an undef vector and make the masks
16511 // undef as well. This makes it easier to match the shuffle based solely on
16512 // the mask.
16513 if (V2IsUndef &&
16514 any_of(Mask, [NumElements](int M) { return M >= NumElements; })) {
16515 SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
16516 for (int &M : NewMask)
16517 if (M >= NumElements)
16518 M = -1;
16519 return DAG.getVectorShuffle(VT, DL, V1, V2, NewMask);
16520 }
16521
16522 // Check for illegal shuffle mask element index values.
16523 int MaskUpperLimit = Mask.size() * (V2IsUndef ? 1 : 2); (void)MaskUpperLimit;
16524 assert(llvm::all_of(Mask,((llvm::all_of(Mask, [&](int M) { return -1 <= M &&
M < MaskUpperLimit; }) && "Out of bounds shuffle index"
) ? static_cast<void> (0) : __assert_fail ("llvm::all_of(Mask, [&](int M) { return -1 <= M && M < MaskUpperLimit; }) && \"Out of bounds shuffle index\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 16526, __PRETTY_FUNCTION__))
16525 [&](int M) { return -1 <= M && M < MaskUpperLimit; }) &&((llvm::all_of(Mask, [&](int M) { return -1 <= M &&
M < MaskUpperLimit; }) && "Out of bounds shuffle index"
) ? static_cast<void> (0) : __assert_fail ("llvm::all_of(Mask, [&](int M) { return -1 <= M && M < MaskUpperLimit; }) && \"Out of bounds shuffle index\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 16526, __PRETTY_FUNCTION__))
16526 "Out of bounds shuffle index")((llvm::all_of(Mask, [&](int M) { return -1 <= M &&
M < MaskUpperLimit; }) && "Out of bounds shuffle index"
) ? static_cast<void> (0) : __assert_fail ("llvm::all_of(Mask, [&](int M) { return -1 <= M && M < MaskUpperLimit; }) && \"Out of bounds shuffle index\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 16526, __PRETTY_FUNCTION__))
;
16527
16528 // We actually see shuffles that are entirely re-arrangements of a set of
16529 // zero inputs. This mostly happens while decomposing complex shuffles into
16530 // simple ones. Directly lower these as a buildvector of zeros.
16531 APInt Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
16532 if (Zeroable.isAllOnesValue())
16533 return getZeroVector(VT, Subtarget, DAG, DL);
16534
16535 bool V2IsZero = !V2IsUndef && ISD::isBuildVectorAllZeros(V2.getNode());
16536
16537 // Create an alternative mask with info about zeroable elements.
16538 // Here we do not set undef elements as zeroable.
16539 SmallVector<int, 64> ZeroableMask(Mask.begin(), Mask.end());
16540 if (V2IsZero) {
16541 assert(!Zeroable.isNullValue() && "V2's non-undef elements are used?!")((!Zeroable.isNullValue() && "V2's non-undef elements are used?!"
) ? static_cast<void> (0) : __assert_fail ("!Zeroable.isNullValue() && \"V2's non-undef elements are used?!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 16541, __PRETTY_FUNCTION__))
;
16542 for (int i = 0; i != NumElements; ++i)
16543 if (Mask[i] != SM_SentinelUndef && Zeroable[i])
16544 ZeroableMask[i] = SM_SentinelZero;
16545 }
16546
16547 // Try to collapse shuffles into using a vector type with fewer elements but
16548 // wider element types. We cap this to not form integers or floating point
16549 // elements wider than 64 bits, but it might be interesting to form i128
16550 // integers to handle flipping the low and high halves of AVX 256-bit vectors.
16551 SmallVector<int, 16> WidenedMask;
16552 if (VT.getScalarSizeInBits() < 64 && !Is1BitVector &&
16553 canWidenShuffleElements(ZeroableMask, WidenedMask)) {
16554 // Shuffle mask widening should not interfere with a broadcast opportunity
16555 // by obfuscating the operands with bitcasts.
16556 // TODO: Avoid lowering directly from this top-level function: make this
16557 // a query (canLowerAsBroadcast) and defer lowering to the type-based calls.
16558 if (SDValue Broadcast = lowerShuffleAsBroadcast(DL, VT, V1, V2, Mask,
16559 Subtarget, DAG))
16560 return Broadcast;
16561
16562 MVT NewEltVT = VT.isFloatingPoint()
16563 ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
16564 : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
16565 int NewNumElts = NumElements / 2;
16566 MVT NewVT = MVT::getVectorVT(NewEltVT, NewNumElts);
16567 // Make sure that the new vector type is legal. For example, v2f64 isn't
16568 // legal on SSE1.
16569 if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
16570 if (V2IsZero) {
16571 // Modify the new Mask to take all zeros from the all-zero vector.
16572 // Choose indices that are blend-friendly.
16573 bool UsedZeroVector = false;
16574 assert(find(WidenedMask, SM_SentinelZero) != WidenedMask.end() &&((find(WidenedMask, SM_SentinelZero) != WidenedMask.end() &&
"V2's non-undef elements are used?!") ? static_cast<void>
(0) : __assert_fail ("find(WidenedMask, SM_SentinelZero) != WidenedMask.end() && \"V2's non-undef elements are used?!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 16575, __PRETTY_FUNCTION__))
16575 "V2's non-undef elements are used?!")((find(WidenedMask, SM_SentinelZero) != WidenedMask.end() &&
"V2's non-undef elements are used?!") ? static_cast<void>
(0) : __assert_fail ("find(WidenedMask, SM_SentinelZero) != WidenedMask.end() && \"V2's non-undef elements are used?!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 16575, __PRETTY_FUNCTION__))
;
16576 for (int i = 0; i != NewNumElts; ++i)
16577 if (WidenedMask[i] == SM_SentinelZero) {
16578 WidenedMask[i] = i + NewNumElts;
16579 UsedZeroVector = true;
16580 }
16581 // Ensure all elements of V2 are zero - isBuildVectorAllZeros permits
16582 // some elements to be undef.
16583 if (UsedZeroVector)
16584 V2 = getZeroVector(NewVT, Subtarget, DAG, DL);
16585 }
16586 V1 = DAG.getBitcast(NewVT, V1);
16587 V2 = DAG.getBitcast(NewVT, V2);
16588 return DAG.getBitcast(
16589 VT, DAG.getVectorShuffle(NewVT, DL, V1, V2, WidenedMask));
16590 }
16591 }
16592
16593 // Commute the shuffle if it will improve canonicalization.
16594 if (canonicalizeShuffleMaskWithCommute(Mask))
16595 return DAG.getCommutedVectorShuffle(*SVOp);
16596
16597 if (SDValue V = lowerShuffleWithVPMOV(DL, Mask, VT, V1, V2, DAG, Subtarget))
16598 return V;
16599
16600 // For each vector width, delegate to a specialized lowering routine.
16601 if (VT.is128BitVector())
16602 return lower128BitShuffle(DL, Mask, VT, V1, V2, Zeroable, Subtarget, DAG);
16603
16604 if (VT.is256BitVector())
16605 return lower256BitShuffle(DL, Mask, VT, V1, V2, Zeroable, Subtarget, DAG);
16606
16607 if (VT.is512BitVector())
16608 return lower512BitShuffle(DL, Mask, VT, V1, V2, Zeroable, Subtarget, DAG);
16609
16610 if (Is1BitVector)
16611 return lower1BitShuffle(DL, Mask, VT, V1, V2, Zeroable, Subtarget, DAG);
16612
16613 llvm_unreachable("Unimplemented!")::llvm::llvm_unreachable_internal("Unimplemented!", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 16613)
;
16614}
16615
16616/// Try to lower a VSELECT instruction to a vector shuffle.
16617static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
16618 const X86Subtarget &Subtarget,
16619 SelectionDAG &DAG) {
16620 SDValue Cond = Op.getOperand(0);
16621 SDValue LHS = Op.getOperand(1);
16622 SDValue RHS = Op.getOperand(2);
16623 MVT VT = Op.getSimpleValueType();
16624
16625 // Only non-legal VSELECTs reach this lowering, convert those into generic
16626 // shuffles and re-use the shuffle lowering path for blends.
16627 SmallVector<int, 32> Mask;
16628 if (createShuffleMaskFromVSELECT(Mask, Cond))
16629 return DAG.getVectorShuffle(VT, SDLoc(Op), LHS, RHS, Mask);
16630
16631 return SDValue();
16632}
16633
16634SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
16635 SDValue Cond = Op.getOperand(0);
16636 SDValue LHS = Op.getOperand(1);
16637 SDValue RHS = Op.getOperand(2);
16638
16639 // A vselect where all conditions and data are constants can be optimized into
16640 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
16641 if (ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()) &&
16642 ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
16643 ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
16644 return SDValue();
16645
16646 // Try to lower this to a blend-style vector shuffle. This can handle all
16647 // constant condition cases.
16648 if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
16649 return BlendOp;
16650
16651 // If this VSELECT has a vector if i1 as a mask, it will be directly matched
16652 // with patterns on the mask registers on AVX-512.
16653 MVT CondVT = Cond.getSimpleValueType();
16654 unsigned CondEltSize = Cond.getScalarValueSizeInBits();
16655 if (CondEltSize == 1)
16656 return Op;
16657
16658 // Variable blends are only legal from SSE4.1 onward.
16659 if (!Subtarget.hasSSE41())
16660 return SDValue();
16661
16662 SDLoc dl(Op);
16663 MVT VT = Op.getSimpleValueType();
16664 unsigned EltSize = VT.getScalarSizeInBits();
16665 unsigned NumElts = VT.getVectorNumElements();
16666
16667 // If the VSELECT is on a 512-bit type, we have to convert a non-i1 condition
16668 // into an i1 condition so that we can use the mask-based 512-bit blend
16669 // instructions.
16670 if (VT.getSizeInBits() == 512) {
16671 // Build a mask by testing the condition against zero.
16672 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
16673 SDValue Mask = DAG.getSetCC(dl, MaskVT, Cond,
16674 DAG.getConstant(0, dl, CondVT),
16675 ISD::SETNE);
16676 // Now return a new VSELECT using the mask.
16677 return DAG.getSelect(dl, VT, Mask, LHS, RHS);
16678 }
16679
16680 // SEXT/TRUNC cases where the mask doesn't match the destination size.
16681 if (CondEltSize != EltSize) {
16682 // If we don't have a sign splat, rely on the expansion.
16683 if (CondEltSize != DAG.ComputeNumSignBits(Cond))
16684 return SDValue();
16685
16686 MVT NewCondSVT = MVT::getIntegerVT(EltSize);
16687 MVT NewCondVT = MVT::getVectorVT(NewCondSVT, NumElts);
16688 Cond = DAG.getSExtOrTrunc(Cond, dl, NewCondVT);
16689 return DAG.getNode(ISD::VSELECT, dl, VT, Cond, LHS, RHS);
16690 }
16691
16692 // Only some types will be legal on some subtargets. If we can emit a legal
16693 // VSELECT-matching blend, return Op, and but if we need to expand, return
16694 // a null value.
16695 switch (VT.SimpleTy) {
16696 default:
16697 // Most of the vector types have blends past SSE4.1.
16698 return Op;
16699
16700 case MVT::v32i8:
16701 // The byte blends for AVX vectors were introduced only in AVX2.
16702 if (Subtarget.hasAVX2())
16703 return Op;
16704
16705 return SDValue();
16706
16707 case MVT::v8i16:
16708 case MVT::v16i16: {
16709 // Bitcast everything to the vXi8 type and use a vXi8 vselect.
16710 MVT CastVT = MVT::getVectorVT(MVT::i8, NumElts * 2);
16711 Cond = DAG.getBitcast(CastVT, Cond);
16712 LHS = DAG.getBitcast(CastVT, LHS);
16713 RHS = DAG.getBitcast(CastVT, RHS);
16714 SDValue Select = DAG.getNode(ISD::VSELECT, dl, CastVT, Cond, LHS, RHS);
16715 return DAG.getBitcast(VT, Select);
16716 }
16717 }
16718}
16719
16720static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
16721 MVT VT = Op.getSimpleValueType();
16722 SDLoc dl(Op);
16723
16724 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
16725 return SDValue();
16726
16727 if (VT.getSizeInBits() == 8) {
16728 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
16729 Op.getOperand(0), Op.getOperand(1));
16730 return DAG.getNode(ISD::TRUNCATE, dl, VT, Extract);
16731 }
16732
16733 if (VT == MVT::f32) {
16734 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
16735 // the result back to FR32 register. It's only worth matching if the
16736 // result has a single use which is a store or a bitcast to i32. And in
16737 // the case of a store, it's not worth it if the index is a constant 0,
16738 // because a MOVSSmr can be used instead, which is smaller and faster.
16739 if (!Op.hasOneUse())
16740 return SDValue();
16741 SDNode *User = *Op.getNode()->use_begin();
16742 if ((User->getOpcode() != ISD::STORE ||
16743 isNullConstant(Op.getOperand(1))) &&
16744 (User->getOpcode() != ISD::BITCAST ||
16745 User->getValueType(0) != MVT::i32))
16746 return SDValue();
16747 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
16748 DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
16749 Op.getOperand(1));
16750 return DAG.getBitcast(MVT::f32, Extract);
16751 }
16752
16753 if (VT == MVT::i32 || VT == MVT::i64) {
16754 // ExtractPS/pextrq works with constant index.
16755 if (isa<ConstantSDNode>(Op.getOperand(1)))
16756 return Op;
16757 }
16758
16759 return SDValue();
16760}
16761
16762/// Extract one bit from mask vector, like v16i1 or v8i1.
16763/// AVX-512 feature.
16764static SDValue ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG,
16765 const X86Subtarget &Subtarget) {
16766 SDValue Vec = Op.getOperand(0);
16767 SDLoc dl(Vec);
16768 MVT VecVT = Vec.getSimpleValueType();
16769 SDValue Idx = Op.getOperand(1);
16770 MVT EltVT = Op.getSimpleValueType();
16771
16772 assert((VecVT.getVectorNumElements() <= 16 || Subtarget.hasBWI()) &&(((VecVT.getVectorNumElements() <= 16 || Subtarget.hasBWI(
)) && "Unexpected vector type in ExtractBitFromMaskVector"
) ? static_cast<void> (0) : __assert_fail ("(VecVT.getVectorNumElements() <= 16 || Subtarget.hasBWI()) && \"Unexpected vector type in ExtractBitFromMaskVector\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 16773, __PRETTY_FUNCTION__))
16773 "Unexpected vector type in ExtractBitFromMaskVector")(((VecVT.getVectorNumElements() <= 16 || Subtarget.hasBWI(
)) && "Unexpected vector type in ExtractBitFromMaskVector"
) ? static_cast<void> (0) : __assert_fail ("(VecVT.getVectorNumElements() <= 16 || Subtarget.hasBWI()) && \"Unexpected vector type in ExtractBitFromMaskVector\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 16773, __PRETTY_FUNCTION__))
;
16774
16775 // variable index can't be handled in mask registers,
16776 // extend vector to VR512/128
16777 if (!isa<ConstantSDNode>(Idx)) {
16778 unsigned NumElts = VecVT.getVectorNumElements();
16779 // Extending v8i1/v16i1 to 512-bit get better performance on KNL
16780 // than extending to 128/256bit.
16781 MVT ExtEltVT = (NumElts <= 8) ? MVT::getIntegerVT(128 / NumElts) : MVT::i8;
16782 MVT ExtVecVT = MVT::getVectorVT(ExtEltVT, NumElts);
16783 SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, dl, ExtVecVT, Vec);
16784 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ExtEltVT, Ext, Idx);
16785 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
16786 }
16787
16788 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
16789 if (IdxVal == 0) // the operation is legal
16790 return Op;
16791
16792 // Extend to natively supported kshift.
16793 unsigned NumElems = VecVT.getVectorNumElements();
16794 MVT WideVecVT = VecVT;
16795 if ((!Subtarget.hasDQI() && NumElems == 8) || NumElems < 8) {
16796 WideVecVT = Subtarget.hasDQI() ? MVT::v8i1 : MVT::v16i1;
16797 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideVecVT,
16798 DAG.getUNDEF(WideVecVT), Vec,
16799 DAG.getIntPtrConstant(0, dl));
16800 }
16801
16802 // Use kshiftr instruction to move to the lower element.
16803 Vec = DAG.getNode(X86ISD::KSHIFTR, dl, WideVecVT, Vec,
16804 DAG.getConstant(IdxVal, dl, MVT::i8));
16805
16806 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
16807 DAG.getIntPtrConstant(0, dl));
16808}
16809
16810SDValue
16811X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
16812 SelectionDAG &DAG) const {
16813 SDLoc dl(Op);
16814 SDValue Vec = Op.getOperand(0);
16815 MVT VecVT = Vec.getSimpleValueType();
16816 SDValue Idx = Op.getOperand(1);
16817
16818 if (VecVT.getVectorElementType() == MVT::i1)
16819 return ExtractBitFromMaskVector(Op, DAG, Subtarget);
16820
16821 if (!isa<ConstantSDNode>(Idx)) {
16822 // Its more profitable to go through memory (1 cycles throughput)
16823 // than using VMOVD + VPERMV/PSHUFB sequence ( 2/3 cycles throughput)
16824 // IACA tool was used to get performance estimation
16825 // (https://software.intel.com/en-us/articles/intel-architecture-code-analyzer)
16826 //
16827 // example : extractelement <16 x i8> %a, i32 %i
16828 //
16829 // Block Throughput: 3.00 Cycles
16830 // Throughput Bottleneck: Port5
16831 //
16832 // | Num Of | Ports pressure in cycles | |
16833 // | Uops | 0 - DV | 5 | 6 | 7 | |
16834 // ---------------------------------------------
16835 // | 1 | | 1.0 | | | CP | vmovd xmm1, edi
16836 // | 1 | | 1.0 | | | CP | vpshufb xmm0, xmm0, xmm1
16837 // | 2 | 1.0 | 1.0 | | | CP | vpextrb eax, xmm0, 0x0
16838 // Total Num Of Uops: 4
16839 //
16840 //
16841 // Block Throughput: 1.00 Cycles
16842 // Throughput Bottleneck: PORT2_AGU, PORT3_AGU, Port4
16843 //
16844 // | | Ports pressure in cycles | |
16845 // |Uops| 1 | 2 - D |3 - D | 4 | 5 | |
16846 // ---------------------------------------------------------
16847 // |2^ | | 0.5 | 0.5 |1.0| |CP| vmovaps xmmword ptr [rsp-0x18], xmm0
16848 // |1 |0.5| | | |0.5| | lea rax, ptr [rsp-0x18]
16849 // |1 | |0.5, 0.5|0.5, 0.5| | |CP| mov al, byte ptr [rdi+rax*1]
16850 // Total Num Of Uops: 4
16851
16852 return SDValue();
16853 }
16854
16855 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
16856
16857 // If this is a 256-bit vector result, first extract the 128-bit vector and
16858 // then extract the element from the 128-bit vector.
16859 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
16860 // Get the 128-bit vector.
16861 Vec = extract128BitVector(Vec, IdxVal, DAG, dl);
16862 MVT EltVT = VecVT.getVectorElementType();
16863
16864 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
16865 assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2")((isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2"
) ? static_cast<void> (0) : __assert_fail ("isPowerOf2_32(ElemsPerChunk) && \"Elements per chunk not power of 2\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 16865, __PRETTY_FUNCTION__))
;
16866
16867 // Find IdxVal modulo ElemsPerChunk. Since ElemsPerChunk is a power of 2
16868 // this can be done with a mask.
16869 IdxVal &= ElemsPerChunk - 1;
16870 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
16871 DAG.getConstant(IdxVal, dl, MVT::i32));
16872 }
16873
16874 assert(VecVT.is128BitVector() && "Unexpected vector length")((VecVT.is128BitVector() && "Unexpected vector length"
) ? static_cast<void> (0) : __assert_fail ("VecVT.is128BitVector() && \"Unexpected vector length\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 16874, __PRETTY_FUNCTION__))
;
16875
16876 MVT VT = Op.getSimpleValueType();
16877
16878 if (VT.getSizeInBits() == 16) {
16879 // If IdxVal is 0, it's cheaper to do a move instead of a pextrw, unless
16880 // we're going to zero extend the register or fold the store (SSE41 only).
16881 if (IdxVal == 0 && !MayFoldIntoZeroExtend(Op) &&
16882 !(Subtarget.hasSSE41() && MayFoldIntoStore(Op)))
16883 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
16884 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
16885 DAG.getBitcast(MVT::v4i32, Vec), Idx));
16886
16887 // Transform it so it match pextrw which produces a 32-bit result.
16888 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
16889 Op.getOperand(0), Op.getOperand(1));
16890 return DAG.getNode(ISD::TRUNCATE, dl, VT, Extract);
16891 }
16892
16893 if (Subtarget.hasSSE41())
16894 if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
16895 return Res;
16896
16897 // TODO: We only extract a single element from v16i8, we can probably afford
16898 // to be more aggressive here before using the default approach of spilling to
16899 // stack.
16900 if (VT.getSizeInBits() == 8 && Op->isOnlyUserOf(Vec.getNode())) {
16901 // Extract either the lowest i32 or any i16, and extract the sub-byte.
16902 int DWordIdx = IdxVal / 4;
16903 if (DWordIdx == 0) {
16904 SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
16905 DAG.getBitcast(MVT::v4i32, Vec),
16906 DAG.getIntPtrConstant(DWordIdx, dl));
16907 int ShiftVal = (IdxVal % 4) * 8;
16908 if (ShiftVal != 0)
16909 Res = DAG.getNode(ISD::SRL, dl, MVT::i32, Res,
16910 DAG.getConstant(ShiftVal, dl, MVT::i8));
16911 return DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
16912 }
16913
16914 int WordIdx = IdxVal / 2;
16915 SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
16916 DAG.getBitcast(MVT::v8i16, Vec),
16917 DAG.getIntPtrConstant(WordIdx, dl));
16918 int ShiftVal = (IdxVal % 2) * 8;
16919 if (ShiftVal != 0)
16920 Res = DAG.getNode(ISD::SRL, dl, MVT::i16, Res,
16921 DAG.getConstant(ShiftVal, dl, MVT::i8));
16922 return DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
16923 }
16924
16925 if (VT.getSizeInBits() == 32) {
16926 if (IdxVal == 0)
16927 return Op;
16928
16929 // SHUFPS the element to the lowest double word, then movss.
16930 int Mask[4] = { static_cast<int>(IdxVal), -1, -1, -1 };
16931 Vec = DAG.getVectorShuffle(VecVT, dl, Vec, DAG.getUNDEF(VecVT), Mask);
16932 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
16933 DAG.getIntPtrConstant(0, dl));
16934 }
16935
16936 if (VT.getSizeInBits() == 64) {
16937 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
16938 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
16939 // to match extract_elt for f64.
16940 if (IdxVal == 0)
16941 return Op;
16942
16943 // UNPCKHPD the element to the lowest double word, then movsd.
16944 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
16945 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
16946 int Mask[2] = { 1, -1 };
16947 Vec = DAG.getVectorShuffle(VecVT, dl, Vec, DAG.getUNDEF(VecVT), Mask);
16948 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
16949 DAG.getIntPtrConstant(0, dl));
16950 }
16951
16952 return SDValue();
16953}
16954
16955/// Insert one bit to mask vector, like v16i1 or v8i1.
16956/// AVX-512 feature.
16957static SDValue InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG,
16958 const X86Subtarget &Subtarget) {
16959 SDLoc dl(Op);
16960 SDValue Vec = Op.getOperand(0);
16961 SDValue Elt = Op.getOperand(1);
16962 SDValue Idx = Op.getOperand(2);
16963 MVT VecVT = Vec.getSimpleValueType();
16964
16965 if (!isa<ConstantSDNode>(Idx)) {
16966 // Non constant index. Extend source and destination,
16967 // insert element and then truncate the result.
16968 unsigned NumElts = VecVT.getVectorNumElements();
16969 MVT ExtEltVT = (NumElts <= 8) ? MVT::getIntegerVT(128 / NumElts) : MVT::i8;
16970 MVT ExtVecVT = MVT::getVectorVT(ExtEltVT, NumElts);
16971 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
16972 DAG.getNode(ISD::SIGN_EXTEND, dl, ExtVecVT, Vec),
16973 DAG.getNode(ISD::SIGN_EXTEND, dl, ExtEltVT, Elt), Idx);
16974 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
16975 }
16976
16977 // Copy into a k-register, extract to v1i1 and insert_subvector.
16978 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i1, Elt);
16979
16980 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, VecVT, Vec, EltInVec,
16981 Op.getOperand(2));
16982}
16983
16984SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
16985 SelectionDAG &DAG) const {
16986 MVT VT = Op.getSimpleValueType();
16987 MVT EltVT = VT.getVectorElementType();
16988 unsigned NumElts = VT.getVectorNumElements();
16989
16990 if (EltVT == MVT::i1)
16991 return InsertBitToMaskVector(Op, DAG, Subtarget);
16992
16993 SDLoc dl(Op);
16994 SDValue N0 = Op.getOperand(0);
16995 SDValue N1 = Op.getOperand(1);
16996 SDValue N2 = Op.getOperand(2);
16997 if (!isa<ConstantSDNode>(N2))
16998 return SDValue();
16999 auto *N2C = cast<ConstantSDNode>(N2);
17000 unsigned IdxVal = N2C->getZExtValue();
17001
17002 bool IsZeroElt = X86::isZeroNode(N1);
17003 bool IsAllOnesElt = VT.isInteger() && llvm::isAllOnesConstant(N1);
17004
17005 // If we are inserting a element, see if we can do this more efficiently with
17006 // a blend shuffle with a rematerializable vector than a costly integer
17007 // insertion.
17008 if ((IsZeroElt || IsAllOnesElt) && Subtarget.hasSSE41() &&
17009 16 <= EltVT.getSizeInBits()) {
17010 SmallVector<int, 8> BlendMask;
17011 for (unsigned i = 0; i != NumElts; ++i)
17012 BlendMask.push_back(i == IdxVal ? i + NumElts : i);
17013 SDValue CstVector = IsZeroElt ? getZeroVector(VT, Subtarget, DAG, dl)
17014 : getOnesVector(VT, DAG, dl);
17015 return DAG.getVectorShuffle(VT, dl, N0, CstVector, BlendMask);
17016 }
17017
17018 // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
17019 // into that, and then insert the subvector back into the result.
17020 if (VT.is256BitVector() || VT.is512BitVector()) {
17021 // With a 256-bit vector, we can insert into the zero element efficiently
17022 // using a blend if we have AVX or AVX2 and the right data type.
17023 if (VT.is256BitVector() && IdxVal == 0) {
17024 // TODO: It is worthwhile to cast integer to floating point and back
17025 // and incur a domain crossing penalty if that's what we'll end up
17026 // doing anyway after extracting to a 128-bit vector.
17027 if ((Subtarget.hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
17028 (Subtarget.hasAVX2() && EltVT == MVT::i32)) {
17029 SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
17030 N2 = DAG.getIntPtrConstant(1, dl);
17031 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
17032 }
17033 }
17034
17035 // Get the desired 128-bit vector chunk.
17036 SDValue V = extract128BitVector(N0, IdxVal, DAG, dl);
17037
17038 // Insert the element into the desired chunk.
17039 unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
17040 assert(isPowerOf2_32(NumEltsIn128))((isPowerOf2_32(NumEltsIn128)) ? static_cast<void> (0) :
__assert_fail ("isPowerOf2_32(NumEltsIn128)", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 17040, __PRETTY_FUNCTION__))
;
17041 // Since NumEltsIn128 is a power of 2 we can use mask instead of modulo.
17042 unsigned IdxIn128 = IdxVal & (NumEltsIn128 - 1);
17043
17044 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
17045 DAG.getConstant(IdxIn128, dl, MVT::i32));
17046
17047 // Insert the changed part back into the bigger vector
17048 return insert128BitVector(N0, V, IdxVal, DAG, dl);
17049 }
17050 assert(VT.is128BitVector() && "Only 128-bit vector types should be left!")((VT.is128BitVector() && "Only 128-bit vector types should be left!"
) ? static_cast<void> (0) : __assert_fail ("VT.is128BitVector() && \"Only 128-bit vector types should be left!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 17050, __PRETTY_FUNCTION__))
;
17051
17052 // This will be just movd/movq/movss/movsd.
17053 if (IdxVal == 0 && ISD::isBuildVectorAllZeros(N0.getNode()) &&
17054 (EltVT == MVT::i32 || EltVT == MVT::f32 || EltVT == MVT::f64 ||
17055 EltVT == MVT::i64)) {
17056 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
17057 return getShuffleVectorZeroOrUndef(N1, 0, true, Subtarget, DAG);
17058 }
17059
17060 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
17061 // argument. SSE41 required for pinsrb.
17062 if (VT == MVT::v8i16 || (VT == MVT::v16i8 && Subtarget.hasSSE41())) {
17063 unsigned Opc;
17064 if (VT == MVT::v8i16) {
17065 assert(Subtarget.hasSSE2() && "SSE2 required for PINSRW")((Subtarget.hasSSE2() && "SSE2 required for PINSRW") ?
static_cast<void> (0) : __assert_fail ("Subtarget.hasSSE2() && \"SSE2 required for PINSRW\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 17065, __PRETTY_FUNCTION__))
;
17066 Opc = X86ISD::PINSRW;
17067 } else {
17068 assert(VT == MVT::v16i8 && "PINSRB requires v16i8 vector")((VT == MVT::v16i8 && "PINSRB requires v16i8 vector")
? static_cast<void> (0) : __assert_fail ("VT == MVT::v16i8 && \"PINSRB requires v16i8 vector\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 17068, __PRETTY_FUNCTION__))
;
17069 assert(Subtarget.hasSSE41() && "SSE41 required for PINSRB")((Subtarget.hasSSE41() && "SSE41 required for PINSRB"
) ? static_cast<void> (0) : __assert_fail ("Subtarget.hasSSE41() && \"SSE41 required for PINSRB\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 17069, __PRETTY_FUNCTION__))
;
17070 Opc = X86ISD::PINSRB;
17071 }
17072
17073 if (N1.getValueType() != MVT::i32)
17074 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
17075 if (N2.getValueType() != MVT::i32)
17076 N2 = DAG.getIntPtrConstant(IdxVal, dl);
17077 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
17078 }
17079
17080 if (Subtarget.hasSSE41()) {
17081 if (EltVT == MVT::f32) {
17082 // Bits [7:6] of the constant are the source select. This will always be
17083 // zero here. The DAG Combiner may combine an extract_elt index into
17084 // these bits. For example (insert (extract, 3), 2) could be matched by
17085 // putting the '3' into bits [7:6] of X86ISD::INSERTPS.
17086 // Bits [5:4] of the constant are the destination select. This is the
17087 // value of the incoming immediate.
17088 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
17089 // combine either bitwise AND or insert of float 0.0 to set these bits.
17090
17091 bool MinSize = DAG.getMachineFunction().getFunction().hasMinSize();
17092 if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
17093 // If this is an insertion of 32-bits into the low 32-bits of
17094 // a vector, we prefer to generate a blend with immediate rather
17095 // than an insertps. Blends are simpler operations in hardware and so
17096 // will always have equal or better performance than insertps.
17097 // But if optimizing for size and there's a load folding opportunity,
17098 // generate insertps because blendps does not have a 32-bit memory
17099 // operand form.
17100 N2 = DAG.getIntPtrConstant(1, dl);
17101 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
17102 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
17103 }
17104 N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
17105 // Create this as a scalar to vector..
17106 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
17107 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
17108 }
17109
17110 // PINSR* works with constant index.
17111 if (EltVT == MVT::i32 || EltVT == MVT::i64)
17112 return Op;
17113 }
17114
17115 return SDValue();
17116}
17117
17118static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, const X86Subtarget &Subtarget,
17119 SelectionDAG &DAG) {
17120 SDLoc dl(Op);
17121 MVT OpVT = Op.getSimpleValueType();
17122
17123 // It's always cheaper to replace a xor+movd with xorps and simplifies further
17124 // combines.
17125 if (X86::isZeroNode(Op.getOperand(0)))
17126 return getZeroVector(OpVT, Subtarget, DAG, dl);
17127
17128 // If this is a 256-bit vector result, first insert into a 128-bit
17129 // vector and then insert into the 256-bit vector.
17130 if (!OpVT.is128BitVector()) {
17131 // Insert into a 128-bit vector.
17132 unsigned SizeFactor = OpVT.getSizeInBits() / 128;
17133 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
17134 OpVT.getVectorNumElements() / SizeFactor);
17135
17136 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
17137
17138 // Insert the 128-bit vector.
17139 return insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
17140 }
17141 assert(OpVT.is128BitVector() && "Expected an SSE type!")((OpVT.is128BitVector() && "Expected an SSE type!") ?
static_cast<void> (0) : __assert_fail ("OpVT.is128BitVector() && \"Expected an SSE type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 17141, __PRETTY_FUNCTION__))
;
17142
17143 // Pass through a v4i32 SCALAR_TO_VECTOR as that's what we use in tblgen.
17144 if (OpVT == MVT::v4i32)
17145 return Op;
17146
17147 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
17148 return DAG.getBitcast(
17149 OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
17150}
17151
17152// Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
17153// simple superregister reference or explicit instructions to insert
17154// the upper bits of a vector.
17155static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget &Subtarget,
17156 SelectionDAG &DAG) {
17157 assert(Op.getSimpleValueType().getVectorElementType() == MVT::i1)((Op.getSimpleValueType().getVectorElementType() == MVT::i1) ?
static_cast<void> (0) : __assert_fail ("Op.getSimpleValueType().getVectorElementType() == MVT::i1"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 17157, __PRETTY_FUNCTION__))
;
17158
17159 return insert1BitVector(Op, DAG, Subtarget);
17160}
17161
17162static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget &Subtarget,
17163 SelectionDAG &DAG) {
17164 assert(Op.getSimpleValueType().getVectorElementType() == MVT::i1 &&((Op.getSimpleValueType().getVectorElementType() == MVT::i1 &&
"Only vXi1 extract_subvectors need custom lowering") ? static_cast
<void> (0) : __assert_fail ("Op.getSimpleValueType().getVectorElementType() == MVT::i1 && \"Only vXi1 extract_subvectors need custom lowering\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 17165, __PRETTY_FUNCTION__))
17165 "Only vXi1 extract_subvectors need custom lowering")((Op.getSimpleValueType().getVectorElementType() == MVT::i1 &&
"Only vXi1 extract_subvectors need custom lowering") ? static_cast
<void> (0) : __assert_fail ("Op.getSimpleValueType().getVectorElementType() == MVT::i1 && \"Only vXi1 extract_subvectors need custom lowering\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 17165, __PRETTY_FUNCTION__))
;
17166
17167 SDLoc dl(Op);
17168 SDValue Vec = Op.getOperand(0);
17169 SDValue Idx = Op.getOperand(1);
17170
17171 if (!isa<ConstantSDNode>(Idx))
17172 return SDValue();
17173
17174 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
17175 if (IdxVal == 0) // the operation is legal
17176 return Op;
17177
17178 MVT VecVT = Vec.getSimpleValueType();
17179 unsigned NumElems = VecVT.getVectorNumElements();
17180
17181 // Extend to natively supported kshift.
17182 MVT WideVecVT = VecVT;
17183 if ((!Subtarget.hasDQI() && NumElems == 8) || NumElems < 8) {
17184 WideVecVT = Subtarget.hasDQI() ? MVT::v8i1 : MVT::v16i1;
17185 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideVecVT,
17186 DAG.getUNDEF(WideVecVT), Vec,
17187 DAG.getIntPtrConstant(0, dl));
17188 }
17189
17190 // Shift to the LSB.
17191 Vec = DAG.getNode(X86ISD::KSHIFTR, dl, WideVecVT, Vec,
17192 DAG.getConstant(IdxVal, dl, MVT::i8));
17193
17194 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, Op.getValueType(), Vec,
17195 DAG.getIntPtrConstant(0, dl));
17196}
17197
17198// Returns the appropriate wrapper opcode for a global reference.
17199unsigned X86TargetLowering::getGlobalWrapperKind(
17200 const GlobalValue *GV, const unsigned char OpFlags) const {
17201 // References to absolute symbols are never PC-relative.
17202 if (GV && GV->isAbsoluteSymbolRef())
17203 return X86ISD::Wrapper;
17204
17205 CodeModel::Model M = getTargetMachine().getCodeModel();
17206 if (Subtarget.isPICStyleRIPRel() &&
17207 (M == CodeModel::Small || M == CodeModel::Kernel))
17208 return X86ISD::WrapperRIP;
17209
17210 // GOTPCREL references must always use RIP.
17211 if (OpFlags == X86II::MO_GOTPCREL)
17212 return X86ISD::WrapperRIP;
17213
17214 return X86ISD::Wrapper;
17215}
17216
17217// ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
17218// their target counterpart wrapped in the X86ISD::Wrapper node. Suppose N is
17219// one of the above mentioned nodes. It has to be wrapped because otherwise
17220// Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
17221// be used to form addressing mode. These wrapped nodes will be selected
17222// into MOV32ri.
17223SDValue
17224X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
17225 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
17226
17227 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
17228 // global base reg.
17229 unsigned char OpFlag = Subtarget.classifyLocalReference(nullptr);
17230
17231 auto PtrVT = getPointerTy(DAG.getDataLayout());
17232 SDValue Result = DAG.getTargetConstantPool(
17233 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
17234 SDLoc DL(CP);
17235 Result = DAG.getNode(getGlobalWrapperKind(), DL, PtrVT, Result);
17236 // With PIC, the address is actually $g + Offset.
17237 if (OpFlag) {
17238 Result =
17239 DAG.getNode(ISD::ADD, DL, PtrVT,
17240 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
17241 }
17242
17243 return Result;
17244}
17245
17246SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
17247 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
17248
17249 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
17250 // global base reg.
17251 unsigned char OpFlag = Subtarget.classifyLocalReference(nullptr);
17252
17253 auto PtrVT = getPointerTy(DAG.getDataLayout());
17254 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
17255 SDLoc DL(JT);
17256 Result = DAG.getNode(getGlobalWrapperKind(), DL, PtrVT, Result);
17257
17258 // With PIC, the address is actually $g + Offset.
17259 if (OpFlag)
17260 Result =
17261 DAG.getNode(ISD::ADD, DL, PtrVT,
17262 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
17263
17264 return Result;
17265}
17266
17267SDValue X86TargetLowering::LowerExternalSymbol(SDValue Op,
17268 SelectionDAG &DAG) const {
17269 return LowerGlobalOrExternal(Op, DAG, /*ForCall=*/false);
17270}
17271
17272SDValue
17273X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
17274 // Create the TargetBlockAddressAddress node.
17275 unsigned char OpFlags =
17276 Subtarget.classifyBlockAddressReference();
17277 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
17278 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
17279 SDLoc dl(Op);
17280 auto PtrVT = getPointerTy(DAG.getDataLayout());
17281 SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
17282 Result = DAG.getNode(getGlobalWrapperKind(), dl, PtrVT, Result);
17283
17284 // With PIC, the address is actually $g + Offset.
17285 if (isGlobalRelativeToPICBase(OpFlags)) {
17286 Result = DAG.getNode(ISD::ADD, dl, PtrVT,
17287 DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
17288 }
17289
17290 return Result;
17291}
17292
17293/// Creates target global address or external symbol nodes for calls or
17294/// other uses.
17295SDValue X86TargetLowering::LowerGlobalOrExternal(SDValue Op, SelectionDAG &DAG,
17296 bool ForCall) const {
17297 // Unpack the global address or external symbol.
17298 const SDLoc &dl = SDLoc(Op);
17299 const GlobalValue *GV = nullptr;
17300 int64_t Offset = 0;
17301 const char *ExternalSym = nullptr;
17302 if (const auto *G = dyn_cast<GlobalAddressSDNode>(Op)) {
17303 GV = G->getGlobal();
17304 Offset = G->getOffset();
17305 } else {
17306 const auto *ES = cast<ExternalSymbolSDNode>(Op);
17307 ExternalSym = ES->getSymbol();
17308 }
17309
17310 // Calculate some flags for address lowering.
17311 const Module &Mod = *DAG.getMachineFunction().getFunction().getParent();
17312 unsigned char OpFlags;
17313 if (ForCall)
17314 OpFlags = Subtarget.classifyGlobalFunctionReference(GV, Mod);
17315 else
17316 OpFlags = Subtarget.classifyGlobalReference(GV, Mod);
17317 bool HasPICReg = isGlobalRelativeToPICBase(OpFlags);
17318 bool NeedsLoad = isGlobalStubReference(OpFlags);
17319
17320 CodeModel::Model M = DAG.getTarget().getCodeModel();
17321 auto PtrVT = getPointerTy(DAG.getDataLayout());
17322 SDValue Result;
17323
17324 if (GV) {
17325 // Create a target global address if this is a global. If possible, fold the
17326 // offset into the global address reference. Otherwise, ADD it on later.
17327 int64_t GlobalOffset = 0;
17328 if (OpFlags == X86II::MO_NO_FLAG &&
17329 X86::isOffsetSuitableForCodeModel(Offset, M)) {
17330 std::swap(GlobalOffset, Offset);
17331 }
17332 Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, GlobalOffset, OpFlags);
17333 } else {
17334 // If this is not a global address, this must be an external symbol.
17335 Result = DAG.getTargetExternalSymbol(ExternalSym, PtrVT, OpFlags);
17336 }
17337
17338 // If this is a direct call, avoid the wrapper if we don't need to do any
17339 // loads or adds. This allows SDAG ISel to match direct calls.
17340 if (ForCall && !NeedsLoad && !HasPICReg && Offset == 0)
17341 return Result;
17342
17343 Result = DAG.getNode(getGlobalWrapperKind(GV, OpFlags), dl, PtrVT, Result);
17344
17345 // With PIC, the address is actually $g + Offset.
17346 if (HasPICReg) {
17347 Result = DAG.getNode(ISD::ADD, dl, PtrVT,
17348 DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
17349 }
17350
17351 // For globals that require a load from a stub to get the address, emit the
17352 // load.
17353 if (NeedsLoad)
17354 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
17355 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
17356
17357 // If there was a non-zero offset that we didn't fold, create an explicit
17358 // addition for it.
17359 if (Offset != 0)
17360 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
17361 DAG.getConstant(Offset, dl, PtrVT));
17362
17363 return Result;
17364}
17365
17366SDValue
17367X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
17368 return LowerGlobalOrExternal(Op, DAG, /*ForCall=*/false);
17369}
17370
17371static SDValue
17372GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
17373 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
17374 unsigned char OperandFlags, bool LocalDynamic = false) {
17375 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
17376 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
17377 SDLoc dl(GA);
17378 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
17379 GA->getValueType(0),
17380 GA->getOffset(),
17381 OperandFlags);
17382
17383 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
17384 : X86ISD::TLSADDR;
17385
17386 if (InFlag) {
17387 SDValue Ops[] = { Chain, TGA, *InFlag };
17388 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
17389 } else {
17390 SDValue Ops[] = { Chain, TGA };
17391 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
17392 }
17393
17394 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
17395 MFI.setAdjustsStack(true);
17396 MFI.setHasCalls(true);
17397
17398 SDValue Flag = Chain.getValue(1);
17399 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
17400}
17401
17402// Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
17403static SDValue
17404LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
17405 const EVT PtrVT) {
17406 SDValue InFlag;
17407 SDLoc dl(GA); // ? function entry point might be better
17408 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
17409 DAG.getNode(X86ISD::GlobalBaseReg,
17410 SDLoc(), PtrVT), InFlag);
17411 InFlag = Chain.getValue(1);
17412
17413 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
17414}
17415
17416// Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
17417static SDValue
17418LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
17419 const EVT PtrVT) {
17420 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
17421 X86::RAX, X86II::MO_TLSGD);
17422}
17423
17424static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
17425 SelectionDAG &DAG,
17426 const EVT PtrVT,
17427 bool is64Bit) {
17428 SDLoc dl(GA);
17429
17430 // Get the start address of the TLS block for this module.
17431 X86MachineFunctionInfo *MFI = DAG.getMachineFunction()
17432 .getInfo<X86MachineFunctionInfo>();
17433 MFI->incNumLocalDynamicTLSAccesses();
17434
17435 SDValue Base;
17436 if (is64Bit) {
17437 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
17438 X86II::MO_TLSLD, /*LocalDynamic=*/true);
17439 } else {
17440 SDValue InFlag;
17441 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
17442 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
17443 InFlag = Chain.getValue(1);
17444 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
17445 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
17446 }
17447
17448 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
17449 // of Base.
17450
17451 // Build x@dtpoff.
17452 unsigned char OperandFlags = X86II::MO_DTPOFF;
17453 unsigned WrapperKind = X86ISD::Wrapper;
17454 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
17455 GA->getValueType(0),
17456 GA->getOffset(), OperandFlags);
17457 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
17458
17459 // Add x@dtpoff with the base.
17460 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
17461}
17462
17463// Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
17464static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
17465 const EVT PtrVT, TLSModel::Model model,
17466 bool is64Bit, bool isPIC) {
17467 SDLoc dl(GA);
17468
17469 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
17470 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
17471 is64Bit ? 257 : 256));
17472
17473 SDValue ThreadPointer =
17474 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
17475 MachinePointerInfo(Ptr));
17476
17477 unsigned char OperandFlags = 0;
17478 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
17479 // initialexec.
17480 unsigned WrapperKind = X86ISD::Wrapper;
17481 if (model == TLSModel::LocalExec) {
17482 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
17483 } else if (model == TLSModel::InitialExec) {
17484 if (is64Bit) {
17485 OperandFlags = X86II::MO_GOTTPOFF;
17486 WrapperKind = X86ISD::WrapperRIP;
17487 } else {
17488 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
17489 }
17490 } else {
17491 llvm_unreachable("Unexpected model")::llvm::llvm_unreachable_internal("Unexpected model", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 17491)
;
17492 }
17493
17494 // emit "addl x@ntpoff,%eax" (local exec)
17495 // or "addl x@indntpoff,%eax" (initial exec)
17496 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
17497 SDValue TGA =
17498 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
17499 GA->getOffset(), OperandFlags);
17500 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
17501
17502 if (model == TLSModel::InitialExec) {
17503 if (isPIC && !is64Bit) {
17504 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
17505 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
17506 Offset);
17507 }
17508
17509 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
17510 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
17511 }
17512
17513 // The address of the thread local variable is the add of the thread
17514 // pointer with the offset of the variable.
17515 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
17516}
17517
17518SDValue
17519X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
17520
17521 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
17522
17523 if (DAG.getTarget().useEmulatedTLS())
17524 return LowerToTLSEmulatedModel(GA, DAG);
17525
17526 const GlobalValue *GV = GA->getGlobal();
17527 auto PtrVT = getPointerTy(DAG.getDataLayout());
17528 bool PositionIndependent = isPositionIndependent();
17529
17530 if (Subtarget.isTargetELF()) {
17531 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
17532 switch (model) {
17533 case TLSModel::GeneralDynamic:
17534 if (Subtarget.is64Bit())
17535 return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
17536 return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
17537 case TLSModel::LocalDynamic:
17538 return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
17539 Subtarget.is64Bit());
17540 case TLSModel::InitialExec:
17541 case TLSModel::LocalExec:
17542 return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget.is64Bit(),
17543 PositionIndependent);
17544 }
17545 llvm_unreachable("Unknown TLS model.")::llvm::llvm_unreachable_internal("Unknown TLS model.", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 17545)
;
17546 }
17547
17548 if (Subtarget.isTargetDarwin()) {
17549 // Darwin only has one model of TLS. Lower to that.
17550 unsigned char OpFlag = 0;
17551 unsigned WrapperKind = Subtarget.isPICStyleRIPRel() ?
17552 X86ISD::WrapperRIP : X86ISD::Wrapper;
17553
17554 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
17555 // global base reg.
17556 bool PIC32 = PositionIndependent && !Subtarget.is64Bit();
17557 if (PIC32)
17558 OpFlag = X86II::MO_TLVP_PIC_BASE;
17559 else
17560 OpFlag = X86II::MO_TLVP;
17561 SDLoc DL(Op);
17562 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
17563 GA->getValueType(0),
17564 GA->getOffset(), OpFlag);
17565 SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
17566
17567 // With PIC32, the address is actually $g + Offset.
17568 if (PIC32)
17569 Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
17570 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
17571 Offset);
17572
17573 // Lowering the machine isd will make sure everything is in the right
17574 // location.
17575 SDValue Chain = DAG.getEntryNode();
17576 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
17577 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
17578 SDValue Args[] = { Chain, Offset };
17579 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
17580 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, DL, true),
17581 DAG.getIntPtrConstant(0, DL, true),
17582 Chain.getValue(1), DL);
17583
17584 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
17585 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
17586 MFI.setAdjustsStack(true);
17587
17588 // And our return value (tls address) is in the standard call return value
17589 // location.
17590 unsigned Reg = Subtarget.is64Bit() ? X86::RAX : X86::EAX;
17591 return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
17592 }
17593
17594 if (Subtarget.isTargetKnownWindowsMSVC() ||
17595 Subtarget.isTargetWindowsItanium() ||
17596 Subtarget.isTargetWindowsGNU()) {
17597 // Just use the implicit TLS architecture
17598 // Need to generate something similar to:
17599 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
17600 // ; from TEB
17601 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
17602 // mov rcx, qword [rdx+rcx*8]
17603 // mov eax, .tls$:tlsvar
17604 // [rax+rcx] contains the address
17605 // Windows 64bit: gs:0x58
17606 // Windows 32bit: fs:__tls_array
17607
17608 SDLoc dl(GA);
17609 SDValue Chain = DAG.getEntryNode();
17610
17611 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
17612 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
17613 // use its literal value of 0x2C.
17614 Value *Ptr = Constant::getNullValue(Subtarget.is64Bit()
17615 ? Type::getInt8PtrTy(*DAG.getContext(),
17616 256)
17617 : Type::getInt32PtrTy(*DAG.getContext(),
17618 257));
17619
17620 SDValue TlsArray = Subtarget.is64Bit()
17621 ? DAG.getIntPtrConstant(0x58, dl)
17622 : (Subtarget.isTargetWindowsGNU()
17623 ? DAG.getIntPtrConstant(0x2C, dl)
17624 : DAG.getExternalSymbol("_tls_array", PtrVT));
17625
17626 SDValue ThreadPointer =
17627 DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr));
17628
17629 SDValue res;
17630 if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
17631 res = ThreadPointer;
17632 } else {
17633 // Load the _tls_index variable
17634 SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
17635 if (Subtarget.is64Bit())
17636 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
17637 MachinePointerInfo(), MVT::i32);
17638 else
17639 IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo());
17640
17641 auto &DL = DAG.getDataLayout();
17642 SDValue Scale =
17643 DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, MVT::i8);
17644 IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
17645
17646 res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
17647 }
17648
17649 res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo());
17650
17651 // Get the offset of start of .tls section
17652 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
17653 GA->getValueType(0),
17654 GA->getOffset(), X86II::MO_SECREL);
17655 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
17656
17657 // The address of the thread local variable is the add of the thread
17658 // pointer with the offset of the variable.
17659 return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
17660 }
17661
17662 llvm_unreachable("TLS not implemented for this target.")::llvm::llvm_unreachable_internal("TLS not implemented for this target."
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 17662)
;
17663}
17664
17665/// Lower SRA_PARTS and friends, which return two i32 values
17666/// and take a 2 x i32 value to shift plus a shift amount.
17667/// TODO: Can this be moved to general expansion code?
17668static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
17669 assert(Op.getNumOperands() == 3 && "Not a double-shift!")((Op.getNumOperands() == 3 && "Not a double-shift!") ?
static_cast<void> (0) : __assert_fail ("Op.getNumOperands() == 3 && \"Not a double-shift!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 17669, __PRETTY_FUNCTION__))
;
17670 MVT VT = Op.getSimpleValueType();
17671 unsigned VTBits = VT.getSizeInBits();
17672 SDLoc dl(Op);
17673 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
17674 SDValue ShOpLo = Op.getOperand(0);
17675 SDValue ShOpHi = Op.getOperand(1);
17676 SDValue ShAmt = Op.getOperand(2);
17677 // ISD::FSHL and ISD::FSHR have defined overflow behavior but ISD::SHL and
17678 // ISD::SRA/L nodes haven't. Insert an AND to be safe, it's optimized away
17679 // during isel.
17680 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
17681 DAG.getConstant(VTBits - 1, dl, MVT::i8));
17682 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
17683 DAG.getConstant(VTBits - 1, dl, MVT::i8))
17684 : DAG.getConstant(0, dl, VT);
17685
17686 SDValue Tmp2, Tmp3;
17687 if (Op.getOpcode() == ISD::SHL_PARTS) {
17688 Tmp2 = DAG.getNode(ISD::FSHL, dl, VT, ShOpHi, ShOpLo, ShAmt);
17689 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
17690 } else {
17691 Tmp2 = DAG.getNode(ISD::FSHR, dl, VT, ShOpHi, ShOpLo, ShAmt);
17692 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
17693 }
17694
17695 // If the shift amount is larger or equal than the width of a part we can't
17696 // rely on the results of shld/shrd. Insert a test and select the appropriate
17697 // values for large shift amounts.
17698 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
17699 DAG.getConstant(VTBits, dl, MVT::i8));
17700 SDValue Cond = DAG.getSetCC(dl, MVT::i8, AndNode,
17701 DAG.getConstant(0, dl, MVT::i8), ISD::SETNE);
17702
17703 SDValue Hi, Lo;
17704 if (Op.getOpcode() == ISD::SHL_PARTS) {
17705 Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2);
17706 Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3);
17707 } else {
17708 Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2);
17709 Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3);
17710 }
17711
17712 return DAG.getMergeValues({ Lo, Hi }, dl);
17713}
17714
17715static SDValue LowerFunnelShift(SDValue Op, const X86Subtarget &Subtarget,
17716 SelectionDAG &DAG) {
17717 MVT VT = Op.getSimpleValueType();
17718 assert((Op.getOpcode() == ISD::FSHL || Op.getOpcode() == ISD::FSHR) &&(((Op.getOpcode() == ISD::FSHL || Op.getOpcode() == ISD::FSHR
) && "Unexpected funnel shift opcode!") ? static_cast
<void> (0) : __assert_fail ("(Op.getOpcode() == ISD::FSHL || Op.getOpcode() == ISD::FSHR) && \"Unexpected funnel shift opcode!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 17719, __PRETTY_FUNCTION__))
17719 "Unexpected funnel shift opcode!")(((Op.getOpcode() == ISD::FSHL || Op.getOpcode() == ISD::FSHR
) && "Unexpected funnel shift opcode!") ? static_cast
<void> (0) : __assert_fail ("(Op.getOpcode() == ISD::FSHL || Op.getOpcode() == ISD::FSHR) && \"Unexpected funnel shift opcode!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 17719, __PRETTY_FUNCTION__))
;
17720
17721 SDLoc DL(Op);
17722 SDValue Op0 = Op.getOperand(0);
17723 SDValue Op1 = Op.getOperand(1);
17724 SDValue Amt = Op.getOperand(2);
17725
17726 bool IsFSHR = Op.getOpcode() == ISD::FSHR;
17727
17728 if (VT.isVector()) {
17729 assert(Subtarget.hasVBMI2() && "Expected VBMI2")((Subtarget.hasVBMI2() && "Expected VBMI2") ? static_cast
<void> (0) : __assert_fail ("Subtarget.hasVBMI2() && \"Expected VBMI2\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 17729, __PRETTY_FUNCTION__))
;
17730
17731 if (IsFSHR)
17732 std::swap(Op0, Op1);
17733
17734 APInt APIntShiftAmt;
17735 if (isConstantSplat(Amt, APIntShiftAmt)) {
17736 uint64_t ShiftAmt = APIntShiftAmt.getZExtValue();
17737 return DAG.getNode(IsFSHR ? X86ISD::VSHRD : X86ISD::VSHLD, DL, VT,
17738 Op0, Op1, DAG.getConstant(ShiftAmt, DL, MVT::i8));
17739 }
17740
17741 return DAG.getNode(IsFSHR ? X86ISD::VSHRDV : X86ISD::VSHLDV, DL, VT,
17742 Op0, Op1, Amt);
17743 }
17744
17745 assert((VT == MVT::i16 || VT == MVT::i32 || VT == MVT::i64) &&(((VT == MVT::i16 || VT == MVT::i32 || VT == MVT::i64) &&
"Unexpected funnel shift type!") ? static_cast<void> (
0) : __assert_fail ("(VT == MVT::i16 || VT == MVT::i32 || VT == MVT::i64) && \"Unexpected funnel shift type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 17746, __PRETTY_FUNCTION__))
17746 "Unexpected funnel shift type!")(((VT == MVT::i16 || VT == MVT::i32 || VT == MVT::i64) &&
"Unexpected funnel shift type!") ? static_cast<void> (
0) : __assert_fail ("(VT == MVT::i16 || VT == MVT::i32 || VT == MVT::i64) && \"Unexpected funnel shift type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 17746, __PRETTY_FUNCTION__))
;
17747
17748 // Expand slow SHLD/SHRD cases if we are not optimizing for size.
17749 bool OptForSize = DAG.getMachineFunction().getFunction().hasOptSize();
17750 if (!OptForSize && Subtarget.isSHLDSlow())
17751 return SDValue();
17752
17753 if (IsFSHR)
17754 std::swap(Op0, Op1);
17755
17756 // i16 needs to modulo the shift amount, but i32/i64 have implicit modulo.
17757 if (VT == MVT::i16)
17758 Amt = DAG.getNode(ISD::AND, DL, Amt.getValueType(), Amt,
17759 DAG.getConstant(15, DL, Amt.getValueType()));
17760
17761 unsigned SHDOp = (IsFSHR ? X86ISD::SHRD : X86ISD::SHLD);
17762 return DAG.getNode(SHDOp, DL, VT, Op0, Op1, Amt);
17763}
17764
17765// Try to use a packed vector operation to handle i64 on 32-bit targets when
17766// AVX512DQ is enabled.
17767static SDValue LowerI64IntToFP_AVX512DQ(SDValue Op, SelectionDAG &DAG,
17768 const X86Subtarget &Subtarget) {
17769 assert((Op.getOpcode() == ISD::SINT_TO_FP ||(((Op.getOpcode() == ISD::SINT_TO_FP || Op.getOpcode() == ISD
::UINT_TO_FP) && "Unexpected opcode!") ? static_cast<
void> (0) : __assert_fail ("(Op.getOpcode() == ISD::SINT_TO_FP || Op.getOpcode() == ISD::UINT_TO_FP) && \"Unexpected opcode!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 17770, __PRETTY_FUNCTION__))
17770 Op.getOpcode() == ISD::UINT_TO_FP) && "Unexpected opcode!")(((Op.getOpcode() == ISD::SINT_TO_FP || Op.getOpcode() == ISD
::UINT_TO_FP) && "Unexpected opcode!") ? static_cast<
void> (0) : __assert_fail ("(Op.getOpcode() == ISD::SINT_TO_FP || Op.getOpcode() == ISD::UINT_TO_FP) && \"Unexpected opcode!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 17770, __PRETTY_FUNCTION__))
;
17771 SDValue Src = Op.getOperand(0);
17772 MVT SrcVT = Src.getSimpleValueType();
17773 MVT VT = Op.getSimpleValueType();
17774
17775 if (!Subtarget.hasDQI() || SrcVT != MVT::i64 || Subtarget.is64Bit() ||
17776 (VT != MVT::f32 && VT != MVT::f64))
17777 return SDValue();
17778
17779 // Pack the i64 into a vector, do the operation and extract.
17780
17781 // Using 256-bit to ensure result is 128-bits for f32 case.
17782 unsigned NumElts = Subtarget.hasVLX() ? 4 : 8;
17783 MVT VecInVT = MVT::getVectorVT(MVT::i64, NumElts);
17784 MVT VecVT = MVT::getVectorVT(VT, NumElts);
17785
17786 SDLoc dl(Op);
17787 SDValue InVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecInVT, Src);
17788 SDValue CvtVec = DAG.getNode(Op.getOpcode(), dl, VecVT, InVec);
17789 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, CvtVec,
17790 DAG.getIntPtrConstant(0, dl));
17791}
17792
17793static bool useVectorCast(unsigned Opcode, MVT FromVT, MVT ToVT,
17794 const X86Subtarget &Subtarget) {
17795 switch (Opcode) {
17796 case ISD::SINT_TO_FP:
17797 // TODO: Handle wider types with AVX/AVX512.
17798 if (!Subtarget.hasSSE2() || FromVT != MVT::v4i32)
17799 return false;
17800 // CVTDQ2PS or (V)CVTDQ2PD
17801 return ToVT == MVT::v4f32 || (Subtarget.hasAVX() && ToVT == MVT::v4f64);
17802
17803 case ISD::UINT_TO_FP:
17804 // TODO: Handle wider types and i64 elements.
17805 if (!Subtarget.hasAVX512() || FromVT != MVT::v4i32)
17806 return false;
17807 // VCVTUDQ2PS or VCVTUDQ2PD
17808 return ToVT == MVT::v4f32 || ToVT == MVT::v4f64;
17809
17810 default:
17811 return false;
17812 }
17813}
17814
17815/// Given a scalar cast operation that is extracted from a vector, try to
17816/// vectorize the cast op followed by extraction. This will avoid an expensive
17817/// round-trip between XMM and GPR.
17818static SDValue vectorizeExtractedCast(SDValue Cast, SelectionDAG &DAG,
17819 const X86Subtarget &Subtarget) {
17820 // TODO: This could be enhanced to handle smaller integer types by peeking
17821 // through an extend.
17822 SDValue Extract = Cast.getOperand(0);
17823 MVT DestVT = Cast.getSimpleValueType();
17824 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
17825 !isa<ConstantSDNode>(Extract.getOperand(1)))
17826 return SDValue();
17827
17828 // See if we have a 128-bit vector cast op for this type of cast.
17829 SDValue VecOp = Extract.getOperand(0);
17830 MVT FromVT = VecOp.getSimpleValueType();
17831 unsigned NumEltsInXMM = 128 / FromVT.getScalarSizeInBits();
17832 MVT Vec128VT = MVT::getVectorVT(FromVT.getScalarType(), NumEltsInXMM);
17833 MVT ToVT = MVT::getVectorVT(DestVT, NumEltsInXMM);
17834 if (!useVectorCast(Cast.getOpcode(), Vec128VT, ToVT, Subtarget))
17835 return SDValue();
17836
17837 // If we are extracting from a non-zero element, first shuffle the source
17838 // vector to allow extracting from element zero.
17839 SDLoc DL(Cast);
17840 if (!isNullConstant(Extract.getOperand(1))) {
17841 SmallVector<int, 16> Mask(FromVT.getVectorNumElements(), -1);
17842 Mask[0] = Extract.getConstantOperandVal(1);
17843 VecOp = DAG.getVectorShuffle(FromVT, DL, VecOp, DAG.getUNDEF(FromVT), Mask);
17844 }
17845 // If the source vector is wider than 128-bits, extract the low part. Do not
17846 // create an unnecessarily wide vector cast op.
17847 if (FromVT != Vec128VT)
17848 VecOp = extract128BitVector(VecOp, 0, DAG, DL);
17849
17850 // cast (extelt V, 0) --> extelt (cast (extract_subv V)), 0
17851 // cast (extelt V, C) --> extelt (cast (extract_subv (shuffle V, [C...]))), 0
17852 SDValue VCast = DAG.getNode(Cast.getOpcode(), DL, ToVT, VecOp);
17853 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, DestVT, VCast,
17854 DAG.getIntPtrConstant(0, DL));
17855}
17856
17857SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
17858 SelectionDAG &DAG) const {
17859 SDValue Src = Op.getOperand(0);
17860 MVT SrcVT = Src.getSimpleValueType();
17861 MVT VT = Op.getSimpleValueType();
17862 SDLoc dl(Op);
17863
17864 if (SDValue Extract = vectorizeExtractedCast(Op, DAG, Subtarget))
17865 return Extract;
17866
17867 if (SrcVT.isVector()) {
17868 if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
17869 return DAG.getNode(X86ISD::CVTSI2P, dl, VT,
17870 DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
17871 DAG.getUNDEF(SrcVT)));
17872 }
17873 return SDValue();
17874 }
17875
17876 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&((SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
"Unknown SINT_TO_FP to lower!") ? static_cast<void> (0
) : __assert_fail ("SrcVT <= MVT::i64 && SrcVT >= MVT::i16 && \"Unknown SINT_TO_FP to lower!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 17877, __PRETTY_FUNCTION__))
17877 "Unknown SINT_TO_FP to lower!")((SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
"Unknown SINT_TO_FP to lower!") ? static_cast<void> (0
) : __assert_fail ("SrcVT <= MVT::i64 && SrcVT >= MVT::i16 && \"Unknown SINT_TO_FP to lower!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 17877, __PRETTY_FUNCTION__))
;
17878
17879 // These are really Legal; return the operand so the caller accepts it as
17880 // Legal.
17881 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(VT))
17882 return Op;
17883 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(VT) && Subtarget.is64Bit())
17884 return Op;
17885
17886 if (SDValue V = LowerI64IntToFP_AVX512DQ(Op, DAG, Subtarget))
17887 return V;
17888
17889 SDValue ValueToStore = Op.getOperand(0);
17890 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(VT) &&
17891 !Subtarget.is64Bit())
17892 // Bitcasting to f64 here allows us to do a single 64-bit store from
17893 // an SSE register, avoiding the store forwarding penalty that would come
17894 // with two 32-bit stores.
17895 ValueToStore = DAG.getBitcast(MVT::f64, ValueToStore);
17896
17897 unsigned Size = SrcVT.getSizeInBits()/8;
17898 MachineFunction &MF = DAG.getMachineFunction();
17899 auto PtrVT = getPointerTy(MF.getDataLayout());
17900 int SSFI = MF.getFrameInfo().CreateStackObject(Size, Size, false);
17901 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
17902 SDValue Chain = DAG.getStore(
17903 DAG.getEntryNode(), dl, ValueToStore, StackSlot,
17904 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI));
17905 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
17906}
17907
17908SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
17909 SDValue StackSlot,
17910 SelectionDAG &DAG) const {
17911 // Build the FILD
17912 SDLoc DL(Op);
17913 SDVTList Tys;
17914 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
17915 if (useSSE)
17916 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
17917 else
17918 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
17919
17920 unsigned ByteSize = SrcVT.getSizeInBits() / 8;
17921
17922 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
17923 MachineMemOperand *LoadMMO;
17924 if (FI) {
17925 int SSFI = FI->getIndex();
17926 LoadMMO = DAG.getMachineFunction().getMachineMemOperand(
17927 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
17928 MachineMemOperand::MOLoad, ByteSize, ByteSize);
17929 } else {
17930 LoadMMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
17931 StackSlot = StackSlot.getOperand(1);
17932 }
17933 SDValue FILDOps[] = {Chain, StackSlot};
17934 SDValue Result =
17935 DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, DL,
17936 Tys, FILDOps, SrcVT, LoadMMO);
17937
17938 if (useSSE) {
17939 Chain = Result.getValue(1);
17940 SDValue InFlag = Result.getValue(2);
17941
17942 // FIXME: Currently the FST is glued to the FILD_FLAG. This
17943 // shouldn't be necessary except that RFP cannot be live across
17944 // multiple blocks. When stackifier is fixed, they can be uncoupled.
17945 MachineFunction &MF = DAG.getMachineFunction();
17946 unsigned SSFISize = Op.getValueSizeInBits() / 8;
17947 int SSFI = MF.getFrameInfo().CreateStackObject(SSFISize, SSFISize, false);
17948 auto PtrVT = getPointerTy(MF.getDataLayout());
17949 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
17950 Tys = DAG.getVTList(MVT::Other);
17951 SDValue FSTOps[] = {Chain, Result, StackSlot, InFlag};
17952 MachineMemOperand *StoreMMO = DAG.getMachineFunction().getMachineMemOperand(
17953 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
17954 MachineMemOperand::MOStore, SSFISize, SSFISize);
17955
17956 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys, FSTOps,
17957 Op.getValueType(), StoreMMO);
17958 Result = DAG.getLoad(
17959 Op.getValueType(), DL, Chain, StackSlot,
17960 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI));
17961 }
17962
17963 return Result;
17964}
17965
17966/// 64-bit unsigned integer to double expansion.
17967static SDValue LowerUINT_TO_FP_i64(SDValue Op, SelectionDAG &DAG,
17968 const X86Subtarget &Subtarget) {
17969 // This algorithm is not obvious. Here it is what we're trying to output:
17970 /*
17971 movq %rax, %xmm0
17972 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
17973 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
17974 #ifdef __SSE3__
17975 haddpd %xmm0, %xmm0
17976 #else
17977 pshufd $0x4e, %xmm0, %xmm1
17978 addpd %xmm1, %xmm0
17979 #endif
17980 */
17981
17982 SDLoc dl(Op);
17983 LLVMContext *Context = DAG.getContext();
17984
17985 // Build some magic constants.
17986 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
17987 Constant *C0 = ConstantDataVector::get(*Context, CV0);
17988 auto PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
17989 SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
17990
17991 SmallVector<Constant*,2> CV1;
17992 CV1.push_back(
17993 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble(),
17994 APInt(64, 0x4330000000000000ULL))));
17995 CV1.push_back(
17996 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble(),
17997 APInt(64, 0x4530000000000000ULL))));
17998 Constant *C1 = ConstantVector::get(CV1);
17999 SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
18000
18001 // Load the 64-bit value into an XMM register.
18002 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
18003 Op.getOperand(0));
18004 SDValue CLod0 =
18005 DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
18006 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
18007 /* Alignment = */ 16);
18008 SDValue Unpck1 =
18009 getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
18010
18011 SDValue CLod1 =
18012 DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
18013 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
18014 /* Alignment = */ 16);
18015 SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
18016 // TODO: Are there any fast-math-flags to propagate here?
18017 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
18018 SDValue Result;
18019
18020 if (Subtarget.hasSSE3()) {
18021 // FIXME: The 'haddpd' instruction may be slower than 'shuffle + addsd'.
18022 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
18023 } else {
18024 SDValue Shuffle = DAG.getVectorShuffle(MVT::v2f64, dl, Sub, Sub, {1,-1});
18025 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuffle, Sub);
18026 }
18027
18028 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
18029 DAG.getIntPtrConstant(0, dl));
18030}
18031
18032/// 32-bit unsigned integer to float expansion.
18033static SDValue LowerUINT_TO_FP_i32(SDValue Op, SelectionDAG &DAG,
18034 const X86Subtarget &Subtarget) {
18035 SDLoc dl(Op);
18036 // FP constant to bias correct the final result.
18037 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
18038 MVT::f64);
18039
18040 // Load the 32-bit value into an XMM register.
18041 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
18042 Op.getOperand(0));
18043
18044 // Zero out the upper parts of the register.
18045 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
18046
18047 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
18048 DAG.getBitcast(MVT::v2f64, Load),
18049 DAG.getIntPtrConstant(0, dl));
18050
18051 // Or the load with the bias.
18052 SDValue Or = DAG.getNode(
18053 ISD::OR, dl, MVT::v2i64,
18054 DAG.getBitcast(MVT::v2i64,
18055 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
18056 DAG.getBitcast(MVT::v2i64,
18057 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
18058 Or =
18059 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
18060 DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
18061
18062 // Subtract the bias.
18063 // TODO: Are there any fast-math-flags to propagate here?
18064 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
18065
18066 // Handle final rounding.
18067 return DAG.getFPExtendOrRound(Sub, dl, Op.getSimpleValueType());
18068}
18069
18070static SDValue lowerUINT_TO_FP_v2i32(SDValue Op, SelectionDAG &DAG,
18071 const X86Subtarget &Subtarget,
18072 const SDLoc &DL) {
18073 if (Op.getSimpleValueType() != MVT::v2f64)
18074 return SDValue();
18075
18076 SDValue N0 = Op.getOperand(0);
18077 assert(N0.getSimpleValueType() == MVT::v2i32 && "Unexpected input type")((N0.getSimpleValueType() == MVT::v2i32 && "Unexpected input type"
) ? static_cast<void> (0) : __assert_fail ("N0.getSimpleValueType() == MVT::v2i32 && \"Unexpected input type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 18077, __PRETTY_FUNCTION__))
;
18078
18079 // Legalize to v4i32 type.
18080 N0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4i32, N0,
18081 DAG.getUNDEF(MVT::v2i32));
18082
18083 if (Subtarget.hasAVX512())
18084 return DAG.getNode(X86ISD::CVTUI2P, DL, MVT::v2f64, N0);
18085
18086 // Same implementation as VectorLegalizer::ExpandUINT_TO_FLOAT,
18087 // but using v2i32 to v2f64 with X86ISD::CVTSI2P.
18088 SDValue HalfWord = DAG.getConstant(16, DL, MVT::v4i32);
18089 SDValue HalfWordMask = DAG.getConstant(0x0000FFFF, DL, MVT::v4i32);
18090
18091 // Two to the power of half-word-size.
18092 SDValue TWOHW = DAG.getConstantFP(1 << 16, DL, MVT::v2f64);
18093
18094 // Clear upper part of LO, lower HI.
18095 SDValue HI = DAG.getNode(ISD::SRL, DL, MVT::v4i32, N0, HalfWord);
18096 SDValue LO = DAG.getNode(ISD::AND, DL, MVT::v4i32, N0, HalfWordMask);
18097
18098 SDValue fHI = DAG.getNode(X86ISD::CVTSI2P, DL, MVT::v2f64, HI);
18099 fHI = DAG.getNode(ISD::FMUL, DL, MVT::v2f64, fHI, TWOHW);
18100 SDValue fLO = DAG.getNode(X86ISD::CVTSI2P, DL, MVT::v2f64, LO);
18101
18102 // Add the two halves.
18103 return DAG.getNode(ISD::FADD, DL, MVT::v2f64, fHI, fLO);
18104}
18105
18106static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
18107 const X86Subtarget &Subtarget) {
18108 // The algorithm is the following:
18109 // #ifdef __SSE4_1__
18110 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
18111 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
18112 // (uint4) 0x53000000, 0xaa);
18113 // #else
18114 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
18115 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
18116 // #endif
18117 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
18118 // return (float4) lo + fhi;
18119
18120 // We shouldn't use it when unsafe-fp-math is enabled though: we might later
18121 // reassociate the two FADDs, and if we do that, the algorithm fails
18122 // spectacularly (PR24512).
18123 // FIXME: If we ever have some kind of Machine FMF, this should be marked
18124 // as non-fast and always be enabled. Why isn't SDAG FMF enough? Because
18125 // there's also the MachineCombiner reassociations happening on Machine IR.
18126 if (DAG.getTarget().Options.UnsafeFPMath)
18127 return SDValue();
18128
18129 SDLoc DL(Op);
18130 SDValue V = Op->getOperand(0);
18131 MVT VecIntVT = V.getSimpleValueType();
18132 bool Is128 = VecIntVT == MVT::v4i32;
18133 MVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
18134 // If we convert to something else than the supported type, e.g., to v4f64,
18135 // abort early.
18136 if (VecFloatVT != Op->getSimpleValueType(0))
18137 return SDValue();
18138
18139 assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&(((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
"Unsupported custom type") ? static_cast<void> (0) : __assert_fail
("(VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) && \"Unsupported custom type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 18140, __PRETTY_FUNCTION__))
18140 "Unsupported custom type")(((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
"Unsupported custom type") ? static_cast<void> (0) : __assert_fail
("(VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) && \"Unsupported custom type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 18140, __PRETTY_FUNCTION__))
;
18141
18142 // In the #idef/#else code, we have in common:
18143 // - The vector of constants:
18144 // -- 0x4b000000
18145 // -- 0x53000000
18146 // - A shift:
18147 // -- v >> 16
18148
18149 // Create the splat vector for 0x4b000000.
18150 SDValue VecCstLow = DAG.getConstant(0x4b000000, DL, VecIntVT);
18151 // Create the splat vector for 0x53000000.
18152 SDValue VecCstHigh = DAG.getConstant(0x53000000, DL, VecIntVT);
18153
18154 // Create the right shift.
18155 SDValue VecCstShift = DAG.getConstant(16, DL, VecIntVT);
18156 SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
18157
18158 SDValue Low, High;
18159 if (Subtarget.hasSSE41()) {
18160 MVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
18161 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
18162 SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
18163 SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
18164 // Low will be bitcasted right away, so do not bother bitcasting back to its
18165 // original type.
18166 Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
18167 VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
18168 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
18169 // (uint4) 0x53000000, 0xaa);
18170 SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
18171 SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
18172 // High will be bitcasted right away, so do not bother bitcasting back to
18173 // its original type.
18174 High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
18175 VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
18176 } else {
18177 SDValue VecCstMask = DAG.getConstant(0xffff, DL, VecIntVT);
18178 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
18179 SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
18180 Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
18181
18182 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
18183 High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
18184 }
18185
18186 // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
18187 SDValue VecCstFAdd = DAG.getConstantFP(
18188 APFloat(APFloat::IEEEsingle(), APInt(32, 0xD3000080)), DL, VecFloatVT);
18189
18190 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
18191 SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
18192 // TODO: Are there any fast-math-flags to propagate here?
18193 SDValue FHigh =
18194 DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
18195 // return (float4) lo + fhi;
18196 SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
18197 return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
18198}
18199
18200static SDValue lowerUINT_TO_FP_vec(SDValue Op, SelectionDAG &DAG,
18201 const X86Subtarget &Subtarget) {
18202 SDValue N0 = Op.getOperand(0);
18203 MVT SrcVT = N0.getSimpleValueType();
18204 SDLoc dl(Op);
18205
18206 switch (SrcVT.SimpleTy) {
18207 default:
18208 llvm_unreachable("Custom UINT_TO_FP is not supported!")::llvm::llvm_unreachable_internal("Custom UINT_TO_FP is not supported!"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 18208)
;
18209 case MVT::v2i32:
18210 return lowerUINT_TO_FP_v2i32(Op, DAG, Subtarget, dl);
18211 case MVT::v4i32:
18212 case MVT::v8i32:
18213 assert(!Subtarget.hasAVX512())((!Subtarget.hasAVX512()) ? static_cast<void> (0) : __assert_fail
("!Subtarget.hasAVX512()", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 18213, __PRETTY_FUNCTION__))
;
18214 return lowerUINT_TO_FP_vXi32(Op, DAG, Subtarget);
18215 }
18216}
18217
18218SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
18219 SelectionDAG &DAG) const {
18220 SDValue N0 = Op.getOperand(0);
18221 SDLoc dl(Op);
18222 auto PtrVT = getPointerTy(DAG.getDataLayout());
18223
18224 if (Op.getSimpleValueType().isVector())
18225 return lowerUINT_TO_FP_vec(Op, DAG, Subtarget);
18226
18227 if (SDValue Extract = vectorizeExtractedCast(Op, DAG, Subtarget))
18228 return Extract;
18229
18230 MVT SrcVT = N0.getSimpleValueType();
18231 MVT DstVT = Op.getSimpleValueType();
18232
18233 if (Subtarget.hasAVX512() && isScalarFPTypeInSSEReg(DstVT) &&
18234 (SrcVT == MVT::i32 || (SrcVT == MVT::i64 && Subtarget.is64Bit()))) {
18235 // Conversions from unsigned i32 to f32/f64 are legal,
18236 // using VCVTUSI2SS/SD. Same for i64 in 64-bit mode.
18237 return Op;
18238 }
18239
18240 if (SDValue V = LowerI64IntToFP_AVX512DQ(Op, DAG, Subtarget))
18241 return V;
18242
18243 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
18244 return LowerUINT_TO_FP_i64(Op, DAG, Subtarget);
18245 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
18246 return LowerUINT_TO_FP_i32(Op, DAG, Subtarget);
18247 if (Subtarget.is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
18248 return SDValue();
18249
18250 // Make a 64-bit buffer, and use it to build an FILD.
18251 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
18252 if (SrcVT == MVT::i32) {
18253 SDValue OffsetSlot = DAG.getMemBasePlusOffset(StackSlot, 4, dl);
18254 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
18255 StackSlot, MachinePointerInfo());
18256 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
18257 OffsetSlot, MachinePointerInfo());
18258 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
18259 return Fild;
18260 }
18261
18262 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP")((SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP"
) ? static_cast<void> (0) : __assert_fail ("SrcVT == MVT::i64 && \"Unexpected type in UINT_TO_FP\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 18262, __PRETTY_FUNCTION__))
;
18263 SDValue ValueToStore = Op.getOperand(0);
18264 if (isScalarFPTypeInSSEReg(Op.getValueType()) && !Subtarget.is64Bit())
18265 // Bitcasting to f64 here allows us to do a single 64-bit store from
18266 // an SSE register, avoiding the store forwarding penalty that would come
18267 // with two 32-bit stores.
18268 ValueToStore = DAG.getBitcast(MVT::f64, ValueToStore);
18269 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, ValueToStore, StackSlot,
18270 MachinePointerInfo());
18271 // For i64 source, we need to add the appropriate power of 2 if the input
18272 // was negative. This is the same as the optimization in
18273 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
18274 // we must be careful to do the computation in x87 extended precision, not
18275 // in SSE. (The generic code can't know it's OK to do this, or how to.)
18276 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
18277 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
18278 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
18279 MachineMemOperand::MOLoad, 8, 8);
18280
18281 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
18282 SDValue Ops[] = { Store, StackSlot };
18283 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
18284 MVT::i64, MMO);
18285
18286 APInt FF(32, 0x5F800000ULL);
18287
18288 // Check whether the sign bit is set.
18289 SDValue SignSet = DAG.getSetCC(
18290 dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
18291 Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
18292
18293 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
18294 SDValue FudgePtr = DAG.getConstantPool(
18295 ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
18296
18297 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
18298 SDValue Zero = DAG.getIntPtrConstant(0, dl);
18299 SDValue Four = DAG.getIntPtrConstant(4, dl);
18300 SDValue Offset = DAG.getSelect(dl, Zero.getValueType(), SignSet, Zero, Four);
18301 FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
18302
18303 // Load the value out, extending it from f32 to f80.
18304 // FIXME: Avoid the extend by constructing the right constant pool?
18305 SDValue Fudge = DAG.getExtLoad(
18306 ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), FudgePtr,
18307 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
18308 /* Alignment = */ 4);
18309 // Extend everything to 80 bits to force it to be done on x87.
18310 // TODO: Are there any fast-math-flags to propagate here?
18311 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
18312 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
18313 DAG.getIntPtrConstant(0, dl));
18314}
18315
18316// If the given FP_TO_SINT (IsSigned) or FP_TO_UINT (!IsSigned) operation
18317// is legal, or has an fp128 or f16 source (which needs to be promoted to f32),
18318// just return an SDValue().
18319// Otherwise it is assumed to be a conversion from one of f32, f64 or f80
18320// to i16, i32 or i64, and we lower it to a legal sequence and return the
18321// result.
18322SDValue
18323X86TargetLowering::FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
18324 bool IsSigned) const {
18325 SDLoc DL(Op);
18326
18327 EVT DstTy = Op.getValueType();
18328 EVT TheVT = Op.getOperand(0).getValueType();
18329 auto PtrVT = getPointerTy(DAG.getDataLayout());
18330
18331 if (TheVT != MVT::f32 && TheVT != MVT::f64 && TheVT != MVT::f80) {
18332 // f16 must be promoted before using the lowering in this routine.
18333 // fp128 does not use this lowering.
18334 return SDValue();
18335 }
18336
18337 // If using FIST to compute an unsigned i64, we'll need some fixup
18338 // to handle values above the maximum signed i64. A FIST is always
18339 // used for the 32-bit subtarget, but also for f80 on a 64-bit target.
18340 bool UnsignedFixup = !IsSigned && DstTy == MVT::i64;
18341
18342 if (!IsSigned && DstTy != MVT::i64) {
18343 // Replace the fp-to-uint32 operation with an fp-to-sint64 FIST.
18344 // The low 32 bits of the fist result will have the correct uint32 result.
18345 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT")((DstTy == MVT::i32 && "Unexpected FP_TO_UINT") ? static_cast
<void> (0) : __assert_fail ("DstTy == MVT::i32 && \"Unexpected FP_TO_UINT\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 18345, __PRETTY_FUNCTION__))
;
18346 DstTy = MVT::i64;
18347 }
18348
18349 assert(DstTy.getSimpleVT() <= MVT::i64 &&((DstTy.getSimpleVT() <= MVT::i64 && DstTy.getSimpleVT
() >= MVT::i16 && "Unknown FP_TO_INT to lower!") ?
static_cast<void> (0) : __assert_fail ("DstTy.getSimpleVT() <= MVT::i64 && DstTy.getSimpleVT() >= MVT::i16 && \"Unknown FP_TO_INT to lower!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 18351, __PRETTY_FUNCTION__))
18350 DstTy.getSimpleVT() >= MVT::i16 &&((DstTy.getSimpleVT() <= MVT::i64 && DstTy.getSimpleVT
() >= MVT::i16 && "Unknown FP_TO_INT to lower!") ?
static_cast<void> (0) : __assert_fail ("DstTy.getSimpleVT() <= MVT::i64 && DstTy.getSimpleVT() >= MVT::i16 && \"Unknown FP_TO_INT to lower!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 18351, __PRETTY_FUNCTION__))
18351 "Unknown FP_TO_INT to lower!")((DstTy.getSimpleVT() <= MVT::i64 && DstTy.getSimpleVT
() >= MVT::i16 && "Unknown FP_TO_INT to lower!") ?
static_cast<void> (0) : __assert_fail ("DstTy.getSimpleVT() <= MVT::i64 && DstTy.getSimpleVT() >= MVT::i16 && \"Unknown FP_TO_INT to lower!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 18351, __PRETTY_FUNCTION__))
;
18352
18353 // We lower FP->int64 into FISTP64 followed by a load from a temporary
18354 // stack slot.
18355 MachineFunction &MF = DAG.getMachineFunction();
18356 unsigned MemSize = DstTy.getStoreSize();
18357 int SSFI = MF.getFrameInfo().CreateStackObject(MemSize, MemSize, false);
18358 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
18359
18360 SDValue Chain = DAG.getEntryNode();
18361 SDValue Value = Op.getOperand(0);
18362 SDValue Adjust; // 0x0 or 0x80000000, for result sign bit adjustment.
18363
18364 if (UnsignedFixup) {
18365 //
18366 // Conversion to unsigned i64 is implemented with a select,
18367 // depending on whether the source value fits in the range
18368 // of a signed i64. Let Thresh be the FP equivalent of
18369 // 0x8000000000000000ULL.
18370 //
18371 // Adjust i32 = (Value < Thresh) ? 0 : 0x80000000;
18372 // FistSrc = (Value < Thresh) ? Value : (Value - Thresh);
18373 // Fist-to-mem64 FistSrc
18374 // Add 0 or 0x800...0ULL to the 64-bit result, which is equivalent
18375 // to XOR'ing the high 32 bits with Adjust.
18376 //
18377 // Being a power of 2, Thresh is exactly representable in all FP formats.
18378 // For X87 we'd like to use the smallest FP type for this constant, but
18379 // for DAG type consistency we have to match the FP operand type.
18380
18381 APFloat Thresh(APFloat::IEEEsingle(), APInt(32, 0x5f000000));
18382 LLVM_ATTRIBUTE_UNUSED__attribute__((__unused__)) APFloat::opStatus Status = APFloat::opOK;
18383 bool LosesInfo = false;
18384 if (TheVT == MVT::f64)
18385 // The rounding mode is irrelevant as the conversion should be exact.
18386 Status = Thresh.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven,
18387 &LosesInfo);
18388 else if (TheVT == MVT::f80)
18389 Status = Thresh.convert(APFloat::x87DoubleExtended(),
18390 APFloat::rmNearestTiesToEven, &LosesInfo);
18391
18392 assert(Status == APFloat::opOK && !LosesInfo &&((Status == APFloat::opOK && !LosesInfo && "FP conversion should have been exact"
) ? static_cast<void> (0) : __assert_fail ("Status == APFloat::opOK && !LosesInfo && \"FP conversion should have been exact\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 18393, __PRETTY_FUNCTION__))
18393 "FP conversion should have been exact")((Status == APFloat::opOK && !LosesInfo && "FP conversion should have been exact"
) ? static_cast<void> (0) : __assert_fail ("Status == APFloat::opOK && !LosesInfo && \"FP conversion should have been exact\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 18393, __PRETTY_FUNCTION__))
;
18394
18395 SDValue ThreshVal = DAG.getConstantFP(Thresh, DL, TheVT);
18396
18397 SDValue Cmp = DAG.getSetCC(DL,
18398 getSetCCResultType(DAG.getDataLayout(),
18399 *DAG.getContext(), TheVT),
18400 Value, ThreshVal, ISD::SETLT);
18401 Adjust = DAG.getSelect(DL, MVT::i64, Cmp,
18402 DAG.getConstant(0, DL, MVT::i64),
18403 DAG.getConstant(APInt::getSignMask(64),
18404 DL, MVT::i64));
18405 SDValue Sub = DAG.getNode(ISD::FSUB, DL, TheVT, Value, ThreshVal);
18406 Cmp = DAG.getSetCC(DL, getSetCCResultType(DAG.getDataLayout(),
18407 *DAG.getContext(), TheVT),
18408 Value, ThreshVal, ISD::SETLT);
18409 Value = DAG.getSelect(DL, TheVT, Cmp, Value, Sub);
18410 }
18411
18412 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, SSFI);
18413
18414 // FIXME This causes a redundant load/store if the SSE-class value is already
18415 // in memory, such as if it is on the callstack.
18416 if (isScalarFPTypeInSSEReg(TheVT)) {
18417 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!")((DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!"
) ? static_cast<void> (0) : __assert_fail ("DstTy == MVT::i64 && \"Invalid FP_TO_SINT to lower!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 18417, __PRETTY_FUNCTION__))
;
18418 Chain = DAG.getStore(Chain, DL, Value, StackSlot, MPI);
18419 SDVTList Tys = DAG.getVTList(TheVT, MVT::Other);
18420 SDValue Ops[] = { Chain, StackSlot };
18421
18422 unsigned FLDSize = TheVT.getStoreSize();
18423 assert(FLDSize <= MemSize && "Stack slot not big enough")((FLDSize <= MemSize && "Stack slot not big enough"
) ? static_cast<void> (0) : __assert_fail ("FLDSize <= MemSize && \"Stack slot not big enough\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 18423, __PRETTY_FUNCTION__))
;
18424 MachineMemOperand *MMO = MF.getMachineMemOperand(
18425 MPI, MachineMemOperand::MOLoad, FLDSize, FLDSize);
18426 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, TheVT, MMO);
18427 Chain = Value.getValue(1);
18428 }
18429
18430 // Build the FP_TO_INT*_IN_MEM
18431 MachineMemOperand *MMO = MF.getMachineMemOperand(
18432 MPI, MachineMemOperand::MOStore, MemSize, MemSize);
18433 SDValue Ops[] = { Chain, Value, StackSlot };
18434 SDValue FIST = DAG.getMemIntrinsicNode(X86ISD::FP_TO_INT_IN_MEM, DL,
18435 DAG.getVTList(MVT::Other),
18436 Ops, DstTy, MMO);
18437
18438 SDValue Res = DAG.getLoad(Op.getValueType(), SDLoc(Op), FIST, StackSlot, MPI);
18439
18440 // If we need an unsigned fixup, XOR the result with adjust.
18441 if (UnsignedFixup)
18442 Res = DAG.getNode(ISD::XOR, DL, MVT::i64, Res, Adjust);
18443
18444 return Res;
18445}
18446
18447static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
18448 const X86Subtarget &Subtarget) {
18449 MVT VT = Op->getSimpleValueType(0);
18450 SDValue In = Op->getOperand(0);
18451 MVT InVT = In.getSimpleValueType();
18452 SDLoc dl(Op);
18453
18454 assert(VT.isVector() && InVT.isVector() && "Expected vector type")((VT.isVector() && InVT.isVector() && "Expected vector type"
) ? static_cast<void> (0) : __assert_fail ("VT.isVector() && InVT.isVector() && \"Expected vector type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 18454, __PRETTY_FUNCTION__))
;
18455 assert(VT.getVectorNumElements() == VT.getVectorNumElements() &&((VT.getVectorNumElements() == VT.getVectorNumElements() &&
"Expected same number of elements") ? static_cast<void>
(0) : __assert_fail ("VT.getVectorNumElements() == VT.getVectorNumElements() && \"Expected same number of elements\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 18456, __PRETTY_FUNCTION__))
18456 "Expected same number of elements")((VT.getVectorNumElements() == VT.getVectorNumElements() &&
"Expected same number of elements") ? static_cast<void>
(0) : __assert_fail ("VT.getVectorNumElements() == VT.getVectorNumElements() && \"Expected same number of elements\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 18456, __PRETTY_FUNCTION__))
;
18457 assert((VT.getVectorElementType() == MVT::i16 ||(((VT.getVectorElementType() == MVT::i16 || VT.getVectorElementType
() == MVT::i32 || VT.getVectorElementType() == MVT::i64) &&
"Unexpected element type") ? static_cast<void> (0) : __assert_fail
("(VT.getVectorElementType() == MVT::i16 || VT.getVectorElementType() == MVT::i32 || VT.getVectorElementType() == MVT::i64) && \"Unexpected element type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 18460, __PRETTY_FUNCTION__))
18458 VT.getVectorElementType() == MVT::i32 ||(((VT.getVectorElementType() == MVT::i16 || VT.getVectorElementType
() == MVT::i32 || VT.getVectorElementType() == MVT::i64) &&
"Unexpected element type") ? static_cast<void> (0) : __assert_fail
("(VT.getVectorElementType() == MVT::i16 || VT.getVectorElementType() == MVT::i32 || VT.getVectorElementType() == MVT::i64) && \"Unexpected element type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 18460, __PRETTY_FUNCTION__))
18459 VT.getVectorElementType() == MVT::i64) &&(((VT.getVectorElementType() == MVT::i16 || VT.getVectorElementType
() == MVT::i32 || VT.getVectorElementType() == MVT::i64) &&
"Unexpected element type") ? static_cast<void> (0) : __assert_fail
("(VT.getVectorElementType() == MVT::i16 || VT.getVectorElementType() == MVT::i32 || VT.getVectorElementType() == MVT::i64) && \"Unexpected element type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 18460, __PRETTY_FUNCTION__))
18460 "Unexpected element type")(((VT.getVectorElementType() == MVT::i16 || VT.getVectorElementType
() == MVT::i32 || VT.getVectorElementType() == MVT::i64) &&
"Unexpected element type") ? static_cast<void> (0) : __assert_fail
("(VT.getVectorElementType() == MVT::i16 || VT.getVectorElementType() == MVT::i32 || VT.getVectorElementType() == MVT::i64) && \"Unexpected element type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 18460, __PRETTY_FUNCTION__))
;
18461 assert((InVT.getVectorElementType() == MVT::i8 ||(((InVT.getVectorElementType() == MVT::i8 || InVT.getVectorElementType
() == MVT::i16 || InVT.getVectorElementType() == MVT::i32) &&
"Unexpected element type") ? static_cast<void> (0) : __assert_fail
("(InVT.getVectorElementType() == MVT::i8 || InVT.getVectorElementType() == MVT::i16 || InVT.getVectorElementType() == MVT::i32) && \"Unexpected element type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 18464, __PRETTY_FUNCTION__))
18462 InVT.getVectorElementType() == MVT::i16 ||(((InVT.getVectorElementType() == MVT::i8 || InVT.getVectorElementType
() == MVT::i16 || InVT.getVectorElementType() == MVT::i32) &&
"Unexpected element type") ? static_cast<void> (0) : __assert_fail
("(InVT.getVectorElementType() == MVT::i8 || InVT.getVectorElementType() == MVT::i16 || InVT.getVectorElementType() == MVT::i32) && \"Unexpected element type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 18464, __PRETTY_FUNCTION__))
18463 InVT.getVectorElementType() == MVT::i32) &&(((InVT.getVectorElementType() == MVT::i8 || InVT.getVectorElementType
() == MVT::i16 || InVT.getVectorElementType() == MVT::i32) &&
"Unexpected element type") ? static_cast<void> (0) : __assert_fail
("(InVT.getVectorElementType() == MVT::i8 || InVT.getVectorElementType() == MVT::i16 || InVT.getVectorElementType() == MVT::i32) && \"Unexpected element type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 18464, __PRETTY_FUNCTION__))
18464 "Unexpected element type")(((InVT.getVectorElementType() == MVT::i8 || InVT.getVectorElementType
() == MVT::i16 || InVT.getVectorElementType() == MVT::i32) &&
"Unexpected element type") ? static_cast<void> (0) : __assert_fail
("(InVT.getVectorElementType() == MVT::i8 || InVT.getVectorElementType() == MVT::i16 || InVT.getVectorElementType() == MVT::i32) && \"Unexpected element type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 18464, __PRETTY_FUNCTION__))
;
18465
18466 // Custom legalize v8i8->v8i64 on CPUs without avx512bw.
18467 if (InVT == MVT::v8i8) {
18468 if (!ExperimentalVectorWideningLegalization || VT != MVT::v8i64)
18469 return SDValue();
18470
18471 In = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op),
18472 MVT::v16i8, In, DAG.getUNDEF(MVT::v8i8));
18473 // FIXME: This should be ANY_EXTEND_VECTOR_INREG for ANY_EXTEND input.
18474 return DAG.getNode(ISD::ZERO_EXTEND_VECTOR_INREG, dl, VT, In);
18475 }
18476
18477 if (Subtarget.hasInt256())
18478 return Op;
18479
18480 // Optimize vectors in AVX mode:
18481 //
18482 // v8i16 -> v8i32
18483 // Use vpmovzwd for 4 lower elements v8i16 -> v4i32.
18484 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
18485 // Concat upper and lower parts.
18486 //
18487 // v4i32 -> v4i64
18488 // Use vpmovzdq for 4 lower elements v4i32 -> v2i64.
18489 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
18490 // Concat upper and lower parts.
18491 //
18492
18493 MVT HalfVT = MVT::getVectorVT(VT.getVectorElementType(),
18494 VT.getVectorNumElements() / 2);
18495
18496 SDValue OpLo = DAG.getNode(ISD::ZERO_EXTEND_VECTOR_INREG, dl, HalfVT, In);
18497
18498 // Short-circuit if we can determine that each 128-bit half is the same value.
18499 // Otherwise, this is difficult to match and optimize.
18500 if (auto *Shuf = dyn_cast<ShuffleVectorSDNode>(In))
18501 if (hasIdenticalHalvesShuffleMask(Shuf->getMask()))
18502 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpLo);
18503
18504 SDValue ZeroVec = DAG.getConstant(0, dl, InVT);
18505 SDValue Undef = DAG.getUNDEF(InVT);
18506 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
18507 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
18508 OpHi = DAG.getBitcast(HalfVT, OpHi);
18509
18510 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
18511}
18512
18513// Helper to split and extend a v16i1 mask to v16i8 or v16i16.
18514static SDValue SplitAndExtendv16i1(unsigned ExtOpc, MVT VT, SDValue In,
18515 const SDLoc &dl, SelectionDAG &DAG) {
18516 assert((VT == MVT::v16i8 || VT == MVT::v16i16) && "Unexpected VT.")(((VT == MVT::v16i8 || VT == MVT::v16i16) && "Unexpected VT."
) ? static_cast<void> (0) : __assert_fail ("(VT == MVT::v16i8 || VT == MVT::v16i16) && \"Unexpected VT.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 18516, __PRETTY_FUNCTION__))
;
18517 SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v8i1, In,
18518 DAG.getIntPtrConstant(0, dl));
18519 SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v8i1, In,
18520 DAG.getIntPtrConstant(8, dl));
18521 Lo = DAG.getNode(ExtOpc, dl, MVT::v8i16, Lo);
18522 Hi = DAG.getNode(ExtOpc, dl, MVT::v8i16, Hi);
18523 SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v16i16, Lo, Hi);
18524 return DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
18525}
18526
18527static SDValue LowerZERO_EXTEND_Mask(SDValue Op,
18528 const X86Subtarget &Subtarget,
18529 SelectionDAG &DAG) {
18530 MVT VT = Op->getSimpleValueType(0);
18531 SDValue In = Op->getOperand(0);
18532 MVT InVT = In.getSimpleValueType();
18533 assert(InVT.getVectorElementType() == MVT::i1 && "Unexpected input type!")((InVT.getVectorElementType() == MVT::i1 && "Unexpected input type!"
) ? static_cast<void> (0) : __assert_fail ("InVT.getVectorElementType() == MVT::i1 && \"Unexpected input type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 18533, __PRETTY_FUNCTION__))
;
18534 SDLoc DL(Op);
18535 unsigned NumElts = VT.getVectorNumElements();
18536
18537 // For all vectors, but vXi8 we can just emit a sign_extend and a shift. This
18538 // avoids a constant pool load.
18539 if (VT.getVectorElementType() != MVT::i8) {
18540 SDValue Extend = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, In);
18541 return DAG.getNode(ISD::SRL, DL, VT, Extend,
18542 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT));
18543 }
18544
18545 // Extend VT if BWI is not supported.
18546 MVT ExtVT = VT;
18547 if (!Subtarget.hasBWI()) {
18548 // If v16i32 is to be avoided, we'll need to split and concatenate.
18549 if (NumElts == 16 && !Subtarget.canExtendTo512DQ())
18550 return SplitAndExtendv16i1(ISD::ZERO_EXTEND, VT, In, DL, DAG);
18551
18552 ExtVT = MVT::getVectorVT(MVT::i32, NumElts);
18553 }
18554
18555 // Widen to 512-bits if VLX is not supported.
18556 MVT WideVT = ExtVT;
18557 if (!ExtVT.is512BitVector() && !Subtarget.hasVLX()) {
18558 NumElts *= 512 / ExtVT.getSizeInBits();
18559 InVT = MVT::getVectorVT(MVT::i1, NumElts);
18560 In = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT, DAG.getUNDEF(InVT),
18561 In, DAG.getIntPtrConstant(0, DL));
18562 WideVT = MVT::getVectorVT(ExtVT.getVectorElementType(),
18563 NumElts);
18564 }
18565
18566 SDValue One = DAG.getConstant(1, DL, WideVT);
18567 SDValue Zero = DAG.getConstant(0, DL, WideVT);
18568
18569 SDValue SelectedVal = DAG.getSelect(DL, WideVT, In, One, Zero);
18570
18571 // Truncate if we had to extend above.
18572 if (VT != ExtVT) {
18573 WideVT = MVT::getVectorVT(MVT::i8, NumElts);
18574 SelectedVal = DAG.getNode(ISD::TRUNCATE, DL, WideVT, SelectedVal);
18575 }
18576
18577 // Extract back to 128/256-bit if we widened.
18578 if (WideVT != VT)
18579 SelectedVal = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SelectedVal,
18580 DAG.getIntPtrConstant(0, DL));
18581
18582 return SelectedVal;
18583}
18584
18585static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget &Subtarget,
18586 SelectionDAG &DAG) {
18587 SDValue In = Op.getOperand(0);
18588 MVT SVT = In.getSimpleValueType();
18589
18590 if (SVT.getVectorElementType() == MVT::i1)
18591 return LowerZERO_EXTEND_Mask(Op, Subtarget, DAG);
18592
18593 assert(Subtarget.hasAVX() && "Expected AVX support")((Subtarget.hasAVX() && "Expected AVX support") ? static_cast
<void> (0) : __assert_fail ("Subtarget.hasAVX() && \"Expected AVX support\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 18593, __PRETTY_FUNCTION__))
;
18594 return LowerAVXExtend(Op, DAG, Subtarget);
18595}
18596
18597/// Helper to recursively truncate vector elements in half with PACKSS/PACKUS.
18598/// It makes use of the fact that vectors with enough leading sign/zero bits
18599/// prevent the PACKSS/PACKUS from saturating the results.
18600/// AVX2 (Int256) sub-targets require extra shuffling as the PACK*S operates
18601/// within each 128-bit lane.
18602static SDValue truncateVectorWithPACK(unsigned Opcode, EVT DstVT, SDValue In,
18603 const SDLoc &DL, SelectionDAG &DAG,
18604 const X86Subtarget &Subtarget) {
18605 assert((Opcode == X86ISD::PACKSS || Opcode == X86ISD::PACKUS) &&(((Opcode == X86ISD::PACKSS || Opcode == X86ISD::PACKUS) &&
"Unexpected PACK opcode") ? static_cast<void> (0) : __assert_fail
("(Opcode == X86ISD::PACKSS || Opcode == X86ISD::PACKUS) && \"Unexpected PACK opcode\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 18606, __PRETTY_FUNCTION__))
18606 "Unexpected PACK opcode")(((Opcode == X86ISD::PACKSS || Opcode == X86ISD::PACKUS) &&
"Unexpected PACK opcode") ? static_cast<void> (0) : __assert_fail
("(Opcode == X86ISD::PACKSS || Opcode == X86ISD::PACKUS) && \"Unexpected PACK opcode\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 18606, __PRETTY_FUNCTION__))
;
18607 assert(DstVT.isVector() && "VT not a vector?")((DstVT.isVector() && "VT not a vector?") ? static_cast
<void> (0) : __assert_fail ("DstVT.isVector() && \"VT not a vector?\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 18607, __PRETTY_FUNCTION__))
;
18608
18609 // Requires SSE2 but AVX512 has fast vector truncate.
18610 if (!Subtarget.hasSSE2())
18611 return SDValue();
18612
18613 EVT SrcVT = In.getValueType();
18614
18615 // No truncation required, we might get here due to recursive calls.
18616 if (SrcVT == DstVT)
18617 return In;
18618
18619 // We only support vector truncation to 64bits or greater from a
18620 // 128bits or greater source.
18621 unsigned DstSizeInBits = DstVT.getSizeInBits();
18622 unsigned SrcSizeInBits = SrcVT.getSizeInBits();
18623 if ((DstSizeInBits % 64) != 0 || (SrcSizeInBits % 128) != 0)
18624 return SDValue();
18625
18626 unsigned NumElems = SrcVT.getVectorNumElements();
18627 if (!isPowerOf2_32(NumElems))
18628 return SDValue();
18629
18630 LLVMContext &Ctx = *DAG.getContext();
18631 assert(DstVT.getVectorNumElements() == NumElems && "Illegal truncation")((DstVT.getVectorNumElements() == NumElems && "Illegal truncation"
) ? static_cast<void> (0) : __assert_fail ("DstVT.getVectorNumElements() == NumElems && \"Illegal truncation\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 18631, __PRETTY_FUNCTION__))
;
18632 assert(SrcSizeInBits > DstSizeInBits && "Illegal truncation")((SrcSizeInBits > DstSizeInBits && "Illegal truncation"
) ? static_cast<void> (0) : __assert_fail ("SrcSizeInBits > DstSizeInBits && \"Illegal truncation\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 18632, __PRETTY_FUNCTION__))
;
18633
18634 EVT PackedSVT = EVT::getIntegerVT(Ctx, SrcVT.getScalarSizeInBits() / 2);
18635
18636 // Pack to the largest type possible:
18637 // vXi64/vXi32 -> PACK*SDW and vXi16 -> PACK*SWB.
18638 EVT InVT = MVT::i16, OutVT = MVT::i8;
18639 if (SrcVT.getScalarSizeInBits() > 16 &&
18640 (Opcode == X86ISD::PACKSS || Subtarget.hasSSE41())) {
18641 InVT = MVT::i32;
18642 OutVT = MVT::i16;
18643 }
18644
18645 // 128bit -> 64bit truncate - PACK 128-bit src in the lower subvector.
18646 if (SrcVT.is128BitVector()) {
18647 InVT = EVT::getVectorVT(Ctx, InVT, 128 / InVT.getSizeInBits());
18648 OutVT = EVT::getVectorVT(Ctx, OutVT, 128 / OutVT.getSizeInBits());
18649 In = DAG.getBitcast(InVT, In);
18650 SDValue Res = DAG.getNode(Opcode, DL, OutVT, In, In);
18651 Res = extractSubVector(Res, 0, DAG, DL, 64);
18652 return DAG.getBitcast(DstVT, Res);
18653 }
18654
18655 // Extract lower/upper subvectors.
18656 unsigned NumSubElts = NumElems / 2;
18657 SDValue Lo = extractSubVector(In, 0 * NumSubElts, DAG, DL, SrcSizeInBits / 2);
18658 SDValue Hi = extractSubVector(In, 1 * NumSubElts, DAG, DL, SrcSizeInBits / 2);
18659
18660 unsigned SubSizeInBits = SrcSizeInBits / 2;
18661 InVT = EVT::getVectorVT(Ctx, InVT, SubSizeInBits / InVT.getSizeInBits());
18662 OutVT = EVT::getVectorVT(Ctx, OutVT, SubSizeInBits / OutVT.getSizeInBits());
18663
18664 // 256bit -> 128bit truncate - PACK lower/upper 128-bit subvectors.
18665 if (SrcVT.is256BitVector() && DstVT.is128BitVector()) {
18666 Lo = DAG.getBitcast(InVT, Lo);
18667 Hi = DAG.getBitcast(InVT, Hi);
18668 SDValue Res = DAG.getNode(Opcode, DL, OutVT, Lo, Hi);
18669 return DAG.getBitcast(DstVT, Res);
18670 }
18671
18672 // AVX2: 512bit -> 256bit truncate - PACK lower/upper 256-bit subvectors.
18673 // AVX2: 512bit -> 128bit truncate - PACK(PACK, PACK).
18674 if (SrcVT.is512BitVector() && Subtarget.hasInt256()) {
18675 Lo = DAG.getBitcast(InVT, Lo);
18676 Hi = DAG.getBitcast(InVT, Hi);
18677 SDValue Res = DAG.getNode(Opcode, DL, OutVT, Lo, Hi);
18678
18679 // 256-bit PACK(ARG0, ARG1) leaves us with ((LO0,LO1),(HI0,HI1)),
18680 // so we need to shuffle to get ((LO0,HI0),(LO1,HI1)).
18681 Res = DAG.getBitcast(MVT::v4i64, Res);
18682 Res = DAG.getVectorShuffle(MVT::v4i64, DL, Res, Res, {0, 2, 1, 3});
18683
18684 if (DstVT.is256BitVector())
18685 return DAG.getBitcast(DstVT, Res);
18686
18687 // If 512bit -> 128bit truncate another stage.
18688 EVT PackedVT = EVT::getVectorVT(Ctx, PackedSVT, NumElems);
18689 Res = DAG.getBitcast(PackedVT, Res);
18690 return truncateVectorWithPACK(Opcode, DstVT, Res, DL, DAG, Subtarget);
18691 }
18692
18693 // Recursively pack lower/upper subvectors, concat result and pack again.
18694 assert(SrcSizeInBits >= 256 && "Expected 256-bit vector or greater")((SrcSizeInBits >= 256 && "Expected 256-bit vector or greater"
) ? static_cast<void> (0) : __assert_fail ("SrcSizeInBits >= 256 && \"Expected 256-bit vector or greater\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 18694, __PRETTY_FUNCTION__))
;
18695 EVT PackedVT = EVT::getVectorVT(Ctx, PackedSVT, NumSubElts);
18696 Lo = truncateVectorWithPACK(Opcode, PackedVT, Lo, DL, DAG, Subtarget);
18697 Hi = truncateVectorWithPACK(Opcode, PackedVT, Hi, DL, DAG, Subtarget);
18698
18699 PackedVT = EVT::getVectorVT(Ctx, PackedSVT, NumElems);
18700 SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, PackedVT, Lo, Hi);
18701 return truncateVectorWithPACK(Opcode, DstVT, Res, DL, DAG, Subtarget);
18702}
18703
18704static SDValue LowerTruncateVecI1(SDValue Op, SelectionDAG &DAG,
18705 const X86Subtarget &Subtarget) {
18706
18707 SDLoc DL(Op);
18708 MVT VT = Op.getSimpleValueType();
18709 SDValue In = Op.getOperand(0);
18710 MVT InVT = In.getSimpleValueType();
18711
18712 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type.")((VT.getVectorElementType() == MVT::i1 && "Unexpected vector type."
) ? static_cast<void> (0) : __assert_fail ("VT.getVectorElementType() == MVT::i1 && \"Unexpected vector type.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 18712, __PRETTY_FUNCTION__))
;
18713
18714 // Shift LSB to MSB and use VPMOVB/W2M or TESTD/Q.
18715 unsigned ShiftInx = InVT.getScalarSizeInBits() - 1;
18716 if (InVT.getScalarSizeInBits() <= 16) {
18717 if (Subtarget.hasBWI()) {
18718 // legal, will go to VPMOVB2M, VPMOVW2M
18719 if (DAG.ComputeNumSignBits(In) < InVT.getScalarSizeInBits()) {
18720 // We need to shift to get the lsb into sign position.
18721 // Shift packed bytes not supported natively, bitcast to word
18722 MVT ExtVT = MVT::getVectorVT(MVT::i16, InVT.getSizeInBits()/16);
18723 In = DAG.getNode(ISD::SHL, DL, ExtVT,
18724 DAG.getBitcast(ExtVT, In),
18725 DAG.getConstant(ShiftInx, DL, ExtVT));
18726 In = DAG.getBitcast(InVT, In);
18727 }
18728 return DAG.getSetCC(DL, VT, DAG.getConstant(0, DL, InVT),
18729 In, ISD::SETGT);
18730 }
18731 // Use TESTD/Q, extended vector to packed dword/qword.
18732 assert((InVT.is256BitVector() || InVT.is128BitVector()) &&(((InVT.is256BitVector() || InVT.is128BitVector()) &&
"Unexpected vector type.") ? static_cast<void> (0) : __assert_fail
("(InVT.is256BitVector() || InVT.is128BitVector()) && \"Unexpected vector type.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 18733, __PRETTY_FUNCTION__))
18733 "Unexpected vector type.")(((InVT.is256BitVector() || InVT.is128BitVector()) &&
"Unexpected vector type.") ? static_cast<void> (0) : __assert_fail
("(InVT.is256BitVector() || InVT.is128BitVector()) && \"Unexpected vector type.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 18733, __PRETTY_FUNCTION__))
;
18734 unsigned NumElts = InVT.getVectorNumElements();
18735 assert((NumElts == 8 || NumElts == 16) && "Unexpected number of elements")(((NumElts == 8 || NumElts == 16) && "Unexpected number of elements"
) ? static_cast<void> (0) : __assert_fail ("(NumElts == 8 || NumElts == 16) && \"Unexpected number of elements\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 18735, __PRETTY_FUNCTION__))
;
18736 // We need to change to a wider element type that we have support for.
18737 // For 8 element vectors this is easy, we either extend to v8i32 or v8i64.
18738 // For 16 element vectors we extend to v16i32 unless we are explicitly
18739 // trying to avoid 512-bit vectors. If we are avoiding 512-bit vectors
18740 // we need to split into two 8 element vectors which we can extend to v8i32,
18741 // truncate and concat the results. There's an additional complication if
18742 // the original type is v16i8. In that case we can't split the v16i8 so
18743 // first we pre-extend it to v16i16 which we can split to v8i16, then extend
18744 // to v8i32, truncate that to v8i1 and concat the two halves.
18745 if (NumElts == 16 && !Subtarget.canExtendTo512DQ()) {
18746 if (InVT == MVT::v16i8) {
18747 // First we need to sign extend up to 256-bits so we can split that.
18748 InVT = MVT::v16i16;
18749 In = DAG.getNode(ISD::SIGN_EXTEND, DL, InVT, In);
18750 }
18751 SDValue Lo = extract128BitVector(In, 0, DAG, DL);
18752 SDValue Hi = extract128BitVector(In, 8, DAG, DL);
18753 // We're split now, just emit two truncates and a concat. The two
18754 // truncates will trigger legalization to come back to this function.
18755 Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i1, Lo);
18756 Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i1, Hi);
18757 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
18758 }
18759 // We either have 8 elements or we're allowed to use 512-bit vectors.
18760 // If we have VLX, we want to use the narrowest vector that can get the
18761 // job done so we use vXi32.
18762 MVT EltVT = Subtarget.hasVLX() ? MVT::i32 : MVT::getIntegerVT(512/NumElts);
18763 MVT ExtVT = MVT::getVectorVT(EltVT, NumElts);
18764 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
18765 InVT = ExtVT;
18766 ShiftInx = InVT.getScalarSizeInBits() - 1;
18767 }
18768
18769 if (DAG.ComputeNumSignBits(In) < InVT.getScalarSizeInBits()) {
18770 // We need to shift to get the lsb into sign position.
18771 In = DAG.getNode(ISD::SHL, DL, InVT, In,
18772 DAG.getConstant(ShiftInx, DL, InVT));
18773 }
18774 // If we have DQI, emit a pattern that will be iseled as vpmovq2m/vpmovd2m.
18775 if (Subtarget.hasDQI())
18776 return DAG.getSetCC(DL, VT, DAG.getConstant(0, DL, InVT), In, ISD::SETGT);
18777 return DAG.getSetCC(DL, VT, In, DAG.getConstant(0, DL, InVT), ISD::SETNE);
18778}
18779
18780SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
18781 SDLoc DL(Op);
18782 MVT VT = Op.getSimpleValueType();
18783 SDValue In = Op.getOperand(0);
18784 MVT InVT = In.getSimpleValueType();
18785 unsigned InNumEltBits = InVT.getScalarSizeInBits();
18786
18787 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&((VT.getVectorNumElements() == InVT.getVectorNumElements() &&
"Invalid TRUNCATE operation") ? static_cast<void> (0) :
__assert_fail ("VT.getVectorNumElements() == InVT.getVectorNumElements() && \"Invalid TRUNCATE operation\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 18788, __PRETTY_FUNCTION__))
18788 "Invalid TRUNCATE operation")((VT.getVectorNumElements() == InVT.getVectorNumElements() &&
"Invalid TRUNCATE operation") ? static_cast<void> (0) :
__assert_fail ("VT.getVectorNumElements() == InVT.getVectorNumElements() && \"Invalid TRUNCATE operation\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 18788, __PRETTY_FUNCTION__))
;
18789
18790 // If called by the legalizer just return.
18791 if (!DAG.getTargetLoweringInfo().isTypeLegal(InVT))
18792 return SDValue();
18793
18794 if (VT.getVectorElementType() == MVT::i1)
18795 return LowerTruncateVecI1(Op, DAG, Subtarget);
18796
18797 // vpmovqb/w/d, vpmovdb/w, vpmovwb
18798 if (Subtarget.hasAVX512()) {
18799 // word to byte only under BWI. Otherwise we have to promoted to v16i32
18800 // and then truncate that. But we should only do that if we haven't been
18801 // asked to avoid 512-bit vectors. The actual promotion to v16i32 will be
18802 // handled by isel patterns.
18803 if (InVT != MVT::v16i16 || Subtarget.hasBWI() ||
18804 Subtarget.canExtendTo512DQ())
18805 return Op;
18806 }
18807
18808 unsigned NumPackedSignBits = std::min<unsigned>(VT.getScalarSizeInBits(), 16);
18809 unsigned NumPackedZeroBits = Subtarget.hasSSE41() ? NumPackedSignBits : 8;
18810
18811 // Truncate with PACKUS if we are truncating a vector with leading zero bits
18812 // that extend all the way to the packed/truncated value.
18813 // Pre-SSE41 we can only use PACKUSWB.
18814 KnownBits Known = DAG.computeKnownBits(In);
18815 if ((InNumEltBits - NumPackedZeroBits) <= Known.countMinLeadingZeros())
18816 if (SDValue V =
18817 truncateVectorWithPACK(X86ISD::PACKUS, VT, In, DL, DAG, Subtarget))
18818 return V;
18819
18820 // Truncate with PACKSS if we are truncating a vector with sign-bits that
18821 // extend all the way to the packed/truncated value.
18822 if ((InNumEltBits - NumPackedSignBits) < DAG.ComputeNumSignBits(In))
18823 if (SDValue V =
18824 truncateVectorWithPACK(X86ISD::PACKSS, VT, In, DL, DAG, Subtarget))
18825 return V;
18826
18827 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
18828 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
18829 if (Subtarget.hasInt256()) {
18830 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
18831 In = DAG.getBitcast(MVT::v8i32, In);
18832 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, In, ShufMask);
18833 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
18834 DAG.getIntPtrConstant(0, DL));
18835 }
18836
18837 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
18838 DAG.getIntPtrConstant(0, DL));
18839 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
18840 DAG.getIntPtrConstant(2, DL));
18841 OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
18842 OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
18843 static const int ShufMask[] = {0, 2, 4, 6};
18844 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
18845 }
18846
18847 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
18848 // On AVX2, v8i32 -> v8i16 becomes PSHUFB.
18849 if (Subtarget.hasInt256()) {
18850 In = DAG.getBitcast(MVT::v32i8, In);
18851
18852 // The PSHUFB mask:
18853 static const int ShufMask1[] = { 0, 1, 4, 5, 8, 9, 12, 13,
18854 -1, -1, -1, -1, -1, -1, -1, -1,
18855 16, 17, 20, 21, 24, 25, 28, 29,
18856 -1, -1, -1, -1, -1, -1, -1, -1 };
18857 In = DAG.getVectorShuffle(MVT::v32i8, DL, In, In, ShufMask1);
18858 In = DAG.getBitcast(MVT::v4i64, In);
18859
18860 static const int ShufMask2[] = {0, 2, -1, -1};
18861 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, In, ShufMask2);
18862 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
18863 DAG.getIntPtrConstant(0, DL));
18864 return DAG.getBitcast(VT, In);
18865 }
18866
18867 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
18868 DAG.getIntPtrConstant(0, DL));
18869
18870 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
18871 DAG.getIntPtrConstant(4, DL));
18872
18873 OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
18874 OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
18875
18876 // The PSHUFB mask:
18877 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
18878 -1, -1, -1, -1, -1, -1, -1, -1};
18879
18880 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, OpLo, ShufMask1);
18881 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, OpHi, ShufMask1);
18882
18883 OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
18884 OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
18885
18886 // The MOVLHPS Mask:
18887 static const int ShufMask2[] = {0, 1, 4, 5};
18888 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
18889 return DAG.getBitcast(MVT::v8i16, res);
18890 }
18891
18892 if (VT == MVT::v16i8 && InVT == MVT::v16i16) {
18893 // Use an AND to zero uppper bits for PACKUS.
18894 In = DAG.getNode(ISD::AND, DL, InVT, In, DAG.getConstant(255, DL, InVT));
18895
18896 SDValue InLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i16, In,
18897 DAG.getIntPtrConstant(0, DL));
18898 SDValue InHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i16, In,
18899 DAG.getIntPtrConstant(8, DL));
18900 return DAG.getNode(X86ISD::PACKUS, DL, VT, InLo, InHi);
18901 }
18902
18903 // Handle truncation of V256 to V128 using shuffles.
18904 assert(VT.is128BitVector() && InVT.is256BitVector() && "Unexpected types!")((VT.is128BitVector() && InVT.is256BitVector() &&
"Unexpected types!") ? static_cast<void> (0) : __assert_fail
("VT.is128BitVector() && InVT.is256BitVector() && \"Unexpected types!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 18904, __PRETTY_FUNCTION__))
;
18905
18906 assert(Subtarget.hasAVX() && "256-bit vector without AVX!")((Subtarget.hasAVX() && "256-bit vector without AVX!"
) ? static_cast<void> (0) : __assert_fail ("Subtarget.hasAVX() && \"256-bit vector without AVX!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 18906, __PRETTY_FUNCTION__))
;
18907
18908 unsigned NumElems = VT.getVectorNumElements();
18909 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
18910
18911 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
18912 // Prepare truncation shuffle mask
18913 for (unsigned i = 0; i != NumElems; ++i)
18914 MaskVec[i] = i * 2;
18915 In = DAG.getBitcast(NVT, In);
18916 SDValue V = DAG.getVectorShuffle(NVT, DL, In, In, MaskVec);
18917 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
18918 DAG.getIntPtrConstant(0, DL));
18919}
18920
18921SDValue X86TargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
18922 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT;
18923 MVT VT = Op.getSimpleValueType();
18924 SDValue Src = Op.getOperand(0);
18925 MVT SrcVT = Src.getSimpleValueType();
18926 SDLoc dl(Op);
18927
18928 if (VT.isVector()) {
18929 if (VT == MVT::v2i1 && SrcVT == MVT::v2f64) {
18930 MVT ResVT = MVT::v4i32;
18931 MVT TruncVT = MVT::v4i1;
18932 unsigned Opc = IsSigned ? X86ISD::CVTTP2SI : X86ISD::CVTTP2UI;
18933 if (!IsSigned && !Subtarget.hasVLX()) {
18934 // Widen to 512-bits.
18935 ResVT = MVT::v8i32;
18936 TruncVT = MVT::v8i1;
18937 Opc = ISD::FP_TO_UINT;
18938 Src = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, MVT::v8f64,
18939 DAG.getUNDEF(MVT::v8f64),
18940 Src, DAG.getIntPtrConstant(0, dl));
18941 }
18942 SDValue Res = DAG.getNode(Opc, dl, ResVT, Src);
18943 Res = DAG.getNode(ISD::TRUNCATE, dl, TruncVT, Res);
18944 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i1, Res,
18945 DAG.getIntPtrConstant(0, dl));
18946 }
18947
18948 assert(Subtarget.hasDQI() && Subtarget.hasVLX() && "Requires AVX512DQVL!")((Subtarget.hasDQI() && Subtarget.hasVLX() &&
"Requires AVX512DQVL!") ? static_cast<void> (0) : __assert_fail
("Subtarget.hasDQI() && Subtarget.hasVLX() && \"Requires AVX512DQVL!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 18948, __PRETTY_FUNCTION__))
;
18949 if (VT == MVT::v2i64 && SrcVT == MVT::v2f32) {
18950 return DAG.getNode(IsSigned ? X86ISD::CVTTP2SI : X86ISD::CVTTP2UI, dl, VT,
18951 DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32, Src,
18952 DAG.getUNDEF(MVT::v2f32)));
18953 }
18954
18955 return SDValue();
18956 }
18957
18958 assert(!VT.isVector())((!VT.isVector()) ? static_cast<void> (0) : __assert_fail
("!VT.isVector()", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 18958, __PRETTY_FUNCTION__))
;
18959
18960 bool UseSSEReg = isScalarFPTypeInSSEReg(SrcVT);
18961
18962 if (!IsSigned && Subtarget.hasAVX512()) {
18963 // Conversions from f32/f64 should be legal.
18964 if (UseSSEReg)
18965 return Op;
18966
18967 // Use default expansion.
18968 if (VT == MVT::i64)
18969 return SDValue();
18970 }
18971
18972 // Promote i16 to i32 if we can use a SSE operation.
18973 if (VT == MVT::i16 && UseSSEReg) {
18974 assert(IsSigned && "Expected i16 FP_TO_UINT to have been promoted!")((IsSigned && "Expected i16 FP_TO_UINT to have been promoted!"
) ? static_cast<void> (0) : __assert_fail ("IsSigned && \"Expected i16 FP_TO_UINT to have been promoted!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 18974, __PRETTY_FUNCTION__))
;
18975 SDValue Res = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src);
18976 return DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
18977 }
18978
18979 // If this is a SINT_TO_FP using SSEReg we're done.
18980 if (UseSSEReg && IsSigned)
18981 return Op;
18982
18983 // Fall back to X87.
18984 if (SDValue V = FP_TO_INTHelper(Op, DAG, IsSigned))
18985 return V;
18986
18987 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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 18987)
;
18988}
18989
18990static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
18991 SDLoc DL(Op);
18992 MVT VT = Op.getSimpleValueType();
18993 SDValue In = Op.getOperand(0);
18994 MVT SVT = In.getSimpleValueType();
18995
18996 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!")((SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!"
) ? static_cast<void> (0) : __assert_fail ("SVT == MVT::v2f32 && \"Only customize MVT::v2f32 type legalization!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 18996, __PRETTY_FUNCTION__))
;
18997
18998 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
18999 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
19000 In, DAG.getUNDEF(SVT)));
19001}
19002
19003/// Horizontal vector math instructions may be slower than normal math with
19004/// shuffles. Limit horizontal op codegen based on size/speed trade-offs, uarch
19005/// implementation, and likely shuffle complexity of the alternate sequence.
19006static bool shouldUseHorizontalOp(bool IsSingleSource, SelectionDAG &DAG,
19007 const X86Subtarget &Subtarget) {
19008 bool IsOptimizingSize = DAG.getMachineFunction().getFunction().hasOptSize();
19009 bool HasFastHOps = Subtarget.hasFastHorizontalOps();
19010 return !IsSingleSource || IsOptimizingSize || HasFastHOps;
19011}
19012
19013/// Depending on uarch and/or optimizing for size, we might prefer to use a
19014/// vector operation in place of the typical scalar operation.
19015static SDValue lowerAddSubToHorizontalOp(SDValue Op, SelectionDAG &DAG,
19016 const X86Subtarget &Subtarget) {
19017 // If both operands have other uses, this is probably not profitable.
19018 SDValue LHS = Op.getOperand(0);
19019 SDValue RHS = Op.getOperand(1);
19020 if (!LHS.hasOneUse() && !RHS.hasOneUse())
19021 return Op;
19022
19023 // FP horizontal add/sub were added with SSE3. Integer with SSSE3.
19024 bool IsFP = Op.getSimpleValueType().isFloatingPoint();
19025 if (IsFP && !Subtarget.hasSSE3())
19026 return Op;
19027 if (!IsFP && !Subtarget.hasSSSE3())
19028 return Op;
19029
19030 // Extract from a common vector.
19031 if (LHS.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
19032 RHS.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
19033 LHS.getOperand(0) != RHS.getOperand(0) ||
19034 !isa<ConstantSDNode>(LHS.getOperand(1)) ||
19035 !isa<ConstantSDNode>(RHS.getOperand(1)) ||
19036 !shouldUseHorizontalOp(true, DAG, Subtarget))
19037 return Op;
19038
19039 // Allow commuted 'hadd' ops.
19040 // TODO: Allow commuted (f)sub by negating the result of (F)HSUB?
19041 unsigned HOpcode;
19042 switch (Op.getOpcode()) {
19043 case ISD::ADD: HOpcode = X86ISD::HADD; break;
19044 case ISD::SUB: HOpcode = X86ISD::HSUB; break;
19045 case ISD::FADD: HOpcode = X86ISD::FHADD; break;
19046 case ISD::FSUB: HOpcode = X86ISD::FHSUB; break;
19047 default:
19048 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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 19048)
;
19049 }
19050 unsigned LExtIndex = LHS.getConstantOperandVal(1);
19051 unsigned RExtIndex = RHS.getConstantOperandVal(1);
19052 if ((LExtIndex & 1) == 1 && (RExtIndex & 1) == 0 &&
19053 (HOpcode == X86ISD::HADD || HOpcode == X86ISD::FHADD))
19054 std::swap(LExtIndex, RExtIndex);
19055
19056 if ((LExtIndex & 1) != 0 || RExtIndex != (LExtIndex + 1))
19057 return Op;
19058
19059 SDValue X = LHS.getOperand(0);
19060 EVT VecVT = X.getValueType();
19061 unsigned BitWidth = VecVT.getSizeInBits();
19062 unsigned NumLanes = BitWidth / 128;
19063 unsigned NumEltsPerLane = VecVT.getVectorNumElements() / NumLanes;
19064 assert((BitWidth == 128 || BitWidth == 256 || BitWidth == 512) &&(((BitWidth == 128 || BitWidth == 256 || BitWidth == 512) &&
"Not expecting illegal vector widths here") ? static_cast<
void> (0) : __assert_fail ("(BitWidth == 128 || BitWidth == 256 || BitWidth == 512) && \"Not expecting illegal vector widths here\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 19065, __PRETTY_FUNCTION__))
19065 "Not expecting illegal vector widths here")(((BitWidth == 128 || BitWidth == 256 || BitWidth == 512) &&
"Not expecting illegal vector widths here") ? static_cast<
void> (0) : __assert_fail ("(BitWidth == 128 || BitWidth == 256 || BitWidth == 512) && \"Not expecting illegal vector widths here\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 19065, __PRETTY_FUNCTION__))
;
19066
19067 // Creating a 256-bit horizontal op would be wasteful, and there is no 512-bit
19068 // equivalent, so extract the 256/512-bit source op to 128-bit if we can.
19069 SDLoc DL(Op);
19070 if (BitWidth == 256 || BitWidth == 512) {
19071 unsigned LaneIdx = LExtIndex / NumEltsPerLane;
19072 X = extract128BitVector(X, LaneIdx * NumEltsPerLane, DAG, DL);
19073 LExtIndex %= NumEltsPerLane;
19074 }
19075
19076 // add (extractelt (X, 0), extractelt (X, 1)) --> extractelt (hadd X, X), 0
19077 // add (extractelt (X, 1), extractelt (X, 0)) --> extractelt (hadd X, X), 0
19078 // add (extractelt (X, 2), extractelt (X, 3)) --> extractelt (hadd X, X), 1
19079 // sub (extractelt (X, 0), extractelt (X, 1)) --> extractelt (hsub X, X), 0
19080 SDValue HOp = DAG.getNode(HOpcode, DL, X.getValueType(), X, X);
19081 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, Op.getSimpleValueType(), HOp,
19082 DAG.getIntPtrConstant(LExtIndex / 2, DL));
19083}
19084
19085/// Depending on uarch and/or optimizing for size, we might prefer to use a
19086/// vector operation in place of the typical scalar operation.
19087static SDValue lowerFaddFsub(SDValue Op, SelectionDAG &DAG,
19088 const X86Subtarget &Subtarget) {
19089 assert((Op.getValueType() == MVT::f32 || Op.getValueType() == MVT::f64) &&(((Op.getValueType() == MVT::f32 || Op.getValueType() == MVT::
f64) && "Only expecting float/double") ? static_cast<
void> (0) : __assert_fail ("(Op.getValueType() == MVT::f32 || Op.getValueType() == MVT::f64) && \"Only expecting float/double\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 19090, __PRETTY_FUNCTION__))
19090 "Only expecting float/double")(((Op.getValueType() == MVT::f32 || Op.getValueType() == MVT::
f64) && "Only expecting float/double") ? static_cast<
void> (0) : __assert_fail ("(Op.getValueType() == MVT::f32 || Op.getValueType() == MVT::f64) && \"Only expecting float/double\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 19090, __PRETTY_FUNCTION__))
;
19091 return lowerAddSubToHorizontalOp(Op, DAG, Subtarget);
19092}
19093
19094/// The only differences between FABS and FNEG are the mask and the logic op.
19095/// FNEG also has a folding opportunity for FNEG(FABS(x)).
19096static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
19097 assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&(((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG
) && "Wrong opcode for lowering FABS or FNEG.") ? static_cast
<void> (0) : __assert_fail ("(Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) && \"Wrong opcode for lowering FABS or FNEG.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 19098, __PRETTY_FUNCTION__))
19098 "Wrong opcode for lowering FABS or FNEG.")(((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG
) && "Wrong opcode for lowering FABS or FNEG.") ? static_cast
<void> (0) : __assert_fail ("(Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) && \"Wrong opcode for lowering FABS or FNEG.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 19098, __PRETTY_FUNCTION__))
;
19099
19100 bool IsFABS = (Op.getOpcode() == ISD::FABS);
19101
19102 // If this is a FABS and it has an FNEG user, bail out to fold the combination
19103 // into an FNABS. We'll lower the FABS after that if it is still in use.
19104 if (IsFABS)
19105 for (SDNode *User : Op->uses())
19106 if (User->getOpcode() == ISD::FNEG)
19107 return Op;
19108
19109 SDLoc dl(Op);
19110 MVT VT = Op.getSimpleValueType();
19111
19112 bool IsF128 = (VT == MVT::f128);
19113 assert((VT == MVT::f64 || VT == MVT::f32 || VT == MVT::f128 ||(((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"
) ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 19116, __PRETTY_FUNCTION__))
19114 VT == MVT::v2f64 || VT == MVT::v4f64 || VT == MVT::v4f32 ||(((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"
) ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 19116, __PRETTY_FUNCTION__))
19115 VT == MVT::v8f32 || VT == MVT::v8f64 || VT == MVT::v16f32) &&(((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"
) ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 19116, __PRETTY_FUNCTION__))
19116 "Unexpected type in LowerFABSorFNEG")(((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"
) ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 19116, __PRETTY_FUNCTION__))
;
19117
19118 // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
19119 // decide if we should generate a 16-byte constant mask when we only need 4 or
19120 // 8 bytes for the scalar case.
19121
19122 // There are no scalar bitwise logical SSE/AVX instructions, so we
19123 // generate a 16-byte vector constant and logic op even for the scalar case.
19124 // Using a 16-byte mask allows folding the load of the mask with
19125 // the logic op, so it can save (~4 bytes) on code size.
19126 bool IsFakeVector = !VT.isVector() && !IsF128;
19127 MVT LogicVT = VT;
19128 if (IsFakeVector)
19129 LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
19130
19131 unsigned EltBits = VT.getScalarSizeInBits();
19132 // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
19133 APInt MaskElt = IsFABS ? APInt::getSignedMaxValue(EltBits) :
19134 APInt::getSignMask(EltBits);
19135 const fltSemantics &Sem = SelectionDAG::EVTToAPFloatSemantics(VT);
19136 SDValue Mask = DAG.getConstantFP(APFloat(Sem, MaskElt), dl, LogicVT);
19137
19138 SDValue Op0 = Op.getOperand(0);
19139 bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
19140 unsigned LogicOp = IsFABS ? X86ISD::FAND :
19141 IsFNABS ? X86ISD::FOR :
19142 X86ISD::FXOR;
19143 SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
19144
19145 if (VT.isVector() || IsF128)
19146 return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
19147
19148 // For the scalar case extend to a 128-bit vector, perform the logic op,
19149 // and extract the scalar result back out.
19150 Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
19151 SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
19152 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
19153 DAG.getIntPtrConstant(0, dl));
19154}
19155
19156static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
19157 SDValue Mag = Op.getOperand(0);
19158 SDValue Sign = Op.getOperand(1);
19159 SDLoc dl(Op);
19160
19161 // If the sign operand is smaller, extend it first.
19162 MVT VT = Op.getSimpleValueType();
19163 if (Sign.getSimpleValueType().bitsLT(VT))
19164 Sign = DAG.getNode(ISD::FP_EXTEND, dl, VT, Sign);
19165
19166 // And if it is bigger, shrink it first.
19167 if (Sign.getSimpleValueType().bitsGT(VT))
19168 Sign = DAG.getNode(ISD::FP_ROUND, dl, VT, Sign, DAG.getIntPtrConstant(1, dl));
19169
19170 // At this point the operands and the result should have the same
19171 // type, and that won't be f80 since that is not custom lowered.
19172 bool IsF128 = (VT == MVT::f128);
19173 assert((VT == MVT::f64 || VT == MVT::f32 || VT == MVT::f128 ||(((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"
) ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 19176, __PRETTY_FUNCTION__))
19174 VT == MVT::v2f64 || VT == MVT::v4f64 || VT == MVT::v4f32 ||(((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"
) ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 19176, __PRETTY_FUNCTION__))
19175 VT == MVT::v8f32 || VT == MVT::v8f64 || VT == MVT::v16f32) &&(((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"
) ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 19176, __PRETTY_FUNCTION__))
19176 "Unexpected type in LowerFCOPYSIGN")(((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"
) ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 19176, __PRETTY_FUNCTION__))
;
19177
19178 const fltSemantics &Sem = SelectionDAG::EVTToAPFloatSemantics(VT);
19179
19180 // Perform all scalar logic operations as 16-byte vectors because there are no
19181 // scalar FP logic instructions in SSE.
19182 // TODO: This isn't necessary. If we used scalar types, we might avoid some
19183 // unnecessary splats, but we might miss load folding opportunities. Should
19184 // this decision be based on OptimizeForSize?
19185 bool IsFakeVector = !VT.isVector() && !IsF128;
19186 MVT LogicVT = VT;
19187 if (IsFakeVector)
19188 LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
19189
19190 // The mask constants are automatically splatted for vector types.
19191 unsigned EltSizeInBits = VT.getScalarSizeInBits();
19192 SDValue SignMask = DAG.getConstantFP(
19193 APFloat(Sem, APInt::getSignMask(EltSizeInBits)), dl, LogicVT);
19194 SDValue MagMask = DAG.getConstantFP(
19195 APFloat(Sem, APInt::getSignedMaxValue(EltSizeInBits)), dl, LogicVT);
19196
19197 // First, clear all bits but the sign bit from the second operand (sign).
19198 if (IsFakeVector)
19199 Sign = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Sign);
19200 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Sign, SignMask);
19201
19202 // Next, clear the sign bit from the first operand (magnitude).
19203 // TODO: If we had general constant folding for FP logic ops, this check
19204 // wouldn't be necessary.
19205 SDValue MagBits;
19206 if (ConstantFPSDNode *Op0CN = isConstOrConstSplatFP(Mag)) {
19207 APFloat APF = Op0CN->getValueAPF();
19208 APF.clearSign();
19209 MagBits = DAG.getConstantFP(APF, dl, LogicVT);
19210 } else {
19211 // If the magnitude operand wasn't a constant, we need to AND out the sign.
19212 if (IsFakeVector)
19213 Mag = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Mag);
19214 MagBits = DAG.getNode(X86ISD::FAND, dl, LogicVT, Mag, MagMask);
19215 }
19216
19217 // OR the magnitude value with the sign bit.
19218 SDValue Or = DAG.getNode(X86ISD::FOR, dl, LogicVT, MagBits, SignBit);
19219 return !IsFakeVector ? Or : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Or,
19220 DAG.getIntPtrConstant(0, dl));
19221}
19222
19223static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
19224 SDValue N0 = Op.getOperand(0);
19225 SDLoc dl(Op);
19226 MVT VT = Op.getSimpleValueType();
19227
19228 MVT OpVT = N0.getSimpleValueType();
19229 assert((OpVT == MVT::f32 || OpVT == MVT::f64) &&(((OpVT == MVT::f32 || OpVT == MVT::f64) && "Unexpected type for FGETSIGN"
) ? static_cast<void> (0) : __assert_fail ("(OpVT == MVT::f32 || OpVT == MVT::f64) && \"Unexpected type for FGETSIGN\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 19230, __PRETTY_FUNCTION__))
19230 "Unexpected type for FGETSIGN")(((OpVT == MVT::f32 || OpVT == MVT::f64) && "Unexpected type for FGETSIGN"
) ? static_cast<void> (0) : __assert_fail ("(OpVT == MVT::f32 || OpVT == MVT::f64) && \"Unexpected type for FGETSIGN\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 19230, __PRETTY_FUNCTION__))
;
19231
19232 // Lower ISD::FGETSIGN to (AND (X86ISD::MOVMSK ...) 1).
19233 MVT VecVT = (OpVT == MVT::f32 ? MVT::v4f32 : MVT::v2f64);
19234 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, N0);
19235 Res = DAG.getNode(X86ISD::MOVMSK, dl, MVT::i32, Res);
19236 Res = DAG.getZExtOrTrunc(Res, dl, VT);
19237 Res = DAG.getNode(ISD::AND, dl, VT, Res, DAG.getConstant(1, dl, VT));
19238 return Res;
19239}
19240
19241/// Helper for creating a X86ISD::SETCC node.
19242static SDValue getSETCC(X86::CondCode Cond, SDValue EFLAGS, const SDLoc &dl,
19243 SelectionDAG &DAG) {
19244 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
19245 DAG.getConstant(Cond, dl, MVT::i8), EFLAGS);
19246}
19247
19248/// Helper for matching OR(EXTRACTELT(X,0),OR(EXTRACTELT(X,1),...))
19249/// style scalarized (associative) reduction patterns.
19250static bool matchBitOpReduction(SDValue Op, ISD::NodeType BinOp,
19251 SmallVectorImpl<SDValue> &SrcOps) {
19252 SmallVector<SDValue, 8> Opnds;
19253 DenseMap<SDValue, APInt> SrcOpMap;
19254 EVT VT = MVT::Other;
19255
19256 // Recognize a special case where a vector is casted into wide integer to
19257 // test all 0s.
19258 assert(Op.getOpcode() == unsigned(BinOp) &&((Op.getOpcode() == unsigned(BinOp) && "Unexpected bit reduction opcode"
) ? static_cast<void> (0) : __assert_fail ("Op.getOpcode() == unsigned(BinOp) && \"Unexpected bit reduction opcode\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 19259, __PRETTY_FUNCTION__))
19259 "Unexpected bit reduction opcode")((Op.getOpcode() == unsigned(BinOp) && "Unexpected bit reduction opcode"
) ? static_cast<void> (0) : __assert_fail ("Op.getOpcode() == unsigned(BinOp) && \"Unexpected bit reduction opcode\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 19259, __PRETTY_FUNCTION__))
;
19260 Opnds.push_back(Op.getOperand(0));
19261 Opnds.push_back(Op.getOperand(1));
19262
19263 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
19264 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
19265 // BFS traverse all BinOp operands.
19266 if (I->getOpcode() == unsigned(BinOp)) {
19267 Opnds.push_back(I->getOperand(0));
19268 Opnds.push_back(I->getOperand(1));
19269 // Re-evaluate the number of nodes to be traversed.
19270 e += 2; // 2 more nodes (LHS and RHS) are pushed.
19271 continue;
19272 }
19273
19274 // Quit if a non-EXTRACT_VECTOR_ELT
19275 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
19276 return false;
19277
19278 // Quit if without a constant index.
19279 SDValue Idx = I->getOperand(1);
19280 if (!isa<ConstantSDNode>(Idx))
19281 return false;
19282
19283 SDValue Src = I->getOperand(0);
19284 DenseMap<SDValue, APInt>::iterator M = SrcOpMap.find(Src);
19285 if (M == SrcOpMap.end()) {
19286 VT = Src.getValueType();
19287 // Quit if not the same type.
19288 if (SrcOpMap.begin() != SrcOpMap.end() &&
19289 VT != SrcOpMap.begin()->first.getValueType())
19290 return false;
19291 unsigned NumElts = VT.getVectorNumElements();
19292 APInt EltCount = APInt::getNullValue(NumElts);
19293 M = SrcOpMap.insert(std::make_pair(Src, EltCount)).first;
19294 SrcOps.push_back(Src);
19295 }
19296 // Quit if element already used.
19297 unsigned CIdx = cast<ConstantSDNode>(Idx)->getZExtValue();
19298 if (M->second[CIdx])
19299 return false;
19300 M->second.setBit(CIdx);
19301 }
19302
19303 // Quit if not all elements are used.
19304 for (DenseMap<SDValue, APInt>::const_iterator I = SrcOpMap.begin(),
19305 E = SrcOpMap.end();
19306 I != E; ++I) {
19307 if (!I->second.isAllOnesValue())
19308 return false;
19309 }
19310
19311 return true;
19312}
19313
19314// Check whether an OR'd tree is PTEST-able.
19315static SDValue LowerVectorAllZeroTest(SDValue Op, ISD::CondCode CC,
19316 const X86Subtarget &Subtarget,
19317 SelectionDAG &DAG, SDValue &X86CC) {
19318 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.")((Op.getOpcode() == ISD::OR && "Only check OR'd tree."
) ? static_cast<void> (0) : __assert_fail ("Op.getOpcode() == ISD::OR && \"Only check OR'd tree.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 19318, __PRETTY_FUNCTION__))
;
19319
19320 if (!Subtarget.hasSSE41() || !Op->hasOneUse())
19321 return SDValue();
19322
19323 SmallVector<SDValue, 8> VecIns;
19324 if (!matchBitOpReduction(Op, ISD::OR, VecIns))
19325 return SDValue();
19326
19327 // Quit if not 128/256-bit vector.
19328 EVT VT = VecIns[0].getValueType();
19329 if (!VT.is128BitVector() && !VT.is256BitVector())
19330 return SDValue();
19331
19332 SDLoc DL(Op);
19333 MVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
19334
19335 // Cast all vectors into TestVT for PTEST.
19336 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
19337 VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
19338
19339 // If more than one full vector is evaluated, OR them first before PTEST.
19340 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
19341 // Each iteration will OR 2 nodes and append the result until there is only
19342 // 1 node left, i.e. the final OR'd value of all vectors.
19343 SDValue LHS = VecIns[Slot];
19344 SDValue RHS = VecIns[Slot + 1];
19345 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
19346 }
19347
19348 X86CC = DAG.getConstant(CC == ISD::SETEQ ? X86::COND_E : X86::COND_NE, DL,
19349 MVT::i8);
19350 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32, VecIns.back(), VecIns.back());
19351}
19352
19353/// return true if \c Op has a use that doesn't just read flags.
19354static bool hasNonFlagsUse(SDValue Op) {
19355 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
19356 ++UI) {
19357 SDNode *User = *UI;
19358 unsigned UOpNo = UI.getOperandNo();
19359 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
19360 // Look pass truncate.
19361 UOpNo = User->use_begin().getOperandNo();
19362 User = *User->use_begin();
19363 }
19364
19365 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
19366 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
19367 return true;
19368 }
19369 return false;
19370}
19371
19372/// Emit nodes that will be selected as "test Op0,Op0", or something
19373/// equivalent.
19374static SDValue EmitTest(SDValue Op, unsigned X86CC, const SDLoc &dl,
19375 SelectionDAG &DAG, const X86Subtarget &Subtarget) {
19376 // CF and OF aren't always set the way we want. Determine which
19377 // of these we need.
19378 bool NeedCF = false;
19379 bool NeedOF = false;
19380 switch (X86CC) {
19381 default: break;
19382 case X86::COND_A: case X86::COND_AE:
19383 case X86::COND_B: case X86::COND_BE:
19384 NeedCF = true;
19385 break;
19386 case X86::COND_G: case X86::COND_GE:
19387 case X86::COND_L: case X86::COND_LE:
19388 case X86::COND_O: case X86::COND_NO: {
19389 // Check if we really need to set the
19390 // Overflow flag. If NoSignedWrap is present
19391 // that is not actually needed.
19392 switch (Op->getOpcode()) {
19393 case ISD::ADD:
19394 case ISD::SUB:
19395 case ISD::MUL:
19396 case ISD::SHL:
19397 if (Op.getNode()->getFlags().hasNoSignedWrap())
19398 break;
19399 LLVM_FALLTHROUGH[[clang::fallthrough]];
19400 default:
19401 NeedOF = true;
19402 break;
19403 }
19404 break;
19405 }
19406 }
19407 // See if we can use the EFLAGS value from the operand instead of
19408 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
19409 // we prove that the arithmetic won't overflow, we can't use OF or CF.
19410 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
19411 // Emit a CMP with 0, which is the TEST pattern.
19412 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
19413 DAG.getConstant(0, dl, Op.getValueType()));
19414 }
19415 unsigned Opcode = 0;
19416 unsigned NumOperands = 0;
19417
19418 SDValue ArithOp = Op;
19419
19420 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
19421 // which may be the result of a CAST. We use the variable 'Op', which is the
19422 // non-casted variable when we check for possible users.
19423 switch (ArithOp.getOpcode()) {
19424 case ISD::AND:
19425 // If the primary 'and' result isn't used, don't bother using X86ISD::AND,
19426 // because a TEST instruction will be better.
19427 if (!hasNonFlagsUse(Op))
19428 break;
19429
19430 LLVM_FALLTHROUGH[[clang::fallthrough]];
19431 case ISD::ADD:
19432 case ISD::SUB:
19433 case ISD::OR:
19434 case ISD::XOR:
19435 // Transform to an x86-specific ALU node with flags if there is a chance of
19436 // using an RMW op or only the flags are used. Otherwise, leave
19437 // the node alone and emit a 'test' instruction.
19438 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
19439 UE = Op.getNode()->use_end(); UI != UE; ++UI)
19440 if (UI->getOpcode() != ISD::CopyToReg &&
19441 UI->getOpcode() != ISD::SETCC &&
19442 UI->getOpcode() != ISD::STORE)
19443 goto default_case;
19444
19445 // Otherwise use a regular EFLAGS-setting instruction.
19446 switch (ArithOp.getOpcode()) {
19447 default: llvm_unreachable("unexpected operator!")::llvm::llvm_unreachable_internal("unexpected operator!", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 19447)
;
19448 case ISD::ADD: Opcode = X86ISD::ADD; break;
19449 case ISD::SUB: Opcode = X86ISD::SUB; break;
19450 case ISD::XOR: Opcode = X86ISD::XOR; break;
19451 case ISD::AND: Opcode = X86ISD::AND; break;
19452 case ISD::OR: Opcode = X86ISD::OR; break;
19453 }
19454
19455 NumOperands = 2;
19456 break;
19457 case X86ISD::ADD:
19458 case X86ISD::SUB:
19459 case X86ISD::OR:
19460 case X86ISD::XOR:
19461 case X86ISD::AND:
19462 return SDValue(Op.getNode(), 1);
19463 default:
19464 default_case:
19465 break;
19466 }
19467
19468 if (Opcode == 0) {
19469 // Emit a CMP with 0, which is the TEST pattern.
19470 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
19471 DAG.getConstant(0, dl, Op.getValueType()));
19472 }
19473 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
19474 SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
19475
19476 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
19477 DAG.ReplaceAllUsesOfValueWith(SDValue(Op.getNode(), 0), New);
19478 return SDValue(New.getNode(), 1);
19479}
19480
19481/// Emit nodes that will be selected as "cmp Op0,Op1", or something
19482/// equivalent.
19483SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
19484 const SDLoc &dl, SelectionDAG &DAG) const {
19485 if (isNullConstant(Op1))
19486 return EmitTest(Op0, X86CC, dl, DAG, Subtarget);
19487
19488 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
19489 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
19490 // Only promote the compare up to I32 if it is a 16 bit operation
19491 // with an immediate. 16 bit immediates are to be avoided.
19492 if (Op0.getValueType() == MVT::i16 &&
19493 ((isa<ConstantSDNode>(Op0) &&
19494 !cast<ConstantSDNode>(Op0)->getAPIntValue().isSignedIntN(8)) ||
19495 (isa<ConstantSDNode>(Op1) &&
19496 !cast<ConstantSDNode>(Op1)->getAPIntValue().isSignedIntN(8))) &&
19497 !DAG.getMachineFunction().getFunction().hasMinSize() &&
19498 !Subtarget.isAtom()) {
19499 unsigned ExtendOp =
19500 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
19501 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
19502 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
19503 }
19504 // Use SUB instead of CMP to enable CSE between SUB and CMP.
19505 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
19506 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs, Op0, Op1);
19507 return SDValue(Sub.getNode(), 1);
19508 }
19509 assert(Op0.getValueType().isFloatingPoint() && "Unexpected VT!")((Op0.getValueType().isFloatingPoint() && "Unexpected VT!"
) ? static_cast<void> (0) : __assert_fail ("Op0.getValueType().isFloatingPoint() && \"Unexpected VT!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 19509, __PRETTY_FUNCTION__))
;
19510 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
19511}
19512
19513/// Convert a comparison if required by the subtarget.
19514SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
19515 SelectionDAG &DAG) const {
19516 // If the subtarget does not support the FUCOMI instruction, floating-point
19517 // comparisons have to be converted.
19518 if (Subtarget.hasCMov() ||
19519 Cmp.getOpcode() != X86ISD::CMP ||
19520 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
19521 !Cmp.getOperand(1).getValueType().isFloatingPoint())
19522 return Cmp;
19523
19524 // The instruction selector will select an FUCOM instruction instead of
19525 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
19526 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
19527 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
19528 SDLoc dl(Cmp);
19529 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
19530 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
19531 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
19532 DAG.getConstant(8, dl, MVT::i8));
19533 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
19534
19535 // Some 64-bit targets lack SAHF support, but they do support FCOMI.
19536 assert(Subtarget.hasLAHFSAHF() && "Target doesn't support SAHF or FCOMI?")((Subtarget.hasLAHFSAHF() && "Target doesn't support SAHF or FCOMI?"
) ? static_cast<void> (0) : __assert_fail ("Subtarget.hasLAHFSAHF() && \"Target doesn't support SAHF or FCOMI?\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 19536, __PRETTY_FUNCTION__))
;
19537 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
19538}
19539
19540/// Check if replacement of SQRT with RSQRT should be disabled.
19541bool X86TargetLowering::isFsqrtCheap(SDValue Op, SelectionDAG &DAG) const {
19542 EVT VT = Op.getValueType();
19543
19544 // We never want to use both SQRT and RSQRT instructions for the same input.
19545 if (DAG.getNodeIfExists(X86ISD::FRSQRT, DAG.getVTList(VT), Op))
19546 return false;
19547
19548 if (VT.isVector())
19549 return Subtarget.hasFastVectorFSQRT();
19550 return Subtarget.hasFastScalarFSQRT();
19551}
19552
19553/// The minimum architected relative accuracy is 2^-12. We need one
19554/// Newton-Raphson step to have a good float result (24 bits of precision).
19555SDValue X86TargetLowering::getSqrtEstimate(SDValue Op,
19556 SelectionDAG &DAG, int Enabled,
19557 int &RefinementSteps,
19558 bool &UseOneConstNR,
19559 bool Reciprocal) const {
19560 EVT VT = Op.getValueType();
19561
19562 // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
19563 // It is likely not profitable to do this for f64 because a double-precision
19564 // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
19565 // instructions: convert to single, rsqrtss, convert back to double, refine
19566 // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
19567 // along with FMA, this could be a throughput win.
19568 // TODO: SQRT requires SSE2 to prevent the introduction of an illegal v4i32
19569 // after legalize types.
19570 if ((VT == MVT::f32 && Subtarget.hasSSE1()) ||
19571 (VT == MVT::v4f32 && Subtarget.hasSSE1() && Reciprocal) ||
19572 (VT == MVT::v4f32 && Subtarget.hasSSE2() && !Reciprocal) ||
19573 (VT == MVT::v8f32 && Subtarget.hasAVX()) ||
19574 (VT == MVT::v16f32 && Subtarget.useAVX512Regs())) {
19575 if (RefinementSteps == ReciprocalEstimate::Unspecified)
19576 RefinementSteps = 1;
19577
19578 UseOneConstNR = false;
19579 // There is no FSQRT for 512-bits, but there is RSQRT14.
19580 unsigned Opcode = VT == MVT::v16f32 ? X86ISD::RSQRT14 : X86ISD::FRSQRT;
19581 return DAG.getNode(Opcode, SDLoc(Op), VT, Op);
19582 }
19583 return SDValue();
19584}
19585
19586/// The minimum architected relative accuracy is 2^-12. We need one
19587/// Newton-Raphson step to have a good float result (24 bits of precision).
19588SDValue X86TargetLowering::getRecipEstimate(SDValue Op, SelectionDAG &DAG,
19589 int Enabled,
19590 int &RefinementSteps) const {
19591 EVT VT = Op.getValueType();
19592
19593 // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
19594 // It is likely not profitable to do this for f64 because a double-precision
19595 // reciprocal estimate with refinement on x86 prior to FMA requires
19596 // 15 instructions: convert to single, rcpss, convert back to double, refine
19597 // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
19598 // along with FMA, this could be a throughput win.
19599
19600 if ((VT == MVT::f32 && Subtarget.hasSSE1()) ||
19601 (VT == MVT::v4f32 && Subtarget.hasSSE1()) ||
19602 (VT == MVT::v8f32 && Subtarget.hasAVX()) ||
19603 (VT == MVT::v16f32 && Subtarget.useAVX512Regs())) {
19604 // Enable estimate codegen with 1 refinement step for vector division.
19605 // Scalar division estimates are disabled because they break too much
19606 // real-world code. These defaults are intended to match GCC behavior.
19607 if (VT == MVT::f32 && Enabled == ReciprocalEstimate::Unspecified)
19608 return SDValue();
19609
19610 if (RefinementSteps == ReciprocalEstimate::Unspecified)
19611 RefinementSteps = 1;
19612
19613 // There is no FSQRT for 512-bits, but there is RCP14.
19614 unsigned Opcode = VT == MVT::v16f32 ? X86ISD::RCP14 : X86ISD::FRCP;
19615 return DAG.getNode(Opcode, SDLoc(Op), VT, Op);
19616 }
19617 return SDValue();
19618}
19619
19620/// If we have at least two divisions that use the same divisor, convert to
19621/// multiplication by a reciprocal. This may need to be adjusted for a given
19622/// CPU if a division's cost is not at least twice the cost of a multiplication.
19623/// This is because we still need one division to calculate the reciprocal and
19624/// then we need two multiplies by that reciprocal as replacements for the
19625/// original divisions.
19626unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
19627 return 2;
19628}
19629
19630/// Result of 'and' is compared against zero. Change to a BT node if possible.
19631/// Returns the BT node and the condition code needed to use it.
19632static SDValue LowerAndToBT(SDValue And, ISD::CondCode CC,
19633 const SDLoc &dl, SelectionDAG &DAG,
19634 SDValue &X86CC) {
19635 assert(And.getOpcode() == ISD::AND && "Expected AND node!")((And.getOpcode() == ISD::AND && "Expected AND node!"
) ? static_cast<void> (0) : __assert_fail ("And.getOpcode() == ISD::AND && \"Expected AND node!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 19635, __PRETTY_FUNCTION__))
;
19636 SDValue Op0 = And.getOperand(0);
19637 SDValue Op1 = And.getOperand(1);
19638 if (Op0.getOpcode() == ISD::TRUNCATE)
19639 Op0 = Op0.getOperand(0);
19640 if (Op1.getOpcode() == ISD::TRUNCATE)
19641 Op1 = Op1.getOperand(0);
19642
19643 SDValue Src, BitNo;
19644 if (Op1.getOpcode() == ISD::SHL)
19645 std::swap(Op0, Op1);
19646 if (Op0.getOpcode() == ISD::SHL) {
19647 if (isOneConstant(Op0.getOperand(0))) {
19648 // If we looked past a truncate, check that it's only truncating away
19649 // known zeros.
19650 unsigned BitWidth = Op0.getValueSizeInBits();
19651 unsigned AndBitWidth = And.getValueSizeInBits();
19652 if (BitWidth > AndBitWidth) {
19653 KnownBits Known = DAG.computeKnownBits(Op0);
19654 if (Known.countMinLeadingZeros() < BitWidth - AndBitWidth)
19655 return SDValue();
19656 }
19657 Src = Op1;
19658 BitNo = Op0.getOperand(1);
19659 }
19660 } else if (Op1.getOpcode() == ISD::Constant) {
19661 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
19662 uint64_t AndRHSVal = AndRHS->getZExtValue();
19663 SDValue AndLHS = Op0;
19664
19665 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
19666 Src = AndLHS.getOperand(0);
19667 BitNo = AndLHS.getOperand(1);
19668 } else {
19669 // Use BT if the immediate can't be encoded in a TEST instruction or we
19670 // are optimizing for size and the immedaite won't fit in a byte.
19671 bool OptForSize = DAG.getMachineFunction().getFunction().hasOptSize();
19672 if ((!isUInt<32>(AndRHSVal) || (OptForSize && !isUInt<8>(AndRHSVal))) &&
19673 isPowerOf2_64(AndRHSVal)) {
19674 Src = AndLHS;
19675 BitNo = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl,
19676 Src.getValueType());
19677 }
19678 }
19679 }
19680
19681 // No patterns found, give up.
19682 if (!Src.getNode())
19683 return SDValue();
19684
19685 // If Src is i8, promote it to i32 with any_extend. There is no i8 BT
19686 // instruction. Since the shift amount is in-range-or-undefined, we know
19687 // that doing a bittest on the i32 value is ok. We extend to i32 because
19688 // the encoding for the i16 version is larger than the i32 version.
19689 // Also promote i16 to i32 for performance / code size reason.
19690 if (Src.getValueType() == MVT::i8 || Src.getValueType() == MVT::i16)
19691 Src = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Src);
19692
19693 // See if we can use the 32-bit instruction instead of the 64-bit one for a
19694 // shorter encoding. Since the former takes the modulo 32 of BitNo and the
19695 // latter takes the modulo 64, this is only valid if the 5th bit of BitNo is
19696 // known to be zero.
19697 if (Src.getValueType() == MVT::i64 &&
19698 DAG.MaskedValueIsZero(BitNo, APInt(BitNo.getValueSizeInBits(), 32)))
19699 Src = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Src);
19700
19701 // If the operand types disagree, extend the shift amount to match. Since
19702 // BT ignores high bits (like shifts) we can use anyextend.
19703 if (Src.getValueType() != BitNo.getValueType())
19704 BitNo = DAG.getNode(ISD::ANY_EXTEND, dl, Src.getValueType(), BitNo);
19705
19706 X86CC = DAG.getConstant(CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B,
19707 dl, MVT::i8);
19708 return DAG.getNode(X86ISD::BT, dl, MVT::i32, Src, BitNo);
19709}
19710
19711/// Turns an ISD::CondCode into a value suitable for SSE floating-point mask
19712/// CMPs.
19713static unsigned translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
19714 SDValue &Op1) {
19715 unsigned SSECC;
19716 bool Swap = false;
19717
19718 // SSE Condition code mapping:
19719 // 0 - EQ
19720 // 1 - LT
19721 // 2 - LE
19722 // 3 - UNORD
19723 // 4 - NEQ
19724 // 5 - NLT
19725 // 6 - NLE
19726 // 7 - ORD
19727 switch (SetCCOpcode) {
19728 default: llvm_unreachable("Unexpected SETCC condition")::llvm::llvm_unreachable_internal("Unexpected SETCC condition"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 19728)
;
19729 case ISD::SETOEQ:
19730 case ISD::SETEQ: SSECC = 0; break;
19731 case ISD::SETOGT:
19732 case ISD::SETGT: Swap = true; LLVM_FALLTHROUGH[[clang::fallthrough]];
19733 case ISD::SETLT:
19734 case ISD::SETOLT: SSECC = 1; break;
19735 case ISD::SETOGE:
19736 case ISD::SETGE: Swap = true; LLVM_FALLTHROUGH[[clang::fallthrough]];
19737 case ISD::SETLE:
19738 case ISD::SETOLE: SSECC = 2; break;
19739 case ISD::SETUO: SSECC = 3; break;
19740 case ISD::SETUNE:
19741 case ISD::SETNE: SSECC = 4; break;
19742 case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH[[clang::fallthrough]];
19743 case ISD::SETUGE: SSECC = 5; break;
19744 case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH[[clang::fallthrough]];
19745 case ISD::SETUGT: SSECC = 6; break;
19746 case ISD::SETO: SSECC = 7; break;
19747 case ISD::SETUEQ: SSECC = 8; break;
19748 case ISD::SETONE: SSECC = 12; break;
19749 }
19750 if (Swap)
19751 std::swap(Op0, Op1);
19752
19753 return SSECC;
19754}
19755
19756/// Break a VSETCC 256-bit integer VSETCC into two new 128 ones and then
19757/// concatenate the result back.
19758static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
19759 MVT VT = Op.getSimpleValueType();
19760
19761 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&((VT.is256BitVector() && Op.getOpcode() == ISD::SETCC
&& "Unsupported value type for operation") ? static_cast
<void> (0) : __assert_fail ("VT.is256BitVector() && Op.getOpcode() == ISD::SETCC && \"Unsupported value type for operation\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 19762, __PRETTY_FUNCTION__))
19762 "Unsupported value type for operation")((VT.is256BitVector() && Op.getOpcode() == ISD::SETCC
&& "Unsupported value type for operation") ? static_cast
<void> (0) : __assert_fail ("VT.is256BitVector() && Op.getOpcode() == ISD::SETCC && \"Unsupported value type for operation\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 19762, __PRETTY_FUNCTION__))
;
19763
19764 unsigned NumElems = VT.getVectorNumElements();
19765 SDLoc dl(Op);
19766 SDValue CC = Op.getOperand(2);
19767
19768 // Extract the LHS vectors
19769 SDValue LHS = Op.getOperand(0);
19770 SDValue LHS1 = extract128BitVector(LHS, 0, DAG, dl);
19771 SDValue LHS2 = extract128BitVector(LHS, NumElems / 2, DAG, dl);
19772
19773 // Extract the RHS vectors
19774 SDValue RHS = Op.getOperand(1);
19775 SDValue RHS1 = extract128BitVector(RHS, 0, DAG, dl);
19776 SDValue RHS2 = extract128BitVector(RHS, NumElems / 2, DAG, dl);
19777
19778 // Issue the operation on the smaller types and concatenate the result back
19779 MVT EltVT = VT.getVectorElementType();
19780 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
19781 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
19782 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
19783 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
19784}
19785
19786static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
19787
19788 SDValue Op0 = Op.getOperand(0);
19789 SDValue Op1 = Op.getOperand(1);
19790 SDValue CC = Op.getOperand(2);
19791 MVT VT = Op.getSimpleValueType();
19792 SDLoc dl(Op);
19793
19794 assert(VT.getVectorElementType() == MVT::i1 &&((VT.getVectorElementType() == MVT::i1 && "Cannot set masked compare for this operation"
) ? static_cast<void> (0) : __assert_fail ("VT.getVectorElementType() == MVT::i1 && \"Cannot set masked compare for this operation\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 19795, __PRETTY_FUNCTION__))
19795 "Cannot set masked compare for this operation")((VT.getVectorElementType() == MVT::i1 && "Cannot set masked compare for this operation"
) ? static_cast<void> (0) : __assert_fail ("VT.getVectorElementType() == MVT::i1 && \"Cannot set masked compare for this operation\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 19795, __PRETTY_FUNCTION__))
;
19796
19797 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
19798
19799 // If this is a seteq make sure any build vectors of all zeros are on the RHS.
19800 // This helps with vptestm matching.
19801 // TODO: Should we just canonicalize the setcc during DAG combine?
19802 if ((SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE) &&
19803 ISD::isBuildVectorAllZeros(Op0.getNode()))
19804 std::swap(Op0, Op1);
19805
19806 // Prefer SETGT over SETLT.
19807 if (SetCCOpcode == ISD::SETLT) {
19808 SetCCOpcode = ISD::getSetCCSwappedOperands(SetCCOpcode);
19809 std::swap(Op0, Op1);
19810 }
19811
19812 return DAG.getSetCC(dl, VT, Op0, Op1, SetCCOpcode);
19813}
19814
19815/// Given a buildvector constant, return a new vector constant with each element
19816/// incremented or decremented. If incrementing or decrementing would result in
19817/// unsigned overflow or underflow or this is not a simple vector constant,
19818/// return an empty value.
19819static SDValue incDecVectorConstant(SDValue V, SelectionDAG &DAG, bool IsInc) {
19820 auto *BV = dyn_cast<BuildVectorSDNode>(V.getNode());
19821 if (!BV)
19822 return SDValue();
19823
19824 MVT VT = V.getSimpleValueType();
19825 MVT EltVT = VT.getVectorElementType();
19826 unsigned NumElts = VT.getVectorNumElements();
19827 SmallVector<SDValue, 8> NewVecC;
19828 SDLoc DL(V);
19829 for (unsigned i = 0; i < NumElts; ++i) {
19830 auto *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
19831 if (!Elt || Elt->isOpaque() || Elt->getSimpleValueType(0) != EltVT)
19832 return SDValue();
19833
19834 // Avoid overflow/underflow.
19835 const APInt &EltC = Elt->getAPIntValue();
19836 if ((IsInc && EltC.isMaxValue()) || (!IsInc && EltC.isNullValue()))
19837 return SDValue();
19838
19839 NewVecC.push_back(DAG.getConstant(EltC + (IsInc ? 1 : -1), DL, EltVT));
19840 }
19841
19842 return DAG.getBuildVector(VT, DL, NewVecC);
19843}
19844
19845/// As another special case, use PSUBUS[BW] when it's profitable. E.g. for
19846/// Op0 u<= Op1:
19847/// t = psubus Op0, Op1
19848/// pcmpeq t, <0..0>
19849static SDValue LowerVSETCCWithSUBUS(SDValue Op0, SDValue Op1, MVT VT,
19850 ISD::CondCode Cond, const SDLoc &dl,
19851 const X86Subtarget &Subtarget,
19852 SelectionDAG &DAG) {
19853 if (!Subtarget.hasSSE2())
19854 return SDValue();
19855
19856 MVT VET = VT.getVectorElementType();
19857 if (VET != MVT::i8 && VET != MVT::i16)
19858 return SDValue();
19859
19860 switch (Cond) {
19861 default:
19862 return SDValue();
19863 case ISD::SETULT: {
19864 // If the comparison is against a constant we can turn this into a
19865 // setule. With psubus, setule does not require a swap. This is
19866 // beneficial because the constant in the register is no longer
19867 // destructed as the destination so it can be hoisted out of a loop.
19868 // Only do this pre-AVX since vpcmp* is no longer destructive.
19869 if (Subtarget.hasAVX())
19870 return SDValue();
19871 SDValue ULEOp1 = incDecVectorConstant(Op1, DAG, false);
19872 if (!ULEOp1)
19873 return SDValue();
19874 Op1 = ULEOp1;
19875 break;
19876 }
19877 case ISD::SETUGT: {
19878 // If the comparison is against a constant, we can turn this into a setuge.
19879 // This is beneficial because materializing a constant 0 for the PCMPEQ is
19880 // probably cheaper than XOR+PCMPGT using 2 different vector constants:
19881 // cmpgt (xor X, SignMaskC) CmpC --> cmpeq (usubsat (CmpC+1), X), 0
19882 SDValue UGEOp1 = incDecVectorConstant(Op1, DAG, true);
19883 if (!UGEOp1)
19884 return SDValue();
19885 Op1 = Op0;
19886 Op0 = UGEOp1;
19887 break;
19888 }
19889 // Psubus is better than flip-sign because it requires no inversion.
19890 case ISD::SETUGE:
19891 std::swap(Op0, Op1);
19892 break;
19893 case ISD::SETULE:
19894 break;
19895 }
19896
19897 SDValue Result = DAG.getNode(ISD::USUBSAT, dl, VT, Op0, Op1);
19898 return DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
19899 DAG.getConstant(0, dl, VT));
19900}
19901
19902static SDValue LowerVSETCC(SDValue Op, const X86Subtarget &Subtarget,
19903 SelectionDAG &DAG) {
19904 SDValue Op0 = Op.getOperand(0);
19905 SDValue Op1 = Op.getOperand(1);
19906 SDValue CC = Op.getOperand(2);
19907 MVT VT = Op.getSimpleValueType();
19908 ISD::CondCode Cond = cast<CondCodeSDNode>(CC)->get();
19909 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
19910 SDLoc dl(Op);
19911
19912 if (isFP) {
19913#ifndef NDEBUG
19914 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
19915 assert(EltVT == MVT::f32 || EltVT == MVT::f64)((EltVT == MVT::f32 || EltVT == MVT::f64) ? static_cast<void
> (0) : __assert_fail ("EltVT == MVT::f32 || EltVT == MVT::f64"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 19915, __PRETTY_FUNCTION__))
;
19916#endif
19917
19918 unsigned Opc;
19919 if (Subtarget.hasAVX512() && VT.getVectorElementType() == MVT::i1) {
19920 assert(VT.getVectorNumElements() <= 16)((VT.getVectorNumElements() <= 16) ? static_cast<void>
(0) : __assert_fail ("VT.getVectorNumElements() <= 16", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 19920, __PRETTY_FUNCTION__))
;
19921 Opc = X86ISD::CMPM;
19922 } else {
19923 Opc = X86ISD::CMPP;
19924 // The SSE/AVX packed FP comparison nodes are defined with a
19925 // floating-point vector result that matches the operand type. This allows
19926 // them to work with an SSE1 target (integer vector types are not legal).
19927 VT = Op0.getSimpleValueType();
19928 }
19929
19930 // In the two cases not handled by SSE compare predicates (SETUEQ/SETONE),
19931 // emit two comparisons and a logic op to tie them together.
19932 SDValue Cmp;
19933 unsigned SSECC = translateX86FSETCC(Cond, Op0, Op1);
19934 if (SSECC >= 8 && !Subtarget.hasAVX()) {
19935 // LLVM predicate is SETUEQ or SETONE.
19936 unsigned CC0, CC1;
19937 unsigned CombineOpc;
19938 if (Cond == ISD::SETUEQ) {
19939 CC0 = 3; // UNORD
19940 CC1 = 0; // EQ
19941 CombineOpc = X86ISD::FOR;
19942 } else {
19943 assert(Cond == ISD::SETONE)((Cond == ISD::SETONE) ? static_cast<void> (0) : __assert_fail
("Cond == ISD::SETONE", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 19943, __PRETTY_FUNCTION__))
;
19944 CC0 = 7; // ORD
19945 CC1 = 4; // NEQ
19946 CombineOpc = X86ISD::FAND;
19947 }
19948
19949 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
19950 DAG.getConstant(CC0, dl, MVT::i8));
19951 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
19952 DAG.getConstant(CC1, dl, MVT::i8));
19953 Cmp = DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
19954 } else {
19955 // Handle all other FP comparisons here.
19956 Cmp = DAG.getNode(Opc, dl, VT, Op0, Op1,
19957 DAG.getConstant(SSECC, dl, MVT::i8));
19958 }
19959
19960 // If this is SSE/AVX CMPP, bitcast the result back to integer to match the
19961 // result type of SETCC. The bitcast is expected to be optimized away
19962 // during combining/isel.
19963 if (Opc == X86ISD::CMPP)
19964 Cmp = DAG.getBitcast(Op.getSimpleValueType(), Cmp);
19965
19966 return Cmp;
19967 }
19968
19969 MVT VTOp0 = Op0.getSimpleValueType();
19970 assert(VTOp0 == Op1.getSimpleValueType() &&((VTOp0 == Op1.getSimpleValueType() && "Expected operands with same type!"
) ? static_cast<void> (0) : __assert_fail ("VTOp0 == Op1.getSimpleValueType() && \"Expected operands with same type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 19971, __PRETTY_FUNCTION__))
19971 "Expected operands with same type!")((VTOp0 == Op1.getSimpleValueType() && "Expected operands with same type!"
) ? static_cast<void> (0) : __assert_fail ("VTOp0 == Op1.getSimpleValueType() && \"Expected operands with same type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 19971, __PRETTY_FUNCTION__))
;
19972 assert(VT.getVectorNumElements() == VTOp0.getVectorNumElements() &&((VT.getVectorNumElements() == VTOp0.getVectorNumElements() &&
"Invalid number of packed elements for source and destination!"
) ? static_cast<void> (0) : __assert_fail ("VT.getVectorNumElements() == VTOp0.getVectorNumElements() && \"Invalid number of packed elements for source and destination!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 19973, __PRETTY_FUNCTION__))
19973 "Invalid number of packed elements for source and destination!")((VT.getVectorNumElements() == VTOp0.getVectorNumElements() &&
"Invalid number of packed elements for source and destination!"
) ? static_cast<void> (0) : __assert_fail ("VT.getVectorNumElements() == VTOp0.getVectorNumElements() && \"Invalid number of packed elements for source and destination!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 19973, __PRETTY_FUNCTION__))
;
19974
19975 // This is being called by type legalization because v2i32 is marked custom
19976 // for result type legalization for v2f32.
19977 if (VTOp0 == MVT::v2i32)
19978 return SDValue();
19979
19980 // The non-AVX512 code below works under the assumption that source and
19981 // destination types are the same.
19982 assert((Subtarget.hasAVX512() || (VT == VTOp0)) &&(((Subtarget.hasAVX512() || (VT == VTOp0)) && "Value types for source and destination must be the same!"
) ? static_cast<void> (0) : __assert_fail ("(Subtarget.hasAVX512() || (VT == VTOp0)) && \"Value types for source and destination must be the same!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 19983, __PRETTY_FUNCTION__))
19983 "Value types for source and destination must be the same!")(((Subtarget.hasAVX512() || (VT == VTOp0)) && "Value types for source and destination must be the same!"
) ? static_cast<void> (0) : __assert_fail ("(Subtarget.hasAVX512() || (VT == VTOp0)) && \"Value types for source and destination must be the same!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 19983, __PRETTY_FUNCTION__))
;
19984
19985 // The result is boolean, but operands are int/float
19986 if (VT.getVectorElementType() == MVT::i1) {
19987 // In AVX-512 architecture setcc returns mask with i1 elements,
19988 // But there is no compare instruction for i8 and i16 elements in KNL.
19989 assert((VTOp0.getScalarSizeInBits() >= 32 || Subtarget.hasBWI()) &&(((VTOp0.getScalarSizeInBits() >= 32 || Subtarget.hasBWI()
) && "Unexpected operand type") ? static_cast<void
> (0) : __assert_fail ("(VTOp0.getScalarSizeInBits() >= 32 || Subtarget.hasBWI()) && \"Unexpected operand type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 19990, __PRETTY_FUNCTION__))
19990 "Unexpected operand type")(((VTOp0.getScalarSizeInBits() >= 32 || Subtarget.hasBWI()
) && "Unexpected operand type") ? static_cast<void
> (0) : __assert_fail ("(VTOp0.getScalarSizeInBits() >= 32 || Subtarget.hasBWI()) && \"Unexpected operand type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 19990, __PRETTY_FUNCTION__))
;
19991 return LowerIntVSETCC_AVX512(Op, DAG);
19992 }
19993
19994 // Lower using XOP integer comparisons.
19995 if (VT.is128BitVector() && Subtarget.hasXOP()) {
19996 // Translate compare code to XOP PCOM compare mode.
19997 unsigned CmpMode = 0;
19998 switch (Cond) {
19999 default: llvm_unreachable("Unexpected SETCC condition")::llvm::llvm_unreachable_internal("Unexpected SETCC condition"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 19999)
;
20000 case ISD::SETULT:
20001 case ISD::SETLT: CmpMode = 0x00; break;
20002 case ISD::SETULE:
20003 case ISD::SETLE: CmpMode = 0x01; break;
20004 case ISD::SETUGT:
20005 case ISD::SETGT: CmpMode = 0x02; break;
20006 case ISD::SETUGE:
20007 case ISD::SETGE: CmpMode = 0x03; break;
20008 case ISD::SETEQ: CmpMode = 0x04; break;
20009 case ISD::SETNE: CmpMode = 0x05; break;
20010 }
20011
20012 // Are we comparing unsigned or signed integers?
20013 unsigned Opc =
20014 ISD::isUnsignedIntSetCC(Cond) ? X86ISD::VPCOMU : X86ISD::VPCOM;
20015
20016 return DAG.getNode(Opc, dl, VT, Op0, Op1,
20017 DAG.getConstant(CmpMode, dl, MVT::i8));
20018 }
20019
20020 // (X & Y) != 0 --> (X & Y) == Y iff Y is power-of-2.
20021 // Revert part of the simplifySetCCWithAnd combine, to avoid an invert.
20022 if (Cond == ISD::SETNE && ISD::isBuildVectorAllZeros(Op1.getNode())) {
20023 SDValue BC0 = peekThroughBitcasts(Op0);
20024 if (BC0.getOpcode() == ISD::AND) {
20025 APInt UndefElts;
20026 SmallVector<APInt, 64> EltBits;
20027 if (getTargetConstantBitsFromNode(BC0.getOperand(1),
20028 VT.getScalarSizeInBits(), UndefElts,
20029 EltBits, false, false)) {
20030 if (llvm::all_of(EltBits, [](APInt &V) { return V.isPowerOf2(); })) {
20031 Cond = ISD::SETEQ;
20032 Op1 = DAG.getBitcast(VT, BC0.getOperand(1));
20033 }
20034 }
20035 }
20036 }
20037
20038 // ICMP_EQ(AND(X,C),C) -> SRA(SHL(X,LOG2(C)),BW-1) iff C is power-of-2.
20039 if (Cond == ISD::SETEQ && Op0.getOpcode() == ISD::AND &&
20040 Op0.getOperand(1) == Op1 && Op0.hasOneUse()) {
20041 ConstantSDNode *C1 = isConstOrConstSplat(Op1);
20042 if (C1 && C1->getAPIntValue().isPowerOf2()) {
20043 unsigned BitWidth = VT.getScalarSizeInBits();
20044 unsigned ShiftAmt = BitWidth - C1->getAPIntValue().logBase2() - 1;
20045
20046 SDValue Result = Op0.getOperand(0);
20047 Result = DAG.getNode(ISD::SHL, dl, VT, Result,
20048 DAG.getConstant(ShiftAmt, dl, VT));
20049 Result = DAG.getNode(ISD::SRA, dl, VT, Result,
20050 DAG.getConstant(BitWidth - 1, dl, VT));
20051 return Result;
20052 }
20053 }
20054
20055 // Break 256-bit integer vector compare into smaller ones.
20056 if (VT.is256BitVector() && !Subtarget.hasInt256())
20057 return Lower256IntVSETCC(Op, DAG);
20058
20059 // If this is a SETNE against the signed minimum value, change it to SETGT.
20060 // If this is a SETNE against the signed maximum value, change it to SETLT.
20061 // which will be swapped to SETGT.
20062 // Otherwise we use PCMPEQ+invert.
20063 APInt ConstValue;
20064 if (Cond == ISD::SETNE &&
20065 ISD::isConstantSplatVector(Op1.getNode(), ConstValue)) {
20066 if (ConstValue.isMinSignedValue())
20067 Cond = ISD::SETGT;
20068 else if (ConstValue.isMaxSignedValue())
20069 Cond = ISD::SETLT;
20070 }
20071
20072 // If both operands are known non-negative, then an unsigned compare is the
20073 // same as a signed compare and there's no need to flip signbits.
20074 // TODO: We could check for more general simplifications here since we're
20075 // computing known bits.
20076 bool FlipSigns = ISD::isUnsignedIntSetCC(Cond) &&
20077 !(DAG.SignBitIsZero(Op0) && DAG.SignBitIsZero(Op1));
20078
20079 // Special case: Use min/max operations for unsigned compares.
20080 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20081 if (ISD::isUnsignedIntSetCC(Cond) &&
20082 (FlipSigns || ISD::isTrueWhenEqual(Cond)) &&
20083 TLI.isOperationLegal(ISD::UMIN, VT)) {
20084 // If we have a constant operand, increment/decrement it and change the
20085 // condition to avoid an invert.
20086 if (Cond == ISD::SETUGT &&
20087 ISD::matchUnaryPredicate(Op1, [](ConstantSDNode *C) {
20088 return !C->getAPIntValue().isMaxValue();
20089 })) {
20090 // X > C --> X >= (C+1) --> X == umax(X, C+1)
20091 Op1 = DAG.getNode(ISD::ADD, dl, VT, Op1, DAG.getConstant(1, dl, VT));
20092 Cond = ISD::SETUGE;
20093 }
20094 if (Cond == ISD::SETULT &&
20095 ISD::matchUnaryPredicate(Op1, [](ConstantSDNode *C) {
20096 return !C->getAPIntValue().isNullValue();
20097 })) {
20098 // X < C --> X <= (C-1) --> X == umin(X, C-1)
20099 Op1 = DAG.getNode(ISD::SUB, dl, VT, Op1, DAG.getConstant(1, dl, VT));
20100 Cond = ISD::SETULE;
20101 }
20102 bool Invert = false;
20103 unsigned Opc;
20104 switch (Cond) {
20105 default: llvm_unreachable("Unexpected condition code")::llvm::llvm_unreachable_internal("Unexpected condition code"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 20105)
;
20106 case ISD::SETUGT: Invert = true; LLVM_FALLTHROUGH[[clang::fallthrough]];
20107 case ISD::SETULE: Opc = ISD::UMIN; break;
20108 case ISD::SETULT: Invert = true; LLVM_FALLTHROUGH[[clang::fallthrough]];
20109 case ISD::SETUGE: Opc = ISD::UMAX; break;
20110 }
20111
20112 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
20113 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
20114
20115 // If the logical-not of the result is required, perform that now.
20116 if (Invert)
20117 Result = DAG.getNOT(dl, Result, VT);
20118
20119 return Result;
20120 }
20121
20122 // Try to use SUBUS and PCMPEQ.
20123 if (SDValue V = LowerVSETCCWithSUBUS(Op0, Op1, VT, Cond, dl, Subtarget, DAG))
20124 return V;
20125
20126 // We are handling one of the integer comparisons here. Since SSE only has
20127 // GT and EQ comparisons for integer, swapping operands and multiple
20128 // operations may be required for some comparisons.
20129 unsigned Opc = (Cond == ISD::SETEQ || Cond == ISD::SETNE) ? X86ISD::PCMPEQ
20130 : X86ISD::PCMPGT;
20131 bool Swap = Cond == ISD::SETLT || Cond == ISD::SETULT ||
20132 Cond == ISD::SETGE || Cond == ISD::SETUGE;
20133 bool Invert = Cond == ISD::SETNE ||
20134 (Cond != ISD::SETEQ && ISD::isTrueWhenEqual(Cond));
20135
20136 if (Swap)
20137 std::swap(Op0, Op1);
20138
20139 // Check that the operation in question is available (most are plain SSE2,
20140 // but PCMPGTQ and PCMPEQQ have different requirements).
20141 if (VT == MVT::v2i64) {
20142 if (Opc == X86ISD::PCMPGT && !Subtarget.hasSSE42()) {
20143 assert(Subtarget.hasSSE2() && "Don't know how to lower!")((Subtarget.hasSSE2() && "Don't know how to lower!") ?
static_cast<void> (0) : __assert_fail ("Subtarget.hasSSE2() && \"Don't know how to lower!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 20143, __PRETTY_FUNCTION__))
;
20144
20145 // Since SSE has no unsigned integer comparisons, we need to flip the sign
20146 // bits of the inputs before performing those operations. The lower
20147 // compare is always unsigned.
20148 SDValue SB;
20149 if (FlipSigns) {
20150 SB = DAG.getConstant(0x8000000080000000ULL, dl, MVT::v2i64);
20151 } else {
20152 SB = DAG.getConstant(0x0000000080000000ULL, dl, MVT::v2i64);
20153 }
20154 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v2i64, Op0, SB);
20155 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v2i64, Op1, SB);
20156
20157 // Cast everything to the right type.
20158 Op0 = DAG.getBitcast(MVT::v4i32, Op0);
20159 Op1 = DAG.getBitcast(MVT::v4i32, Op1);
20160
20161 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
20162 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
20163 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
20164
20165 // Create masks for only the low parts/high parts of the 64 bit integers.
20166 static const int MaskHi[] = { 1, 1, 3, 3 };
20167 static const int MaskLo[] = { 0, 0, 2, 2 };
20168 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
20169 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
20170 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
20171
20172 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
20173 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
20174
20175 if (Invert)
20176 Result = DAG.getNOT(dl, Result, MVT::v4i32);
20177
20178 return DAG.getBitcast(VT, Result);
20179 }
20180
20181 if (Opc == X86ISD::PCMPEQ && !Subtarget.hasSSE41()) {
20182 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
20183 // pcmpeqd + pshufd + pand.
20184 assert(Subtarget.hasSSE2() && !FlipSigns && "Don't know how to lower!")((Subtarget.hasSSE2() && !FlipSigns && "Don't know how to lower!"
) ? static_cast<void> (0) : __assert_fail ("Subtarget.hasSSE2() && !FlipSigns && \"Don't know how to lower!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 20184, __PRETTY_FUNCTION__))
;
20185
20186 // First cast everything to the right type.
20187 Op0 = DAG.getBitcast(MVT::v4i32, Op0);
20188 Op1 = DAG.getBitcast(MVT::v4i32, Op1);
20189
20190 // Do the compare.
20191 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
20192
20193 // Make sure the lower and upper halves are both all-ones.
20194 static const int Mask[] = { 1, 0, 3, 2 };
20195 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
20196 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
20197
20198 if (Invert)
20199 Result = DAG.getNOT(dl, Result, MVT::v4i32);
20200
20201 return DAG.getBitcast(VT, Result);
20202 }
20203 }
20204
20205 // Since SSE has no unsigned integer comparisons, we need to flip the sign
20206 // bits of the inputs before performing those operations.
20207 if (FlipSigns) {
20208 MVT EltVT = VT.getVectorElementType();
20209 SDValue SM = DAG.getConstant(APInt::getSignMask(EltVT.getSizeInBits()), dl,
20210 VT);
20211 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SM);
20212 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SM);
20213 }
20214
20215 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
20216
20217 // If the logical-not of the result is required, perform that now.
20218 if (Invert)
20219 Result = DAG.getNOT(dl, Result, VT);
20220
20221 return Result;
20222}
20223
20224// Try to select this as a KORTEST+SETCC if possible.
20225static SDValue EmitKORTEST(SDValue Op0, SDValue Op1, ISD::CondCode CC,
20226 const SDLoc &dl, SelectionDAG &DAG,
20227 const X86Subtarget &Subtarget,
20228 SDValue &X86CC) {
20229 // Only support equality comparisons.
20230 if (CC != ISD::SETEQ && CC != ISD::SETNE)
20231 return SDValue();
20232
20233 // Must be a bitcast from vXi1.
20234 if (Op0.getOpcode() != ISD::BITCAST)
20235 return SDValue();
20236
20237 Op0 = Op0.getOperand(0);
20238 MVT VT = Op0.getSimpleValueType();
20239 if (!(Subtarget.hasAVX512() && VT == MVT::v16i1) &&
20240 !(Subtarget.hasDQI() && VT == MVT::v8i1) &&
20241 !(Subtarget.hasBWI() && (VT == MVT::v32i1 || VT == MVT::v64i1)))
20242 return SDValue();
20243
20244 X86::CondCode X86Cond;
20245 if (isNullConstant(Op1)) {
20246 X86Cond = CC == ISD::SETEQ ? X86::COND_E : X86::COND_NE;
20247 } else if (isAllOnesConstant(Op1)) {
20248 // C flag is set for all ones.
20249 X86Cond = CC == ISD::SETEQ ? X86::COND_B : X86::COND_AE;
20250 } else
20251 return SDValue();
20252
20253 // If the input is an OR, we can combine it's operands into the KORTEST.
20254 SDValue LHS = Op0;
20255 SDValue RHS = Op0;
20256 if (Op0.getOpcode() == ISD::OR && Op0.hasOneUse()) {
20257 LHS = Op0.getOperand(0);
20258 RHS = Op0.getOperand(1);
20259 }
20260
20261 X86CC = DAG.getConstant(X86Cond, dl, MVT::i8);
20262 return DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
20263}
20264
20265/// Emit flags for the given setcc condition and operands. Also returns the
20266/// corresponding X86 condition code constant in X86CC.
20267SDValue X86TargetLowering::emitFlagsForSetcc(SDValue Op0, SDValue Op1,
20268 ISD::CondCode CC, const SDLoc &dl,
20269 SelectionDAG &DAG,
20270 SDValue &X86CC) const {
20271 // Optimize to BT if possible.
20272 // Lower (X & (1 << N)) == 0 to BT(X, N).
20273 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
20274 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
20275 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() && isNullConstant(Op1) &&
20276 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
20277 if (SDValue BT = LowerAndToBT(Op0, CC, dl, DAG, X86CC))
20278 return BT;
20279 }
20280
20281 // Try to use PTEST for a tree ORs equality compared with 0.
20282 // TODO: We could do AND tree with all 1s as well by using the C flag.
20283 if (Op0.getOpcode() == ISD::OR && isNullConstant(Op1) &&
20284 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
20285 if (SDValue PTEST = LowerVectorAllZeroTest(Op0, CC, Subtarget, DAG, X86CC))
20286 return PTEST;
20287 }
20288
20289 // Try to lower using KORTEST.
20290 if (SDValue KORTEST = EmitKORTEST(Op0, Op1, CC, dl, DAG, Subtarget, X86CC))
20291 return KORTEST;
20292
20293 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
20294 // these.
20295 if ((isOneConstant(Op1) || isNullConstant(Op1)) &&
20296 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
20297 // If the input is a setcc, then reuse the input setcc or use a new one with
20298 // the inverted condition.
20299 if (Op0.getOpcode() == X86ISD::SETCC) {
20300 bool Invert = (CC == ISD::SETNE) ^ isNullConstant(Op1);
20301
20302 X86CC = Op0.getOperand(0);
20303 if (Invert) {
20304 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
20305 CCode = X86::GetOppositeBranchCondition(CCode);
20306 X86CC = DAG.getConstant(CCode, dl, MVT::i8);
20307 }
20308
20309 return Op0.getOperand(1);
20310 }
20311 }
20312
20313 bool IsFP = Op1.getSimpleValueType().isFloatingPoint();
20314 X86::CondCode CondCode = TranslateX86CC(CC, dl, IsFP, Op0, Op1, DAG);
20315 if (CondCode == X86::COND_INVALID)
20316 return SDValue();
20317
20318 SDValue EFLAGS = EmitCmp(Op0, Op1, CondCode, dl, DAG);
20319 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
20320 X86CC = DAG.getConstant(CondCode, dl, MVT::i8);
20321 return EFLAGS;
20322}
20323
20324SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
20325
20326 MVT VT = Op.getSimpleValueType();
20327
20328 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
20329
20330 assert(VT == MVT::i8 && "SetCC type must be 8-bit integer")((VT == MVT::i8 && "SetCC type must be 8-bit integer"
) ? static_cast<void> (0) : __assert_fail ("VT == MVT::i8 && \"SetCC type must be 8-bit integer\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 20330, __PRETTY_FUNCTION__))
;
20331 SDValue Op0 = Op.getOperand(0);
20332 SDValue Op1 = Op.getOperand(1);
20333 SDLoc dl(Op);
20334 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
20335
20336 SDValue X86CC;
20337 SDValue EFLAGS = emitFlagsForSetcc(Op0, Op1, CC, dl, DAG, X86CC);
20338 if (!EFLAGS)
20339 return SDValue();
20340
20341 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8, X86CC, EFLAGS);
20342}
20343
20344SDValue X86TargetLowering::LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) const {
20345 SDValue LHS = Op.getOperand(0);
20346 SDValue RHS = Op.getOperand(1);
20347 SDValue Carry = Op.getOperand(2);
20348 SDValue Cond = Op.getOperand(3);
20349 SDLoc DL(Op);
20350
20351 assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only.")((LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only."
) ? static_cast<void> (0) : __assert_fail ("LHS.getSimpleValueType().isInteger() && \"SETCCCARRY is integer only.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 20351, __PRETTY_FUNCTION__))
;
20352 X86::CondCode CC = TranslateIntegerX86CC(cast<CondCodeSDNode>(Cond)->get());
20353
20354 // Recreate the carry if needed.
20355 EVT CarryVT = Carry.getValueType();
20356 APInt NegOne = APInt::getAllOnesValue(CarryVT.getScalarSizeInBits());
20357 Carry = DAG.getNode(X86ISD::ADD, DL, DAG.getVTList(CarryVT, MVT::i32),
20358 Carry, DAG.getConstant(NegOne, DL, CarryVT));
20359
20360 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
20361 SDValue Cmp = DAG.getNode(X86ISD::SBB, DL, VTs, LHS, RHS, Carry.getValue(1));
20362 return getSETCC(CC, Cmp.getValue(1), DL, DAG);
20363}
20364
20365// This function returns three things: the arithmetic computation itself
20366// (Value), an EFLAGS result (Overflow), and a condition code (Cond). The
20367// flag and the condition code define the case in which the arithmetic
20368// computation overflows.
20369static std::pair<SDValue, SDValue>
20370getX86XALUOOp(X86::CondCode &Cond, SDValue Op, SelectionDAG &DAG) {
20371 assert(Op.getResNo() == 0 && "Unexpected result number!")((Op.getResNo() == 0 && "Unexpected result number!") ?
static_cast<void> (0) : __assert_fail ("Op.getResNo() == 0 && \"Unexpected result number!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 20371, __PRETTY_FUNCTION__))
;
20372 SDValue Value, Overflow;
20373 SDValue LHS = Op.getOperand(0);
20374 SDValue RHS = Op.getOperand(1);
20375 unsigned BaseOp = 0;
20376 SDLoc DL(Op);
20377 switch (Op.getOpcode()) {
20378 default: llvm_unreachable("Unknown ovf instruction!")::llvm::llvm_unreachable_internal("Unknown ovf instruction!",
"/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 20378)
;
20379 case ISD::SADDO:
20380 BaseOp = X86ISD::ADD;
20381 Cond = X86::COND_O;
20382 break;
20383 case ISD::UADDO:
20384 BaseOp = X86ISD::ADD;
20385 Cond = isOneConstant(RHS) ? X86::COND_E : X86::COND_B;
20386 break;
20387 case ISD::SSUBO:
20388 BaseOp = X86ISD::SUB;
20389 Cond = X86::COND_O;
20390 break;
20391 case ISD::USUBO:
20392 BaseOp = X86ISD::SUB;
20393 Cond = X86::COND_B;
20394 break;
20395 case ISD::SMULO:
20396 BaseOp = X86ISD::SMUL;
20397 Cond = X86::COND_O;
20398 break;
20399 case ISD::UMULO:
20400 BaseOp = X86ISD::UMUL;
20401 Cond = X86::COND_O;
20402 break;
20403 }
20404
20405 if (BaseOp) {
20406 // Also sets EFLAGS.
20407 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
20408 Value = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
20409 Overflow = Value.getValue(1);
20410 }
20411
20412 return std::make_pair(Value, Overflow);
20413}
20414
20415static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
20416 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
20417 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
20418 // looks for this combo and may remove the "setcc" instruction if the "setcc"
20419 // has only one use.
20420 SDLoc DL(Op);
20421 X86::CondCode Cond;
20422 SDValue Value, Overflow;
20423 std::tie(Value, Overflow) = getX86XALUOOp(Cond, Op, DAG);
20424
20425 SDValue SetCC = getSETCC(Cond, Overflow, DL, DAG);
20426 assert(Op->getValueType(1) == MVT::i8 && "Unexpected VT!")((Op->getValueType(1) == MVT::i8 && "Unexpected VT!"
) ? static_cast<void> (0) : __assert_fail ("Op->getValueType(1) == MVT::i8 && \"Unexpected VT!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 20426, __PRETTY_FUNCTION__))
;
20427 return DAG.getNode(ISD::MERGE_VALUES, DL, Op->getVTList(), Value, SetCC);
20428}
20429
20430/// Return true if opcode is a X86 logical comparison.
20431static bool isX86LogicalCmp(SDValue Op) {
20432 unsigned Opc = Op.getOpcode();
20433 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
20434 Opc == X86ISD::SAHF)
20435 return true;
20436 if (Op.getResNo() == 1 &&
20437 (Opc == X86ISD::ADD || Opc == X86ISD::SUB || Opc == X86ISD::ADC ||
20438 Opc == X86ISD::SBB || Opc == X86ISD::SMUL || Opc == X86ISD::UMUL ||
20439 Opc == X86ISD::OR || Opc == X86ISD::XOR || Opc == X86ISD::AND))
20440 return true;
20441
20442 return false;
20443}
20444
20445static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
20446 if (V.getOpcode() != ISD::TRUNCATE)
20447 return false;
20448
20449 SDValue VOp0 = V.getOperand(0);
20450 unsigned InBits = VOp0.getValueSizeInBits();
20451 unsigned Bits = V.getValueSizeInBits();
20452 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
20453}
20454
20455SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
20456 bool AddTest = true;
20457 SDValue Cond = Op.getOperand(0);
20458 SDValue Op1 = Op.getOperand(1);
20459 SDValue Op2 = Op.getOperand(2);
20460 SDLoc DL(Op);
20461 MVT VT = Op1.getSimpleValueType();
20462 SDValue CC;
20463
20464 // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
20465 // are available or VBLENDV if AVX is available.
20466 // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
20467 if (Cond.getOpcode() == ISD::SETCC &&
20468 ((Subtarget.hasSSE2() && VT == MVT::f64) ||
20469 (Subtarget.hasSSE1() && VT == MVT::f32)) &&
20470 VT == Cond.getOperand(0).getSimpleValueType() && Cond->hasOneUse()) {
20471 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
20472 unsigned SSECC = translateX86FSETCC(
20473 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
20474
20475 if (Subtarget.hasAVX512()) {
20476 SDValue Cmp = DAG.getNode(X86ISD::FSETCCM, DL, MVT::v1i1, CondOp0,
20477 CondOp1, DAG.getConstant(SSECC, DL, MVT::i8));
20478 assert(!VT.isVector() && "Not a scalar type?")((!VT.isVector() && "Not a scalar type?") ? static_cast
<void> (0) : __assert_fail ("!VT.isVector() && \"Not a scalar type?\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 20478, __PRETTY_FUNCTION__))
;
20479 return DAG.getNode(X86ISD::SELECTS, DL, VT, Cmp, Op1, Op2);
20480 }
20481
20482 if (SSECC < 8 || Subtarget.hasAVX()) {
20483 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
20484 DAG.getConstant(SSECC, DL, MVT::i8));
20485
20486 // If we have AVX, we can use a variable vector select (VBLENDV) instead
20487 // of 3 logic instructions for size savings and potentially speed.
20488 // Unfortunately, there is no scalar form of VBLENDV.
20489
20490 // If either operand is a +0.0 constant, don't try this. We can expect to
20491 // optimize away at least one of the logic instructions later in that
20492 // case, so that sequence would be faster than a variable blend.
20493
20494 // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
20495 // uses XMM0 as the selection register. That may need just as many
20496 // instructions as the AND/ANDN/OR sequence due to register moves, so
20497 // don't bother.
20498 if (Subtarget.hasAVX() && !isNullFPConstant(Op1) &&
20499 !isNullFPConstant(Op2)) {
20500 // Convert to vectors, do a VSELECT, and convert back to scalar.
20501 // All of the conversions should be optimized away.
20502 MVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
20503 SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
20504 SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
20505 SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
20506
20507 MVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
20508 VCmp = DAG.getBitcast(VCmpVT, VCmp);
20509
20510 SDValue VSel = DAG.getSelect(DL, VecVT, VCmp, VOp1, VOp2);
20511
20512 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
20513 VSel, DAG.getIntPtrConstant(0, DL));
20514 }
20515 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
20516 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
20517 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
20518 }
20519 }
20520
20521 // AVX512 fallback is to lower selects of scalar floats to masked moves.
20522 if ((VT == MVT::f64 || VT == MVT::f32) && Subtarget.hasAVX512()) {
20523 SDValue Cmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v1i1, Cond);
20524 return DAG.getNode(X86ISD::SELECTS, DL, VT, Cmp, Op1, Op2);
20525 }
20526
20527 // For v64i1 without 64-bit support we need to split and rejoin.
20528 if (VT == MVT::v64i1 && !Subtarget.is64Bit()) {
20529 assert(Subtarget.hasBWI() && "Expected BWI to be legal")((Subtarget.hasBWI() && "Expected BWI to be legal") ?
static_cast<void> (0) : __assert_fail ("Subtarget.hasBWI() && \"Expected BWI to be legal\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 20529, __PRETTY_FUNCTION__))
;
20530 SDValue Op1Lo = extractSubVector(Op1, 0, DAG, DL, 32);
20531 SDValue Op2Lo = extractSubVector(Op2, 0, DAG, DL, 32);
20532 SDValue Op1Hi = extractSubVector(Op1, 32, DAG, DL, 32);
20533 SDValue Op2Hi = extractSubVector(Op2, 32, DAG, DL, 32);
20534 SDValue Lo = DAG.getSelect(DL, MVT::v32i1, Cond, Op1Lo, Op2Lo);
20535 SDValue Hi = DAG.getSelect(DL, MVT::v32i1, Cond, Op1Hi, Op2Hi);
20536 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
20537 }
20538
20539 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
20540 SDValue Op1Scalar;
20541 if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
20542 Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
20543 else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
20544 Op1Scalar = Op1.getOperand(0);
20545 SDValue Op2Scalar;
20546 if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
20547 Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
20548 else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
20549 Op2Scalar = Op2.getOperand(0);
20550 if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
20551 SDValue newSelect = DAG.getSelect(DL, Op1Scalar.getValueType(), Cond,
20552 Op1Scalar, Op2Scalar);
20553 if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
20554 return DAG.getBitcast(VT, newSelect);
20555 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
20556 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
20557 DAG.getIntPtrConstant(0, DL));
20558 }
20559 }
20560
20561 if (Cond.getOpcode() == ISD::SETCC) {
20562 if (SDValue NewCond = LowerSETCC(Cond, DAG)) {
20563 Cond = NewCond;
20564 // If the condition was updated, it's possible that the operands of the
20565 // select were also updated (for example, EmitTest has a RAUW). Refresh
20566 // the local references to the select operands in case they got stale.
20567 Op1 = Op.getOperand(1);
20568 Op2 = Op.getOperand(2);
20569 }
20570 }
20571
20572 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
20573 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
20574 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
20575 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
20576 // (select (and (x , 0x1) == 0), y, (z ^ y) ) -> (-(and (x , 0x1)) & z ) ^ y
20577 // (select (and (x , 0x1) == 0), y, (z | y) ) -> (-(and (x , 0x1)) & z ) | y
20578 if (Cond.getOpcode() == X86ISD::SETCC &&
20579 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
20580 isNullConstant(Cond.getOperand(1).getOperand(1))) {
20581 SDValue Cmp = Cond.getOperand(1);
20582 unsigned CondCode =
20583 cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
20584
20585 if ((isAllOnesConstant(Op1) || isAllOnesConstant(Op2)) &&
20586 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
20587 SDValue Y = isAllOnesConstant(Op2) ? Op1 : Op2;
20588 SDValue CmpOp0 = Cmp.getOperand(0);
20589
20590 // Apply further optimizations for special cases
20591 // (select (x != 0), -1, 0) -> neg & sbb
20592 // (select (x == 0), 0, -1) -> neg & sbb
20593 if (isNullConstant(Y) &&
20594 (isAllOnesConstant(Op1) == (CondCode == X86::COND_NE))) {
20595 SDValue Zero = DAG.getConstant(0, DL, CmpOp0.getValueType());
20596 SDValue CmpZero = DAG.getNode(X86ISD::CMP, DL, MVT::i32, Zero, CmpOp0);
20597 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
20598 Zero = DAG.getConstant(0, DL, Op.getValueType());
20599 return DAG.getNode(X86ISD::SBB, DL, VTs, Zero, Zero, CmpZero);
20600 }
20601
20602 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
20603 CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
20604 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
20605
20606 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
20607 SDValue Zero = DAG.getConstant(0, DL, Op.getValueType());
20608 SDValue Res = // Res = 0 or -1.
20609 DAG.getNode(X86ISD::SBB, DL, VTs, Zero, Zero, Cmp);
20610
20611 if (isAllOnesConstant(Op1) != (CondCode == X86::COND_E))
20612 Res = DAG.getNOT(DL, Res, Res.getValueType());
20613
20614 if (!isNullConstant(Op2))
20615 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
20616 return Res;
20617 } else if (!Subtarget.hasCMov() && CondCode == X86::COND_E &&
20618 Cmp.getOperand(0).getOpcode() == ISD::AND &&
20619 isOneConstant(Cmp.getOperand(0).getOperand(1))) {
20620 SDValue CmpOp0 = Cmp.getOperand(0);
20621 SDValue Src1, Src2;
20622 // true if Op2 is XOR or OR operator and one of its operands
20623 // is equal to Op1
20624 // ( a , a op b) || ( b , a op b)
20625 auto isOrXorPattern = [&]() {
20626 if ((Op2.getOpcode() == ISD::XOR || Op2.getOpcode() == ISD::OR) &&
20627 (Op2.getOperand(0) == Op1 || Op2.getOperand(1) == Op1)) {
20628 Src1 =
20629 Op2.getOperand(0) == Op1 ? Op2.getOperand(1) : Op2.getOperand(0);
20630 Src2 = Op1;
20631 return true;
20632 }
20633 return false;
20634 };
20635
20636 if (isOrXorPattern()) {
20637 SDValue Neg;
20638 unsigned int CmpSz = CmpOp0.getSimpleValueType().getSizeInBits();
20639 // we need mask of all zeros or ones with same size of the other
20640 // operands.
20641 if (CmpSz > VT.getSizeInBits())
20642 Neg = DAG.getNode(ISD::TRUNCATE, DL, VT, CmpOp0);
20643 else if (CmpSz < VT.getSizeInBits())
20644 Neg = DAG.getNode(ISD::AND, DL, VT,
20645 DAG.getNode(ISD::ANY_EXTEND, DL, VT, CmpOp0.getOperand(0)),
20646 DAG.getConstant(1, DL, VT));
20647 else
20648 Neg = CmpOp0;
20649 SDValue Mask = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
20650 Neg); // -(and (x, 0x1))
20651 SDValue And = DAG.getNode(ISD::AND, DL, VT, Mask, Src1); // Mask & z
20652 return DAG.getNode(Op2.getOpcode(), DL, VT, And, Src2); // And Op y
20653 }
20654 }
20655 }
20656
20657 // Look past (and (setcc_carry (cmp ...)), 1).
20658 if (Cond.getOpcode() == ISD::AND &&
20659 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY &&
20660 isOneConstant(Cond.getOperand(1)))
20661 Cond = Cond.getOperand(0);
20662
20663 // If condition flag is set by a X86ISD::CMP, then use it as the condition
20664 // setting operand in place of the X86ISD::SETCC.
20665 unsigned CondOpcode = Cond.getOpcode();
20666 if (CondOpcode == X86ISD::SETCC ||
20667 CondOpcode == X86ISD::SETCC_CARRY) {
20668 CC = Cond.getOperand(0);
20669
20670 SDValue Cmp = Cond.getOperand(1);
20671 MVT VT = Op.getSimpleValueType();
20672
20673 bool IllegalFPCMov = false;
20674 if (VT.isFloatingPoint() && !VT.isVector() &&
20675 !isScalarFPTypeInSSEReg(VT)) // FPStack?
20676 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
20677
20678 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
20679 Cmp.getOpcode() == X86ISD::BT) { // FIXME
20680 Cond = Cmp;
20681 AddTest = false;
20682 }
20683 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
20684 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
20685 CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) {
20686 SDValue Value;
20687 X86::CondCode X86Cond;
20688 std::tie(Value, Cond) = getX86XALUOOp(X86Cond, Cond.getValue(0), DAG);
20689
20690 CC = DAG.getConstant(X86Cond, DL, MVT::i8);
20691 AddTest = false;
20692 }
20693
20694 if (AddTest) {
20695 // Look past the truncate if the high bits are known zero.
20696 if (isTruncWithZeroHighBitsInput(Cond, DAG))
20697 Cond = Cond.getOperand(0);
20698
20699 // We know the result of AND is compared against zero. Try to match
20700 // it to BT.
20701 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
20702 SDValue BTCC;
20703 if (SDValue BT = LowerAndToBT(Cond, ISD::SETNE, DL, DAG, BTCC)) {
20704 CC = BTCC;
20705 Cond = BT;
20706 AddTest = false;
20707 }
20708 }
20709 }
20710
20711 if (AddTest) {
20712 CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
20713 Cond = EmitCmp(Cond, DAG.getConstant(0, DL, Cond.getValueType()),
20714 X86::COND_NE, DL, DAG);
20715 }
20716
20717 // a < b ? -1 : 0 -> RES = ~setcc_carry
20718 // a < b ? 0 : -1 -> RES = setcc_carry
20719 // a >= b ? -1 : 0 -> RES = setcc_carry
20720 // a >= b ? 0 : -1 -> RES = ~setcc_carry
20721 if (Cond.getOpcode() == X86ISD::SUB) {
20722 Cond = ConvertCmpIfNecessary(Cond, DAG);
20723 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
20724
20725 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
20726 (isAllOnesConstant(Op1) || isAllOnesConstant(Op2)) &&
20727 (isNullConstant(Op1) || isNullConstant(Op2))) {
20728 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
20729 DAG.getConstant(X86::COND_B, DL, MVT::i8),
20730 Cond);
20731 if (isAllOnesConstant(Op1) != (CondCode == X86::COND_B))
20732 return DAG.getNOT(DL, Res, Res.getValueType());
20733 return Res;
20734 }
20735 }
20736
20737 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
20738 // widen the cmov and push the truncate through. This avoids introducing a new
20739 // branch during isel and doesn't add any extensions.
20740 if (Op.getValueType() == MVT::i8 &&
20741 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
20742 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
20743 if (T1.getValueType() == T2.getValueType() &&
20744 // Blacklist CopyFromReg to avoid partial register stalls.
20745 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
20746 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, T1.getValueType(), T2, T1,
20747 CC, Cond);
20748 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
20749 }
20750 }
20751
20752 // Or finally, promote i8 cmovs if we have CMOV,
20753 // or i16 cmovs if it won't prevent folding a load.
20754 // FIXME: we should not limit promotion of i8 case to only when the CMOV is
20755 // legal, but EmitLoweredSelect() can not deal with these extensions
20756 // being inserted between two CMOV's. (in i16 case too TBN)
20757 // https://bugs.llvm.org/show_bug.cgi?id=40974
20758 if ((Op.getValueType() == MVT::i8 && Subtarget.hasCMov()) ||
20759 (Op.getValueType() == MVT::i16 && !MayFoldLoad(Op1) &&
20760 !MayFoldLoad(Op2))) {
20761 Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op1);
20762 Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op2);
20763 SDValue Ops[] = { Op2, Op1, CC, Cond };
20764 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, MVT::i32, Ops);
20765 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
20766 }
20767
20768 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
20769 // condition is true.
20770 SDValue Ops[] = { Op2, Op1, CC, Cond };
20771 return DAG.getNode(X86ISD::CMOV, DL, Op.getValueType(), Ops);
20772}
20773
20774static SDValue LowerSIGN_EXTEND_Mask(SDValue Op,
20775 const X86Subtarget &Subtarget,
20776 SelectionDAG &DAG) {
20777 MVT VT = Op->getSimpleValueType(0);
20778 SDValue In = Op->getOperand(0);
20779 MVT InVT = In.getSimpleValueType();
20780 assert(InVT.getVectorElementType() == MVT::i1 && "Unexpected input type!")((InVT.getVectorElementType() == MVT::i1 && "Unexpected input type!"
) ? static_cast<void> (0) : __assert_fail ("InVT.getVectorElementType() == MVT::i1 && \"Unexpected input type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 20780, __PRETTY_FUNCTION__))
;
20781 MVT VTElt = VT.getVectorElementType();
20782 SDLoc dl(Op);
20783
20784 unsigned NumElts = VT.getVectorNumElements();
20785
20786 // Extend VT if the scalar type is i8/i16 and BWI is not supported.
20787 MVT ExtVT = VT;
20788 if (!Subtarget.hasBWI() && VTElt.getSizeInBits() <= 16) {
20789 // If v16i32 is to be avoided, we'll need to split and concatenate.
20790 if (NumElts == 16 && !Subtarget.canExtendTo512DQ())
20791 return SplitAndExtendv16i1(Op.getOpcode(), VT, In, dl, DAG);
20792
20793 ExtVT = MVT::getVectorVT(MVT::i32, NumElts);
20794 }
20795
20796 // Widen to 512-bits if VLX is not supported.
20797 MVT WideVT = ExtVT;
20798 if (!ExtVT.is512BitVector() && !Subtarget.hasVLX()) {
20799 NumElts *= 512 / ExtVT.getSizeInBits();
20800 InVT = MVT::getVectorVT(MVT::i1, NumElts);
20801 In = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, InVT, DAG.getUNDEF(InVT),
20802 In, DAG.getIntPtrConstant(0, dl));
20803 WideVT = MVT::getVectorVT(ExtVT.getVectorElementType(), NumElts);
20804 }
20805
20806 SDValue V;
20807 MVT WideEltVT = WideVT.getVectorElementType();
20808 if ((Subtarget.hasDQI() && WideEltVT.getSizeInBits() >= 32) ||
20809 (Subtarget.hasBWI() && WideEltVT.getSizeInBits() <= 16)) {
20810 V = DAG.getNode(Op.getOpcode(), dl, WideVT, In);
20811 } else {
20812 SDValue NegOne = DAG.getConstant(-1, dl, WideVT);
20813 SDValue Zero = DAG.getConstant(0, dl, WideVT);
20814 V = DAG.getSelect(dl, WideVT, In, NegOne, Zero);
20815 }
20816
20817 // Truncate if we had to extend i16/i8 above.
20818 if (VT != ExtVT) {
20819 WideVT = MVT::getVectorVT(VTElt, NumElts);
20820 V = DAG.getNode(ISD::TRUNCATE, dl, WideVT, V);
20821 }
20822
20823 // Extract back to 128/256-bit if we widened.
20824 if (WideVT != VT)
20825 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, V,
20826 DAG.getIntPtrConstant(0, dl));
20827
20828 return V;
20829}
20830
20831static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget &Subtarget,
20832 SelectionDAG &DAG) {
20833 SDValue In = Op->getOperand(0);
20834 MVT InVT = In.getSimpleValueType();
20835
20836 if (InVT.getVectorElementType() == MVT::i1)
20837 return LowerSIGN_EXTEND_Mask(Op, Subtarget, DAG);
20838
20839 assert(Subtarget.hasAVX() && "Expected AVX support")((Subtarget.hasAVX() && "Expected AVX support") ? static_cast
<void> (0) : __assert_fail ("Subtarget.hasAVX() && \"Expected AVX support\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 20839, __PRETTY_FUNCTION__))
;
20840 return LowerAVXExtend(Op, DAG, Subtarget);
20841}
20842
20843// Lowering for SIGN_EXTEND_VECTOR_INREG and ZERO_EXTEND_VECTOR_INREG.
20844// For sign extend this needs to handle all vector sizes and SSE4.1 and
20845// non-SSE4.1 targets. For zero extend this should only handle inputs of
20846// MVT::v64i8 when BWI is not supported, but AVX512 is.
20847static SDValue LowerEXTEND_VECTOR_INREG(SDValue Op,
20848 const X86Subtarget &Subtarget,
20849 SelectionDAG &DAG) {
20850 SDValue In = Op->getOperand(0);
20851 MVT VT = Op->getSimpleValueType(0);
20852 MVT InVT = In.getSimpleValueType();
20853
20854 MVT SVT = VT.getVectorElementType();
20855 MVT InSVT = InVT.getVectorElementType();
20856 assert(SVT.getSizeInBits() > InSVT.getSizeInBits())((SVT.getSizeInBits() > InSVT.getSizeInBits()) ? static_cast
<void> (0) : __assert_fail ("SVT.getSizeInBits() > InSVT.getSizeInBits()"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 20856, __PRETTY_FUNCTION__))
;
20857
20858 if (SVT != MVT::i64 && SVT != MVT::i32 && SVT != MVT::i16)
20859 return SDValue();
20860 if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
20861 return SDValue();
20862 if (!(VT.is128BitVector() && Subtarget.hasSSE2()) &&
20863 !(VT.is256BitVector() && Subtarget.hasAVX()) &&
20864 !(VT.is512BitVector() && Subtarget.hasAVX512()))
20865 return SDValue();
20866
20867 SDLoc dl(Op);
20868 unsigned Opc = Op.getOpcode();
20869 unsigned NumElts = VT.getVectorNumElements();
20870
20871 // For 256-bit vectors, we only need the lower (128-bit) half of the input.
20872 // For 512-bit vectors, we need 128-bits or 256-bits.
20873 if (InVT.getSizeInBits() > 128) {
20874 // Input needs to be at least the same number of elements as output, and
20875 // at least 128-bits.
20876 int InSize = InSVT.getSizeInBits() * NumElts;
20877 In = extractSubVector(In, 0, DAG, dl, std::max(InSize, 128));
20878 InVT = In.getSimpleValueType();
20879 }
20880
20881 // SSE41 targets can use the pmov[sz]x* instructions directly for 128-bit results,
20882 // so are legal and shouldn't occur here. AVX2/AVX512 pmovsx* instructions still
20883 // need to be handled here for 256/512-bit results.
20884 if (Subtarget.hasInt256()) {
20885 assert(VT.getSizeInBits() > 128 && "Unexpected 128-bit vector extension")((VT.getSizeInBits() > 128 && "Unexpected 128-bit vector extension"
) ? static_cast<void> (0) : __assert_fail ("VT.getSizeInBits() > 128 && \"Unexpected 128-bit vector extension\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 20885, __PRETTY_FUNCTION__))
;
20886
20887 if (InVT.getVectorNumElements() != NumElts)
20888 return DAG.getNode(Op.getOpcode(), dl, VT, In);
20889
20890 // FIXME: Apparently we create inreg operations that could be regular
20891 // extends.
20892 unsigned ExtOpc =
20893 Opc == ISD::SIGN_EXTEND_VECTOR_INREG ? ISD::SIGN_EXTEND
20894 : ISD::ZERO_EXTEND;
20895 return DAG.getNode(ExtOpc, dl, VT, In);
20896 }
20897
20898 // pre-AVX2 256-bit extensions need to be split into 128-bit instructions.
20899 if (Subtarget.hasAVX()) {
20900 assert(VT.is256BitVector() && "256-bit vector expected")((VT.is256BitVector() && "256-bit vector expected") ?
static_cast<void> (0) : __assert_fail ("VT.is256BitVector() && \"256-bit vector expected\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 20900, __PRETTY_FUNCTION__))
;
20901 int HalfNumElts = NumElts / 2;
20902 MVT HalfVT = MVT::getVectorVT(SVT, HalfNumElts);
20903
20904 unsigned NumSrcElts = InVT.getVectorNumElements();
20905 SmallVector<int, 16> HiMask(NumSrcElts, SM_SentinelUndef);
20906 for (int i = 0; i != HalfNumElts; ++i)
20907 HiMask[i] = HalfNumElts + i;
20908
20909 SDValue Lo = DAG.getNode(Opc, dl, HalfVT, In);
20910 SDValue Hi = DAG.getVectorShuffle(InVT, dl, In, DAG.getUNDEF(InVT), HiMask);
20911 Hi = DAG.getNode(Opc, dl, HalfVT, Hi);
20912 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
20913 }
20914
20915 // We should only get here for sign extend.
20916 assert(Opc == ISD::SIGN_EXTEND_VECTOR_INREG && "Unexpected opcode!")((Opc == ISD::SIGN_EXTEND_VECTOR_INREG && "Unexpected opcode!"
) ? static_cast<void> (0) : __assert_fail ("Opc == ISD::SIGN_EXTEND_VECTOR_INREG && \"Unexpected opcode!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 20916, __PRETTY_FUNCTION__))
;
20917 assert(VT.is128BitVector() && InVT.is128BitVector() && "Unexpected VTs")((VT.is128BitVector() && InVT.is128BitVector() &&
"Unexpected VTs") ? static_cast<void> (0) : __assert_fail
("VT.is128BitVector() && InVT.is128BitVector() && \"Unexpected VTs\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 20917, __PRETTY_FUNCTION__))
;
20918
20919 // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
20920 SDValue Curr = In;
20921 SDValue SignExt = Curr;
20922
20923 // As SRAI is only available on i16/i32 types, we expand only up to i32
20924 // and handle i64 separately.
20925 if (InVT != MVT::v4i32) {
20926 MVT DestVT = VT == MVT::v2i64 ? MVT::v4i32 : VT;
20927
20928 unsigned DestWidth = DestVT.getScalarSizeInBits();
20929 unsigned Scale = DestWidth / InSVT.getSizeInBits();
20930
20931 unsigned InNumElts = InVT.getVectorNumElements();
20932 unsigned DestElts = DestVT.getVectorNumElements();
20933
20934 // Build a shuffle mask that takes each input element and places it in the
20935 // MSBs of the new element size.
20936 SmallVector<int, 16> Mask(InNumElts, SM_SentinelUndef);
20937 for (unsigned i = 0; i != DestElts; ++i)
20938 Mask[i * Scale + (Scale - 1)] = i;
20939
20940 Curr = DAG.getVectorShuffle(InVT, dl, In, In, Mask);
20941 Curr = DAG.getBitcast(DestVT, Curr);
20942
20943 unsigned SignExtShift = DestWidth - InSVT.getSizeInBits();
20944 SignExt = DAG.getNode(X86ISD::VSRAI, dl, DestVT, Curr,
20945 DAG.getConstant(SignExtShift, dl, MVT::i8));
20946 }
20947
20948 if (VT == MVT::v2i64) {
20949 assert(Curr.getValueType() == MVT::v4i32 && "Unexpected input VT")((Curr.getValueType() == MVT::v4i32 && "Unexpected input VT"
) ? static_cast<void> (0) : __assert_fail ("Curr.getValueType() == MVT::v4i32 && \"Unexpected input VT\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 20949, __PRETTY_FUNCTION__))
;
20950 SDValue Zero = DAG.getConstant(0, dl, MVT::v4i32);
20951 SDValue Sign = DAG.getSetCC(dl, MVT::v4i32, Zero, Curr, ISD::SETGT);
20952 SignExt = DAG.getVectorShuffle(MVT::v4i32, dl, SignExt, Sign, {0, 4, 1, 5});
20953 SignExt = DAG.getBitcast(VT, SignExt);
20954 }
20955
20956 return SignExt;
20957}
20958
20959static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget &Subtarget,
20960 SelectionDAG &DAG) {
20961 MVT VT = Op->getSimpleValueType(0);
20962 SDValue In = Op->getOperand(0);
20963 MVT InVT = In.getSimpleValueType();
20964 SDLoc dl(Op);
20965
20966 if (InVT.getVectorElementType() == MVT::i1)
20967 return LowerSIGN_EXTEND_Mask(Op, Subtarget, DAG);
20968
20969 assert(VT.isVector() && InVT.isVector() && "Expected vector type")((VT.isVector() && InVT.isVector() && "Expected vector type"
) ? static_cast<void> (0) : __assert_fail ("VT.isVector() && InVT.isVector() && \"Expected vector type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 20969, __PRETTY_FUNCTION__))
;
20970 assert(VT.getVectorNumElements() == VT.getVectorNumElements() &&((VT.getVectorNumElements() == VT.getVectorNumElements() &&
"Expected same number of elements") ? static_cast<void>
(0) : __assert_fail ("VT.getVectorNumElements() == VT.getVectorNumElements() && \"Expected same number of elements\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 20971, __PRETTY_FUNCTION__))
20971 "Expected same number of elements")((VT.getVectorNumElements() == VT.getVectorNumElements() &&
"Expected same number of elements") ? static_cast<void>
(0) : __assert_fail ("VT.getVectorNumElements() == VT.getVectorNumElements() && \"Expected same number of elements\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 20971, __PRETTY_FUNCTION__))
;
20972 assert((VT.getVectorElementType() == MVT::i16 ||(((VT.getVectorElementType() == MVT::i16 || VT.getVectorElementType
() == MVT::i32 || VT.getVectorElementType() == MVT::i64) &&
"Unexpected element type") ? static_cast<void> (0) : __assert_fail
("(VT.getVectorElementType() == MVT::i16 || VT.getVectorElementType() == MVT::i32 || VT.getVectorElementType() == MVT::i64) && \"Unexpected element type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 20975, __PRETTY_FUNCTION__))
20973 VT.getVectorElementType() == MVT::i32 ||(((VT.getVectorElementType() == MVT::i16 || VT.getVectorElementType
() == MVT::i32 || VT.getVectorElementType() == MVT::i64) &&
"Unexpected element type") ? static_cast<void> (0) : __assert_fail
("(VT.getVectorElementType() == MVT::i16 || VT.getVectorElementType() == MVT::i32 || VT.getVectorElementType() == MVT::i64) && \"Unexpected element type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 20975, __PRETTY_FUNCTION__))
20974 VT.getVectorElementType() == MVT::i64) &&(((VT.getVectorElementType() == MVT::i16 || VT.getVectorElementType
() == MVT::i32 || VT.getVectorElementType() == MVT::i64) &&
"Unexpected element type") ? static_cast<void> (0) : __assert_fail
("(VT.getVectorElementType() == MVT::i16 || VT.getVectorElementType() == MVT::i32 || VT.getVectorElementType() == MVT::i64) && \"Unexpected element type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 20975, __PRETTY_FUNCTION__))
20975 "Unexpected element type")(((VT.getVectorElementType() == MVT::i16 || VT.getVectorElementType
() == MVT::i32 || VT.getVectorElementType() == MVT::i64) &&
"Unexpected element type") ? static_cast<void> (0) : __assert_fail
("(VT.getVectorElementType() == MVT::i16 || VT.getVectorElementType() == MVT::i32 || VT.getVectorElementType() == MVT::i64) && \"Unexpected element type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 20975, __PRETTY_FUNCTION__))
;
20976 assert((InVT.getVectorElementType() == MVT::i8 ||(((InVT.getVectorElementType() == MVT::i8 || InVT.getVectorElementType
() == MVT::i16 || InVT.getVectorElementType() == MVT::i32) &&
"Unexpected element type") ? static_cast<void> (0) : __assert_fail
("(InVT.getVectorElementType() == MVT::i8 || InVT.getVectorElementType() == MVT::i16 || InVT.getVectorElementType() == MVT::i32) && \"Unexpected element type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 20979, __PRETTY_FUNCTION__))
20977 InVT.getVectorElementType() == MVT::i16 ||(((InVT.getVectorElementType() == MVT::i8 || InVT.getVectorElementType
() == MVT::i16 || InVT.getVectorElementType() == MVT::i32) &&
"Unexpected element type") ? static_cast<void> (0) : __assert_fail
("(InVT.getVectorElementType() == MVT::i8 || InVT.getVectorElementType() == MVT::i16 || InVT.getVectorElementType() == MVT::i32) && \"Unexpected element type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 20979, __PRETTY_FUNCTION__))
20978 InVT.getVectorElementType() == MVT::i32) &&(((InVT.getVectorElementType() == MVT::i8 || InVT.getVectorElementType
() == MVT::i16 || InVT.getVectorElementType() == MVT::i32) &&
"Unexpected element type") ? static_cast<void> (0) : __assert_fail
("(InVT.getVectorElementType() == MVT::i8 || InVT.getVectorElementType() == MVT::i16 || InVT.getVectorElementType() == MVT::i32) && \"Unexpected element type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 20979, __PRETTY_FUNCTION__))
20979 "Unexpected element type")(((InVT.getVectorElementType() == MVT::i8 || InVT.getVectorElementType
() == MVT::i16 || InVT.getVectorElementType() == MVT::i32) &&
"Unexpected element type") ? static_cast<void> (0) : __assert_fail
("(InVT.getVectorElementType() == MVT::i8 || InVT.getVectorElementType() == MVT::i16 || InVT.getVectorElementType() == MVT::i32) && \"Unexpected element type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 20979, __PRETTY_FUNCTION__))
;
20980
20981 // Custom legalize v8i8->v8i64 on CPUs without avx512bw.
20982 if (InVT == MVT::v8i8) {
20983 if (!ExperimentalVectorWideningLegalization || VT != MVT::v8i64)
20984 return SDValue();
20985
20986 In = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op),
20987 MVT::v16i8, In, DAG.getUNDEF(MVT::v8i8));
20988 return DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, dl, VT, In);
20989 }
20990
20991 if (Subtarget.hasInt256())
20992 return Op;
20993
20994 // Optimize vectors in AVX mode
20995 // Sign extend v8i16 to v8i32 and
20996 // v4i32 to v4i64
20997 //
20998 // Divide input vector into two parts
20999 // for v4i32 the high shuffle mask will be {2, 3, -1, -1}
21000 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
21001 // concat the vectors to original VT
21002
21003 MVT HalfVT = MVT::getVectorVT(VT.getVectorElementType(),
21004 VT.getVectorNumElements() / 2);
21005
21006 SDValue OpLo = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, dl, HalfVT, In);
21007
21008 unsigned NumElems = InVT.getVectorNumElements();
21009 SmallVector<int,8> ShufMask(NumElems, -1);
21010 for (unsigned i = 0; i != NumElems/2; ++i)
21011 ShufMask[i] = i + NumElems/2;
21012
21013 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, In, ShufMask);
21014 OpHi = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, dl, HalfVT, OpHi);
21015
21016 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
21017}
21018
21019/// Change a 256-bit vector store into a pair of 128-bit vector stores.
21020static SDValue split256BitStore(StoreSDNode *Store, SelectionDAG &DAG) {
21021 SDValue StoredVal = Store->getValue();
21022 assert(StoredVal.getValueType().is256BitVector() && "Expecting 256-bit op")((StoredVal.getValueType().is256BitVector() && "Expecting 256-bit op"
) ? static_cast<void> (0) : __assert_fail ("StoredVal.getValueType().is256BitVector() && \"Expecting 256-bit op\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 21022, __PRETTY_FUNCTION__))
;
21023
21024 // Splitting volatile memory ops is not allowed unless the operation was not
21025 // legal to begin with. We are assuming the input op is legal (this transform
21026 // is only used for targets with AVX).
21027 if (Store->isVolatile())
21028 return SDValue();
21029
21030 MVT StoreVT = StoredVal.getSimpleValueType();
21031 unsigned NumElems = StoreVT.getVectorNumElements();
21032 SDLoc DL(Store);
21033 SDValue Value0 = extract128BitVector(StoredVal, 0, DAG, DL);
21034 SDValue Value1 = extract128BitVector(StoredVal, NumElems / 2, DAG, DL);
21035 SDValue Ptr0 = Store->getBasePtr();
21036 SDValue Ptr1 = DAG.getMemBasePlusOffset(Ptr0, 16, DL);
21037 unsigned Alignment = Store->getAlignment();
21038 SDValue Ch0 =
21039 DAG.getStore(Store->getChain(), DL, Value0, Ptr0, Store->getPointerInfo(),
21040 Alignment, Store->getMemOperand()->getFlags());
21041 SDValue Ch1 =
21042 DAG.getStore(Store->getChain(), DL, Value1, Ptr1,
21043 Store->getPointerInfo().getWithOffset(16),
21044 MinAlign(Alignment, 16), Store->getMemOperand()->getFlags());
21045 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Ch0, Ch1);
21046}
21047
21048static SDValue LowerStore(SDValue Op, const X86Subtarget &Subtarget,
21049 SelectionDAG &DAG) {
21050 StoreSDNode *St = cast<StoreSDNode>(Op.getNode());
21051 SDLoc dl(St);
21052 SDValue StoredVal = St->getValue();
21053
21054 // Without AVX512DQ, we need to use a scalar type for v2i1/v4i1/v8i1 stores.
21055 if (StoredVal.getValueType().isVector() &&
21056 StoredVal.getValueType().getVectorElementType() == MVT::i1) {
21057 assert(StoredVal.getValueType().getVectorNumElements() <= 8 &&((StoredVal.getValueType().getVectorNumElements() <= 8 &&
"Unexpected VT") ? static_cast<void> (0) : __assert_fail
("StoredVal.getValueType().getVectorNumElements() <= 8 && \"Unexpected VT\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 21058, __PRETTY_FUNCTION__))
21058 "Unexpected VT")((StoredVal.getValueType().getVectorNumElements() <= 8 &&
"Unexpected VT") ? static_cast<void> (0) : __assert_fail
("StoredVal.getValueType().getVectorNumElements() <= 8 && \"Unexpected VT\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 21058, __PRETTY_FUNCTION__))
;
21059 assert(!St->isTruncatingStore() && "Expected non-truncating store")((!St->isTruncatingStore() && "Expected non-truncating store"
) ? static_cast<void> (0) : __assert_fail ("!St->isTruncatingStore() && \"Expected non-truncating store\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 21059, __PRETTY_FUNCTION__))
;
21060 assert(Subtarget.hasAVX512() && !Subtarget.hasDQI() &&((Subtarget.hasAVX512() && !Subtarget.hasDQI() &&
"Expected AVX512F without AVX512DQI") ? static_cast<void>
(0) : __assert_fail ("Subtarget.hasAVX512() && !Subtarget.hasDQI() && \"Expected AVX512F without AVX512DQI\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 21061, __PRETTY_FUNCTION__))
21061 "Expected AVX512F without AVX512DQI")((Subtarget.hasAVX512() && !Subtarget.hasDQI() &&
"Expected AVX512F without AVX512DQI") ? static_cast<void>
(0) : __assert_fail ("Subtarget.hasAVX512() && !Subtarget.hasDQI() && \"Expected AVX512F without AVX512DQI\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 21061, __PRETTY_FUNCTION__))
;
21062
21063 StoredVal = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, MVT::v16i1,
21064 DAG.getUNDEF(MVT::v16i1), StoredVal,
21065 DAG.getIntPtrConstant(0, dl));
21066 StoredVal = DAG.getBitcast(MVT::i16, StoredVal);
21067 StoredVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, StoredVal);
21068
21069 return DAG.getStore(St->getChain(), dl, StoredVal, St->getBasePtr(),
21070 St->getPointerInfo(), St->getAlignment(),
21071 St->getMemOperand()->getFlags());
21072 }
21073
21074 if (St->isTruncatingStore())
21075 return SDValue();
21076
21077 // If this is a 256-bit store of concatenated ops, we are better off splitting
21078 // that store into two 128-bit stores. This avoids spurious use of 256-bit ops
21079 // and each half can execute independently. Some cores would split the op into
21080 // halves anyway, so the concat (vinsertf128) is purely an extra op.
21081 MVT StoreVT = StoredVal.getSimpleValueType();
21082 if (StoreVT.is256BitVector()) {
21083 if (StoredVal.getOpcode() != ISD::CONCAT_VECTORS || !StoredVal.hasOneUse())
21084 return SDValue();
21085 return split256BitStore(St, DAG);
21086 }
21087
21088 assert(StoreVT.isVector() && StoreVT.getSizeInBits() == 64 &&((StoreVT.isVector() && StoreVT.getSizeInBits() == 64
&& "Unexpected VT") ? static_cast<void> (0) : __assert_fail
("StoreVT.isVector() && StoreVT.getSizeInBits() == 64 && \"Unexpected VT\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 21089, __PRETTY_FUNCTION__))
21089 "Unexpected VT")((StoreVT.isVector() && StoreVT.getSizeInBits() == 64
&& "Unexpected VT") ? static_cast<void> (0) : __assert_fail
("StoreVT.isVector() && StoreVT.getSizeInBits() == 64 && \"Unexpected VT\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 21089, __PRETTY_FUNCTION__))
;
21090 if (DAG.getTargetLoweringInfo().getTypeAction(*DAG.getContext(), StoreVT) !=
21091 TargetLowering::TypeWidenVector)
21092 return SDValue();
21093
21094 // Widen the vector, cast to a v2x64 type, extract the single 64-bit element
21095 // and store it.
21096 MVT WideVT = MVT::getVectorVT(StoreVT.getVectorElementType(),
21097 StoreVT.getVectorNumElements() * 2);
21098 StoredVal = DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, StoredVal,
21099 DAG.getUNDEF(StoreVT));
21100 MVT StVT = Subtarget.is64Bit() && StoreVT.isInteger() ? MVT::i64 : MVT::f64;
21101 MVT CastVT = MVT::getVectorVT(StVT, 2);
21102 StoredVal = DAG.getBitcast(CastVT, StoredVal);
21103 StoredVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, StVT, StoredVal,
21104 DAG.getIntPtrConstant(0, dl));
21105
21106 return DAG.getStore(St->getChain(), dl, StoredVal, St->getBasePtr(),
21107 St->getPointerInfo(), St->getAlignment(),
21108 St->getMemOperand()->getFlags());
21109}
21110
21111// Lower vector extended loads using a shuffle. If SSSE3 is not available we
21112// may emit an illegal shuffle but the expansion is still better than scalar
21113// code. We generate sext/sext_invec for SEXTLOADs if it's available, otherwise
21114// we'll emit a shuffle and a arithmetic shift.
21115// FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
21116// TODO: It is possible to support ZExt by zeroing the undef values during
21117// the shuffle phase or after the shuffle.
21118static SDValue LowerLoad(SDValue Op, const X86Subtarget &Subtarget,
21119 SelectionDAG &DAG) {
21120 MVT RegVT = Op.getSimpleValueType();
21121 assert(RegVT.isVector() && "We only custom lower vector loads.")((RegVT.isVector() && "We only custom lower vector loads."
) ? static_cast<void> (0) : __assert_fail ("RegVT.isVector() && \"We only custom lower vector loads.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 21121, __PRETTY_FUNCTION__))
;
21122 assert(RegVT.isInteger() &&((RegVT.isInteger() && "We only custom lower integer vector loads."
) ? static_cast<void> (0) : __assert_fail ("RegVT.isInteger() && \"We only custom lower integer vector loads.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 21123, __PRETTY_FUNCTION__))
21123 "We only custom lower integer vector loads.")((RegVT.isInteger() && "We only custom lower integer vector loads."
) ? static_cast<void> (0) : __assert_fail ("RegVT.isInteger() && \"We only custom lower integer vector loads.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 21123, __PRETTY_FUNCTION__))
;
21124
21125 LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
21126 SDLoc dl(Ld);
21127 EVT MemVT = Ld->getMemoryVT();
21128
21129 // Without AVX512DQ, we need to use a scalar type for v2i1/v4i1/v8i1 loads.
21130 if (RegVT.getVectorElementType() == MVT::i1) {
21131 assert(EVT(RegVT) == MemVT && "Expected non-extending load")((EVT(RegVT) == MemVT && "Expected non-extending load"
) ? static_cast<void> (0) : __assert_fail ("EVT(RegVT) == MemVT && \"Expected non-extending load\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 21131, __PRETTY_FUNCTION__))
;
21132 assert(RegVT.getVectorNumElements() <= 8 && "Unexpected VT")((RegVT.getVectorNumElements() <= 8 && "Unexpected VT"
) ? static_cast<void> (0) : __assert_fail ("RegVT.getVectorNumElements() <= 8 && \"Unexpected VT\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 21132, __PRETTY_FUNCTION__))
;
21133 assert(Subtarget.hasAVX512() && !Subtarget.hasDQI() &&((Subtarget.hasAVX512() && !Subtarget.hasDQI() &&
"Expected AVX512F without AVX512DQI") ? static_cast<void>
(0) : __assert_fail ("Subtarget.hasAVX512() && !Subtarget.hasDQI() && \"Expected AVX512F without AVX512DQI\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 21134, __PRETTY_FUNCTION__))
21134 "Expected AVX512F without AVX512DQI")((Subtarget.hasAVX512() && !Subtarget.hasDQI() &&
"Expected AVX512F without AVX512DQI") ? static_cast<void>
(0) : __assert_fail ("Subtarget.hasAVX512() && !Subtarget.hasDQI() && \"Expected AVX512F without AVX512DQI\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 21134, __PRETTY_FUNCTION__))
;
21135
21136 SDValue NewLd = DAG.getLoad(MVT::i8, dl, Ld->getChain(), Ld->getBasePtr(),
21137 Ld->getPointerInfo(), Ld->getAlignment(),
21138 Ld->getMemOperand()->getFlags());
21139
21140 // Replace chain users with the new chain.
21141 assert(NewLd->getNumValues() == 2 && "Loads must carry a chain!")((NewLd->getNumValues() == 2 && "Loads must carry a chain!"
) ? static_cast<void> (0) : __assert_fail ("NewLd->getNumValues() == 2 && \"Loads must carry a chain!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 21141, __PRETTY_FUNCTION__))
;
21142
21143 SDValue Val = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i16, NewLd);
21144 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, RegVT,
21145 DAG.getBitcast(MVT::v16i1, Val),
21146 DAG.getIntPtrConstant(0, dl));
21147 return DAG.getMergeValues({Val, NewLd.getValue(1)}, dl);
21148 }
21149
21150 // Nothing useful we can do without SSE2 shuffles.
21151 assert(Subtarget.hasSSE2() && "We only custom lower sext loads with SSE2.")((Subtarget.hasSSE2() && "We only custom lower sext loads with SSE2."
) ? static_cast<void> (0) : __assert_fail ("Subtarget.hasSSE2() && \"We only custom lower sext loads with SSE2.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 21151, __PRETTY_FUNCTION__))
;
21152
21153 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21154 unsigned RegSz = RegVT.getSizeInBits();
21155
21156 ISD::LoadExtType Ext = Ld->getExtensionType();
21157
21158 assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)(((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD) && "Only anyext and sext are currently implemented."
) ? static_cast<void> (0) : __assert_fail ("(Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD) && \"Only anyext and sext are currently implemented.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 21159, __PRETTY_FUNCTION__))
21159 && "Only anyext and sext are currently implemented.")(((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD) && "Only anyext and sext are currently implemented."
) ? static_cast<void> (0) : __assert_fail ("(Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD) && \"Only anyext and sext are currently implemented.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 21159, __PRETTY_FUNCTION__))
;
21160 assert(MemVT != RegVT && "Cannot extend to the same type")((MemVT != RegVT && "Cannot extend to the same type")
? static_cast<void> (0) : __assert_fail ("MemVT != RegVT && \"Cannot extend to the same type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 21160, __PRETTY_FUNCTION__))
;
21161 assert(MemVT.isVector() && "Must load a vector from memory")((MemVT.isVector() && "Must load a vector from memory"
) ? static_cast<void> (0) : __assert_fail ("MemVT.isVector() && \"Must load a vector from memory\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 21161, __PRETTY_FUNCTION__))
;
21162
21163 unsigned NumElems = RegVT.getVectorNumElements();
21164 unsigned MemSz = MemVT.getSizeInBits();
21165 assert(RegSz > MemSz && "Register size must be greater than the mem size")((RegSz > MemSz && "Register size must be greater than the mem size"
) ? static_cast<void> (0) : __assert_fail ("RegSz > MemSz && \"Register size must be greater than the mem size\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 21165, __PRETTY_FUNCTION__))
;
21166
21167 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget.hasInt256()) {
21168 // The only way in which we have a legal 256-bit vector result but not the
21169 // integer 256-bit operations needed to directly lower a sextload is if we
21170 // have AVX1 but not AVX2. In that case, we can always emit a sextload to
21171 // a 128-bit vector and a normal sign_extend to 256-bits that should get
21172 // correctly legalized. We do this late to allow the canonical form of
21173 // sextload to persist throughout the rest of the DAG combiner -- it wants
21174 // to fold together any extensions it can, and so will fuse a sign_extend
21175 // of an sextload into a sextload targeting a wider value.
21176 SDValue Load;
21177 if (MemSz == 128) {
21178 // Just switch this to a normal load.
21179 assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "((TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
"it must be a legal 128-bit vector " "type!") ? static_cast<
void> (0) : __assert_fail ("TLI.isTypeLegal(MemVT) && \"If the memory type is a 128-bit type, \" \"it must be a legal 128-bit vector \" \"type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 21181, __PRETTY_FUNCTION__))
21180 "it must be a legal 128-bit vector "((TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
"it must be a legal 128-bit vector " "type!") ? static_cast<
void> (0) : __assert_fail ("TLI.isTypeLegal(MemVT) && \"If the memory type is a 128-bit type, \" \"it must be a legal 128-bit vector \" \"type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 21181, __PRETTY_FUNCTION__))
21181 "type!")((TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
"it must be a legal 128-bit vector " "type!") ? static_cast<
void> (0) : __assert_fail ("TLI.isTypeLegal(MemVT) && \"If the memory type is a 128-bit type, \" \"it must be a legal 128-bit vector \" \"type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 21181, __PRETTY_FUNCTION__))
;
21182 Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
21183 Ld->getPointerInfo(), Ld->getAlignment(),
21184 Ld->getMemOperand()->getFlags());
21185 } else {
21186 assert(MemSz < 128 &&((MemSz < 128 && "Can't extend a type wider than 128 bits to a 256 bit vector!"
) ? static_cast<void> (0) : __assert_fail ("MemSz < 128 && \"Can't extend a type wider than 128 bits to a 256 bit vector!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 21187, __PRETTY_FUNCTION__))
21187 "Can't extend a type wider than 128 bits to a 256 bit vector!")((MemSz < 128 && "Can't extend a type wider than 128 bits to a 256 bit vector!"
) ? static_cast<void> (0) : __assert_fail ("MemSz < 128 && \"Can't extend a type wider than 128 bits to a 256 bit vector!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 21187, __PRETTY_FUNCTION__))
;
21188 // Do an sext load to a 128-bit vector type. We want to use the same
21189 // number of elements, but elements half as wide. This will end up being
21190 // recursively lowered by this routine, but will succeed as we definitely
21191 // have all the necessary features if we're using AVX1.
21192 EVT HalfEltVT =
21193 EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
21194 EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
21195 Load =
21196 DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
21197 Ld->getPointerInfo(), MemVT, Ld->getAlignment(),
21198 Ld->getMemOperand()->getFlags());
21199 }
21200
21201 // Replace chain users with the new chain.
21202 assert(Load->getNumValues() == 2 && "Loads must carry a chain!")((Load->getNumValues() == 2 && "Loads must carry a chain!"
) ? static_cast<void> (0) : __assert_fail ("Load->getNumValues() == 2 && \"Loads must carry a chain!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 21202, __PRETTY_FUNCTION__))
;
21203
21204 // Finally, do a normal sign-extend to the desired register.
21205 SDValue SExt = DAG.getSExtOrTrunc(Load, dl, RegVT);
21206 return DAG.getMergeValues({SExt, Load.getValue(1)}, dl);
21207 }
21208
21209 // All sizes must be a power of two.
21210 assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&((isPowerOf2_32(RegSz * MemSz * NumElems) && "Non-power-of-two elements are not custom lowered!"
) ? static_cast<void> (0) : __assert_fail ("isPowerOf2_32(RegSz * MemSz * NumElems) && \"Non-power-of-two elements are not custom lowered!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 21211, __PRETTY_FUNCTION__))
21211 "Non-power-of-two elements are not custom lowered!")((isPowerOf2_32(RegSz * MemSz * NumElems) && "Non-power-of-two elements are not custom lowered!"
) ? static_cast<void> (0) : __assert_fail ("isPowerOf2_32(RegSz * MemSz * NumElems) && \"Non-power-of-two elements are not custom lowered!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 21211, __PRETTY_FUNCTION__))
;
21212
21213 // Attempt to load the original value using scalar loads.
21214 // Find the largest scalar type that divides the total loaded size.
21215 MVT SclrLoadTy = MVT::i8;
21216 for (MVT Tp : MVT::integer_valuetypes()) {
21217 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
21218 SclrLoadTy = Tp;
21219 }
21220 }
21221
21222 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
21223 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
21224 (64 <= MemSz))
21225 SclrLoadTy = MVT::f64;
21226
21227 // Calculate the number of scalar loads that we need to perform
21228 // in order to load our vector from memory.
21229 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
21230
21231 assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&(((Ext != ISD::SEXTLOAD || NumLoads == 1) && "Can only lower sext loads with a single scalar load!"
) ? static_cast<void> (0) : __assert_fail ("(Ext != ISD::SEXTLOAD || NumLoads == 1) && \"Can only lower sext loads with a single scalar load!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 21232, __PRETTY_FUNCTION__))
21232 "Can only lower sext loads with a single scalar load!")(((Ext != ISD::SEXTLOAD || NumLoads == 1) && "Can only lower sext loads with a single scalar load!"
) ? static_cast<void> (0) : __assert_fail ("(Ext != ISD::SEXTLOAD || NumLoads == 1) && \"Can only lower sext loads with a single scalar load!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 21232, __PRETTY_FUNCTION__))
;
21233
21234 unsigned loadRegSize = RegSz;
21235 if (Ext == ISD::SEXTLOAD && RegSz >= 256)
21236 loadRegSize = 128;
21237
21238 // If we don't have BWI we won't be able to create the shuffle needed for
21239 // v8i8->v8i64.
21240 if (Ext == ISD::EXTLOAD && !Subtarget.hasBWI() && RegVT == MVT::v8i64 &&
21241 MemVT == MVT::v8i8)
21242 loadRegSize = 128;
21243
21244 // Represent our vector as a sequence of elements which are the
21245 // largest scalar that we can load.
21246 EVT LoadUnitVecVT = EVT::getVectorVT(
21247 *DAG.getContext(), SclrLoadTy, loadRegSize / SclrLoadTy.getSizeInBits());
21248
21249 // Represent the data using the same element type that is stored in
21250 // memory. In practice, we ''widen'' MemVT.
21251 EVT WideVecVT =
21252 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
21253 loadRegSize / MemVT.getScalarSizeInBits());
21254
21255 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&((WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
"Invalid vector type") ? static_cast<void> (0) : __assert_fail
("WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() && \"Invalid vector type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 21256, __PRETTY_FUNCTION__))
21256 "Invalid vector type")((WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
"Invalid vector type") ? static_cast<void> (0) : __assert_fail
("WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() && \"Invalid vector type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 21256, __PRETTY_FUNCTION__))
;
21257
21258 // We can't shuffle using an illegal type.
21259 assert(TLI.isTypeLegal(WideVecVT) &&((TLI.isTypeLegal(WideVecVT) && "We only lower types that form legal widened vector types"
) ? static_cast<void> (0) : __assert_fail ("TLI.isTypeLegal(WideVecVT) && \"We only lower types that form legal widened vector types\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 21260, __PRETTY_FUNCTION__))
21260 "We only lower types that form legal widened vector types")((TLI.isTypeLegal(WideVecVT) && "We only lower types that form legal widened vector types"
) ? static_cast<void> (0) : __assert_fail ("TLI.isTypeLegal(WideVecVT) && \"We only lower types that form legal widened vector types\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 21260, __PRETTY_FUNCTION__))
;
21261
21262 SmallVector<SDValue, 8> Chains;
21263 SDValue Ptr = Ld->getBasePtr();
21264 unsigned OffsetInc = SclrLoadTy.getSizeInBits() / 8;
21265 SDValue Increment = DAG.getConstant(OffsetInc, dl,
21266 TLI.getPointerTy(DAG.getDataLayout()));
21267 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
21268
21269 unsigned Offset = 0;
21270 for (unsigned i = 0; i < NumLoads; ++i) {
21271 unsigned NewAlign = MinAlign(Ld->getAlignment(), Offset);
21272
21273 // Perform a single load.
21274 SDValue ScalarLoad =
21275 DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr,
21276 Ld->getPointerInfo().getWithOffset(Offset),
21277 NewAlign, Ld->getMemOperand()->getFlags());
21278 Chains.push_back(ScalarLoad.getValue(1));
21279 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
21280 // another round of DAGCombining.
21281 if (i == 0)
21282 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
21283 else
21284 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
21285 ScalarLoad, DAG.getIntPtrConstant(i, dl));
21286
21287 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21288 Offset += OffsetInc;
21289 }
21290
21291 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
21292
21293 // Bitcast the loaded value to a vector of the original element type, in
21294 // the size of the target vector type.
21295 SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
21296 unsigned SizeRatio = RegSz / MemSz;
21297
21298 if (Ext == ISD::SEXTLOAD) {
21299 SDValue Sext = getExtendInVec(/*Signed*/true, dl, RegVT, SlicedVec, DAG);
21300 return DAG.getMergeValues({Sext, TF}, dl);
21301 }
21302
21303 if (Ext == ISD::EXTLOAD && !Subtarget.hasBWI() && RegVT == MVT::v8i64 &&
21304 MemVT == MVT::v8i8) {
21305 SDValue Sext = getExtendInVec(/*Signed*/false, dl, RegVT, SlicedVec, DAG);
21306 return DAG.getMergeValues({Sext, TF}, dl);
21307 }
21308
21309 // Redistribute the loaded elements into the different locations.
21310 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
21311 for (unsigned i = 0; i != NumElems; ++i)
21312 ShuffleVec[i * SizeRatio] = i;
21313
21314 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
21315 DAG.getUNDEF(WideVecVT), ShuffleVec);
21316
21317 // Bitcast to the requested type.
21318 Shuff = DAG.getBitcast(RegVT, Shuff);
21319 return DAG.getMergeValues({Shuff, TF}, dl);
21320}
21321
21322/// Return true if node is an ISD::AND or ISD::OR of two X86ISD::SETCC nodes
21323/// each of which has no other use apart from the AND / OR.
21324static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
21325 Opc = Op.getOpcode();
21326 if (Opc != ISD::OR && Opc != ISD::AND)
21327 return false;
21328 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
21329 Op.getOperand(0).hasOneUse() &&
21330 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
21331 Op.getOperand(1).hasOneUse());
21332}
21333
21334/// Return true if node is an ISD::XOR of a X86ISD::SETCC and 1 and that the
21335/// SETCC node has a single use.
21336static bool isXor1OfSetCC(SDValue Op) {
21337 if (Op.getOpcode() != ISD::XOR)
21338 return false;
21339 if (isOneConstant(Op.getOperand(1)))
21340 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
21341 Op.getOperand(0).hasOneUse();
21342 return false;
21343}
21344
21345SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
21346 bool addTest = true;
21347 SDValue Chain = Op.getOperand(0);
21348 SDValue Cond = Op.getOperand(1);
21349 SDValue Dest = Op.getOperand(2);
21350 SDLoc dl(Op);
21351 SDValue CC;
21352 bool Inverted = false;
21353
21354 if (Cond.getOpcode() == ISD::SETCC) {
21355 // Check for setcc([su]{add,sub,mul}o == 0).
21356 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
21357 isNullConstant(Cond.getOperand(1)) &&
21358 Cond.getOperand(0).getResNo() == 1 &&
21359 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
21360 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
21361 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
21362 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
21363 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
21364 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
21365 Inverted = true;
21366 Cond = Cond.getOperand(0);
21367 } else {
21368 if (SDValue NewCond = LowerSETCC(Cond, DAG))
21369 Cond = NewCond;
21370 }
21371 }
21372#if 0
21373 // FIXME: LowerXALUO doesn't handle these!!
21374 else if (Cond.getOpcode() == X86ISD::ADD ||
21375 Cond.getOpcode() == X86ISD::SUB ||
21376 Cond.getOpcode() == X86ISD::SMUL ||
21377 Cond.getOpcode() == X86ISD::UMUL)
21378 Cond = LowerXALUO(Cond, DAG);
21379#endif
21380
21381 // Look pass (and (setcc_carry (cmp ...)), 1).
21382 if (Cond.getOpcode() == ISD::AND &&
21383 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY &&
21384 isOneConstant(Cond.getOperand(1)))
21385 Cond = Cond.getOperand(0);
21386
21387 // If condition flag is set by a X86ISD::CMP, then use it as the condition
21388 // setting operand in place of the X86ISD::SETCC.
21389 unsigned CondOpcode = Cond.getOpcode();
21390 if (CondOpcode == X86ISD::SETCC ||
21391 CondOpcode == X86ISD::SETCC_CARRY) {
21392 CC = Cond.getOperand(0);
21393
21394 SDValue Cmp = Cond.getOperand(1);
21395 unsigned Opc = Cmp.getOpcode();
21396 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
21397 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
21398 Cond = Cmp;
21399 addTest = false;
21400 } else {
21401 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
21402 default: break;
21403 case X86::COND_O:
21404 case X86::COND_B:
21405 // These can only come from an arithmetic instruction with overflow,
21406 // e.g. SADDO, UADDO.
21407 Cond = Cond.getOperand(1);
21408 addTest = false;
21409 break;
21410 }
21411 }
21412 }
21413 CondOpcode = Cond.getOpcode();
21414 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
21415 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
21416 CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) {
21417 SDValue Value;
21418 X86::CondCode X86Cond;
21419 std::tie(Value, Cond) = getX86XALUOOp(X86Cond, Cond.getValue(0), DAG);
21420
21421 if (Inverted)
21422 X86Cond = X86::GetOppositeBranchCondition(X86Cond);
21423
21424 CC = DAG.getConstant(X86Cond, dl, MVT::i8);
21425 addTest = false;
21426 } else {
21427 unsigned CondOpc;
21428 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
21429 SDValue Cmp = Cond.getOperand(0).getOperand(1);
21430 if (CondOpc == ISD::OR) {
21431 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
21432 // two branches instead of an explicit OR instruction with a
21433 // separate test.
21434 if (Cmp == Cond.getOperand(1).getOperand(1) &&
21435 isX86LogicalCmp(Cmp)) {
21436 CC = Cond.getOperand(0).getOperand(0);
21437 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
21438 Chain, Dest, CC, Cmp);
21439 CC = Cond.getOperand(1).getOperand(0);
21440 Cond = Cmp;
21441 addTest = false;
21442 }
21443 } else { // ISD::AND
21444 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
21445 // two branches instead of an explicit AND instruction with a
21446 // separate test. However, we only do this if this block doesn't
21447 // have a fall-through edge, because this requires an explicit
21448 // jmp when the condition is false.
21449 if (Cmp == Cond.getOperand(1).getOperand(1) &&
21450 isX86LogicalCmp(Cmp) &&
21451 Op.getNode()->hasOneUse()) {
21452 X86::CondCode CCode =
21453 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
21454 CCode = X86::GetOppositeBranchCondition(CCode);
21455 CC = DAG.getConstant(CCode, dl, MVT::i8);
21456 SDNode *User = *Op.getNode()->use_begin();
21457 // Look for an unconditional branch following this conditional branch.
21458 // We need this because we need to reverse the successors in order
21459 // to implement FCMP_OEQ.
21460 if (User->getOpcode() == ISD::BR) {
21461 SDValue FalseBB = User->getOperand(1);
21462 SDNode *NewBR =
21463 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
21464 assert(NewBR == User)((NewBR == User) ? static_cast<void> (0) : __assert_fail
("NewBR == User", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 21464, __PRETTY_FUNCTION__))
;
21465 (void)NewBR;
21466 Dest = FalseBB;
21467
21468 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
21469 Chain, Dest, CC, Cmp);
21470 X86::CondCode CCode =
21471 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
21472 CCode = X86::GetOppositeBranchCondition(CCode);
21473 CC = DAG.getConstant(CCode, dl, MVT::i8);
21474 Cond = Cmp;
21475 addTest = false;
21476 }
21477 }
21478 }
21479 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
21480 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
21481 // It should be transformed during dag combiner except when the condition
21482 // is set by a arithmetics with overflow node.
21483 X86::CondCode CCode =
21484 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
21485 CCode = X86::GetOppositeBranchCondition(CCode);
21486 CC = DAG.getConstant(CCode, dl, MVT::i8);
21487 Cond = Cond.getOperand(0).getOperand(1);
21488 addTest = false;
21489 } else if (Cond.getOpcode() == ISD::SETCC &&
21490 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
21491 // For FCMP_OEQ, we can emit
21492 // two branches instead of an explicit AND instruction with a
21493 // separate test. However, we only do this if this block doesn't
21494 // have a fall-through edge, because this requires an explicit
21495 // jmp when the condition is false.
21496 if (Op.getNode()->hasOneUse()) {
21497 SDNode *User = *Op.getNode()->use_begin();
21498 // Look for an unconditional branch following this conditional branch.
21499 // We need this because we need to reverse the successors in order
21500 // to implement FCMP_OEQ.
21501 if (User->getOpcode() == ISD::BR) {
21502 SDValue FalseBB = User->getOperand(1);
21503 SDNode *NewBR =
21504 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
21505 assert(NewBR == User)((NewBR == User) ? static_cast<void> (0) : __assert_fail
("NewBR == User", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 21505, __PRETTY_FUNCTION__))
;
21506 (void)NewBR;
21507 Dest = FalseBB;
21508
21509 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
21510 Cond.getOperand(0), Cond.getOperand(1));
21511 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
21512 CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
21513 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
21514 Chain, Dest, CC, Cmp);
21515 CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
21516 Cond = Cmp;
21517 addTest = false;
21518 }
21519 }
21520 } else if (Cond.getOpcode() == ISD::SETCC &&
21521 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
21522 // For FCMP_UNE, we can emit
21523 // two branches instead of an explicit OR instruction with a
21524 // separate test.
21525 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
21526 Cond.getOperand(0), Cond.getOperand(1));
21527 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
21528 CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
21529 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
21530 Chain, Dest, CC, Cmp);
21531 CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
21532 Cond = Cmp;
21533 addTest = false;
21534 }
21535 }
21536
21537 if (addTest) {
21538 // Look pass the truncate if the high bits are known zero.
21539 if (isTruncWithZeroHighBitsInput(Cond, DAG))
21540 Cond = Cond.getOperand(0);
21541
21542 // We know the result of AND is compared against zero. Try to match
21543 // it to BT.
21544 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
21545 SDValue BTCC;
21546 if (SDValue BT = LowerAndToBT(Cond, ISD::SETNE, dl, DAG, BTCC)) {
21547 CC = BTCC;
21548 Cond = BT;
21549 addTest = false;
21550 }
21551 }
21552 }
21553
21554 if (addTest) {
21555 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
21556 CC = DAG.getConstant(X86Cond, dl, MVT::i8);
21557 Cond = EmitCmp(Cond, DAG.getConstant(0, dl, Cond.getValueType()),
21558 X86Cond, dl, DAG);
21559 }
21560 Cond = ConvertCmpIfNecessary(Cond, DAG);
21561 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
21562 Chain, Dest, CC, Cond);
21563}
21564
21565// Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
21566// Calls to _alloca are needed to probe the stack when allocating more than 4k
21567// bytes in one go. Touching the stack at 4K increments is necessary to ensure
21568// that the guard pages used by the OS virtual memory manager are allocated in
21569// correct sequence.
21570SDValue
21571X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
21572 SelectionDAG &DAG) const {
21573 MachineFunction &MF = DAG.getMachineFunction();
21574 bool SplitStack = MF.shouldSplitStack();
21575 bool EmitStackProbe = !getStackProbeSymbolName(MF).empty();
21576 bool Lower = (Subtarget.isOSWindows() && !Subtarget.isTargetMachO()) ||
21577 SplitStack || EmitStackProbe;
21578 SDLoc dl(Op);
21579
21580 // Get the inputs.
21581 SDNode *Node = Op.getNode();
21582 SDValue Chain = Op.getOperand(0);
21583 SDValue Size = Op.getOperand(1);
21584 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
21585 EVT VT = Node->getValueType(0);
21586
21587 // Chain the dynamic stack allocation so that it doesn't modify the stack
21588 // pointer when other instructions are using the stack.
21589 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
21590
21591 bool Is64Bit = Subtarget.is64Bit();
21592 MVT SPTy = getPointerTy(DAG.getDataLayout());
21593
21594 SDValue Result;
21595 if (!Lower) {
21596 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21597 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
21598 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"((SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
" not tell us which reg is the stack pointer!") ? static_cast
<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 21599, __PRETTY_FUNCTION__))
21599 " not tell us which reg is the stack pointer!")((SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
" not tell us which reg is the stack pointer!") ? static_cast
<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 21599, __PRETTY_FUNCTION__))
;
21600
21601 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
21602 Chain = SP.getValue(1);
21603 const TargetFrameLowering &TFI = *Subtarget.getFrameLowering();
21604 unsigned StackAlign = TFI.getStackAlignment();
21605 Result = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
21606 if (Align > StackAlign)
21607 Result = DAG.getNode(ISD::AND, dl, VT, Result,
21608 DAG.getConstant(-(uint64_t)Align, dl, VT));
21609 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Result); // Output chain
21610 } else if (SplitStack) {
21611 MachineRegisterInfo &MRI = MF.getRegInfo();
21612
21613 if (Is64Bit) {
21614 // The 64 bit implementation of segmented stacks needs to clobber both r10
21615 // r11. This makes it impossible to use it along with nested parameters.
21616 const Function &F = MF.getFunction();
21617 for (const auto &A : F.args()) {
21618 if (A.hasNestAttr())
21619 report_fatal_error("Cannot use segmented stacks with functions that "
21620 "have nested arguments.");
21621 }
21622 }
21623
21624 const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
21625 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
21626 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
21627 Result = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
21628 DAG.getRegister(Vreg, SPTy));
21629 } else {
21630 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
21631 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Size);
21632 MF.getInfo<X86MachineFunctionInfo>()->setHasWinAlloca(true);
21633
21634 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
21635 unsigned SPReg = RegInfo->getStackRegister();
21636 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
21637 Chain = SP.getValue(1);
21638
21639 if (Align) {
21640 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
21641 DAG.getConstant(-(uint64_t)Align, dl, VT));
21642 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
21643 }
21644
21645 Result = SP;
21646 }
21647
21648 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
21649 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
21650
21651 SDValue Ops[2] = {Result, Chain};
21652 return DAG.getMergeValues(Ops, dl);
21653}
21654
21655SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
21656 MachineFunction &MF = DAG.getMachineFunction();
21657 auto PtrVT = getPointerTy(MF.getDataLayout());
21658 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
21659
21660 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
21661 SDLoc DL(Op);
21662
21663 if (!Subtarget.is64Bit() ||
21664 Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv())) {
21665 // vastart just stores the address of the VarArgsFrameIndex slot into the
21666 // memory location argument.
21667 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
21668 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
21669 MachinePointerInfo(SV));
21670 }
21671
21672 // __va_list_tag:
21673 // gp_offset (0 - 6 * 8)
21674 // fp_offset (48 - 48 + 8 * 16)
21675 // overflow_arg_area (point to parameters coming in memory).
21676 // reg_save_area
21677 SmallVector<SDValue, 8> MemOps;
21678 SDValue FIN = Op.getOperand(1);
21679 // Store gp_offset
21680 SDValue Store = DAG.getStore(
21681 Op.getOperand(0), DL,
21682 DAG.getConstant(FuncInfo->getVarArgsGPOffset(), DL, MVT::i32), FIN,
21683 MachinePointerInfo(SV));
21684 MemOps.push_back(Store);
21685
21686 // Store fp_offset
21687 FIN = DAG.getMemBasePlusOffset(FIN, 4, DL);
21688 Store = DAG.getStore(
21689 Op.getOperand(0), DL,
21690 DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL, MVT::i32), FIN,
21691 MachinePointerInfo(SV, 4));
21692 MemOps.push_back(Store);
21693
21694 // Store ptr to overflow_arg_area
21695 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
21696 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
21697 Store =
21698 DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN, MachinePointerInfo(SV, 8));
21699 MemOps.push_back(Store);
21700
21701 // Store ptr to reg_save_area.
21702 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(
21703 Subtarget.isTarget64BitLP64() ? 8 : 4, DL));
21704 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
21705 Store = DAG.getStore(
21706 Op.getOperand(0), DL, RSFIN, FIN,
21707 MachinePointerInfo(SV, Subtarget.isTarget64BitLP64() ? 16 : 12));
21708 MemOps.push_back(Store);
21709 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
21710}
21711
21712SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
21713 assert(Subtarget.is64Bit() &&((Subtarget.is64Bit() && "LowerVAARG only handles 64-bit va_arg!"
) ? static_cast<void> (0) : __assert_fail ("Subtarget.is64Bit() && \"LowerVAARG only handles 64-bit va_arg!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 21714, __PRETTY_FUNCTION__))
21714 "LowerVAARG only handles 64-bit va_arg!")((Subtarget.is64Bit() && "LowerVAARG only handles 64-bit va_arg!"
) ? static_cast<void> (0) : __assert_fail ("Subtarget.is64Bit() && \"LowerVAARG only handles 64-bit va_arg!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 21714, __PRETTY_FUNCTION__))
;
21715 assert(Op.getNumOperands() == 4)((Op.getNumOperands() == 4) ? static_cast<void> (0) : __assert_fail
("Op.getNumOperands() == 4", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 21715, __PRETTY_FUNCTION__))
;
21716
21717 MachineFunction &MF = DAG.getMachineFunction();
21718 if (Subtarget.isCallingConvWin64(MF.getFunction().getCallingConv()))
21719 // The Win64 ABI uses char* instead of a structure.
21720 return DAG.expandVAArg(Op.getNode());
21721
21722 SDValue Chain = Op.getOperand(0);
21723 SDValue SrcPtr = Op.getOperand(1);
21724 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
21725 unsigned Align = Op.getConstantOperandVal(3);
21726 SDLoc dl(Op);
21727
21728 EVT ArgVT = Op.getNode()->getValueType(0);
21729 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
21730 uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
21731 uint8_t ArgMode;
21732
21733 // Decide which area this value should be read from.
21734 // TODO: Implement the AMD64 ABI in its entirety. This simple
21735 // selection mechanism works only for the basic types.
21736 if (ArgVT == MVT::f80) {
21737 llvm_unreachable("va_arg for f80 not yet implemented")::llvm::llvm_unreachable_internal("va_arg for f80 not yet implemented"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 21737)
;
21738 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
21739 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
21740 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
21741 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
21742 } else {
21743 llvm_unreachable("Unhandled argument type in LowerVAARG")::llvm::llvm_unreachable_internal("Unhandled argument type in LowerVAARG"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 21743)
;
21744 }
21745
21746 if (ArgMode == 2) {
21747 // Sanity Check: Make sure using fp_offset makes sense.
21748 assert(!Subtarget.useSoftFloat() &&((!Subtarget.useSoftFloat() && !(MF.getFunction().hasFnAttribute
(Attribute::NoImplicitFloat)) && Subtarget.hasSSE1())
? static_cast<void> (0) : __assert_fail ("!Subtarget.useSoftFloat() && !(MF.getFunction().hasFnAttribute(Attribute::NoImplicitFloat)) && Subtarget.hasSSE1()"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 21750, __PRETTY_FUNCTION__))
21749 !(MF.getFunction().hasFnAttribute(Attribute::NoImplicitFloat)) &&((!Subtarget.useSoftFloat() && !(MF.getFunction().hasFnAttribute
(Attribute::NoImplicitFloat)) && Subtarget.hasSSE1())
? static_cast<void> (0) : __assert_fail ("!Subtarget.useSoftFloat() && !(MF.getFunction().hasFnAttribute(Attribute::NoImplicitFloat)) && Subtarget.hasSSE1()"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 21750, __PRETTY_FUNCTION__))
21750 Subtarget.hasSSE1())((!Subtarget.useSoftFloat() && !(MF.getFunction().hasFnAttribute
(Attribute::NoImplicitFloat)) && Subtarget.hasSSE1())
? static_cast<void> (0) : __assert_fail ("!Subtarget.useSoftFloat() && !(MF.getFunction().hasFnAttribute(Attribute::NoImplicitFloat)) && Subtarget.hasSSE1()"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 21750, __PRETTY_FUNCTION__))
;
21751 }
21752
21753 // Insert VAARG_64 node into the DAG
21754 // VAARG_64 returns two values: Variable Argument Address, Chain
21755 SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
21756 DAG.getConstant(ArgMode, dl, MVT::i8),
21757 DAG.getConstant(Align, dl, MVT::i32)};
21758 SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
21759 SDValue VAARG = DAG.getMemIntrinsicNode(
21760 X86ISD::VAARG_64, dl,
21761 VTs, InstOps, MVT::i64,
21762 MachinePointerInfo(SV),
21763 /*Align=*/0,
21764 MachineMemOperand::MOLoad | MachineMemOperand::MOStore);
21765 Chain = VAARG.getValue(1);
21766
21767 // Load the next argument and return it
21768 return DAG.getLoad(ArgVT, dl, Chain, VAARG, MachinePointerInfo());
21769}
21770
21771static SDValue LowerVACOPY(SDValue Op, const X86Subtarget &Subtarget,
21772 SelectionDAG &DAG) {
21773 // X86-64 va_list is a struct { i32, i32, i8*, i8* }, except on Windows,
21774 // where a va_list is still an i8*.
21775 assert(Subtarget.is64Bit() && "This code only handles 64-bit va_copy!")((Subtarget.is64Bit() && "This code only handles 64-bit va_copy!"
) ? static_cast<void> (0) : __assert_fail ("Subtarget.is64Bit() && \"This code only handles 64-bit va_copy!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 21775, __PRETTY_FUNCTION__))
;
21776 if (Subtarget.isCallingConvWin64(
21777 DAG.getMachineFunction().getFunction().getCallingConv()))
21778 // Probably a Win64 va_copy.
21779 return DAG.expandVACopy(Op.getNode());
21780
21781 SDValue Chain = Op.getOperand(0);
21782 SDValue DstPtr = Op.getOperand(1);
21783 SDValue SrcPtr = Op.getOperand(2);
21784 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
21785 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
21786 SDLoc DL(Op);
21787
21788 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
21789 DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
21790 false, false,
21791 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
21792}
21793
21794// Helper to get immediate/variable SSE shift opcode from other shift opcodes.
21795static unsigned getTargetVShiftUniformOpcode(unsigned Opc, bool IsVariable) {
21796 switch (Opc) {
21797 case ISD::SHL:
21798 case X86ISD::VSHL:
21799 case X86ISD::VSHLI:
21800 return IsVariable ? X86ISD::VSHL : X86ISD::VSHLI;
21801 case ISD::SRL:
21802 case X86ISD::VSRL:
21803 case X86ISD::VSRLI:
21804 return IsVariable ? X86ISD::VSRL : X86ISD::VSRLI;
21805 case ISD::SRA:
21806 case X86ISD::VSRA:
21807 case X86ISD::VSRAI:
21808 return IsVariable ? X86ISD::VSRA : X86ISD::VSRAI;
21809 }
21810 llvm_unreachable("Unknown target vector shift node")::llvm::llvm_unreachable_internal("Unknown target vector shift node"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 21810)
;
21811}
21812
21813/// Handle vector element shifts where the shift amount is a constant.
21814/// Takes immediate version of shift as input.
21815static SDValue getTargetVShiftByConstNode(unsigned Opc, const SDLoc &dl, MVT VT,
21816 SDValue SrcOp, uint64_t ShiftAmt,
21817 SelectionDAG &DAG) {
21818 MVT ElementType = VT.getVectorElementType();
21819
21820 // Bitcast the source vector to the output type, this is mainly necessary for
21821 // vXi8/vXi64 shifts.
21822 if (VT != SrcOp.getSimpleValueType())
21823 SrcOp = DAG.getBitcast(VT, SrcOp);
21824
21825 // Fold this packed shift into its first operand if ShiftAmt is 0.
21826 if (ShiftAmt == 0)
21827 return SrcOp;
21828
21829 // Check for ShiftAmt >= element width
21830 if (ShiftAmt >= ElementType.getSizeInBits()) {
21831 if (Opc == X86ISD::VSRAI)
21832 ShiftAmt = ElementType.getSizeInBits() - 1;
21833 else
21834 return DAG.getConstant(0, dl, VT);
21835 }
21836
21837 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)(((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD
::VSRAI) && "Unknown target vector shift-by-constant node"
) ? static_cast<void> (0) : __assert_fail ("(Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI) && \"Unknown target vector shift-by-constant node\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 21838, __PRETTY_FUNCTION__))
21838 && "Unknown target vector shift-by-constant node")(((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD
::VSRAI) && "Unknown target vector shift-by-constant node"
) ? static_cast<void> (0) : __assert_fail ("(Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI) && \"Unknown target vector shift-by-constant node\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 21838, __PRETTY_FUNCTION__))
;
21839
21840 // Fold this packed vector shift into a build vector if SrcOp is a
21841 // vector of Constants or UNDEFs.
21842 if (ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
21843 SmallVector<SDValue, 8> Elts;
21844 unsigned NumElts = SrcOp->getNumOperands();
21845 ConstantSDNode *ND;
21846
21847 switch(Opc) {
21848 default: llvm_unreachable("Unknown opcode!")::llvm::llvm_unreachable_internal("Unknown opcode!", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 21848)
;
21849 case X86ISD::VSHLI:
21850 for (unsigned i=0; i!=NumElts; ++i) {
21851 SDValue CurrentOp = SrcOp->getOperand(i);
21852 if (CurrentOp->isUndef()) {
21853 Elts.push_back(CurrentOp);
21854 continue;
21855 }
21856 ND = cast<ConstantSDNode>(CurrentOp);
21857 const APInt &C = ND->getAPIntValue();
21858 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
21859 }
21860 break;
21861 case X86ISD::VSRLI:
21862 for (unsigned i=0; i!=NumElts; ++i) {
21863 SDValue CurrentOp = SrcOp->getOperand(i);
21864 if (CurrentOp->isUndef()) {
21865 Elts.push_back(CurrentOp);
21866 continue;
21867 }
21868 ND = cast<ConstantSDNode>(CurrentOp);
21869 const APInt &C = ND->getAPIntValue();
21870 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
21871 }
21872 break;
21873 case X86ISD::VSRAI:
21874 for (unsigned i=0; i!=NumElts; ++i) {
21875 SDValue CurrentOp = SrcOp->getOperand(i);
21876 if (CurrentOp->isUndef()) {
21877 Elts.push_back(CurrentOp);
21878 continue;
21879 }
21880 ND = cast<ConstantSDNode>(CurrentOp);
21881 const APInt &C = ND->getAPIntValue();
21882 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
21883 }
21884 break;
21885 }
21886
21887 return DAG.getBuildVector(VT, dl, Elts);
21888 }
21889
21890 return DAG.getNode(Opc, dl, VT, SrcOp,
21891 DAG.getConstant(ShiftAmt, dl, MVT::i8));
21892}
21893
21894/// Handle vector element shifts where the shift amount may or may not be a
21895/// constant. Takes immediate version of shift as input.
21896static SDValue getTargetVShiftNode(unsigned Opc, const SDLoc &dl, MVT VT,
21897 SDValue SrcOp, SDValue ShAmt,
21898 const X86Subtarget &Subtarget,
21899 SelectionDAG &DAG) {
21900 MVT SVT = ShAmt.getSimpleValueType();
21901 assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!")(((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!"
) ? static_cast<void> (0) : __assert_fail ("(SVT == MVT::i32 || SVT == MVT::i64) && \"Unexpected value type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 21901, __PRETTY_FUNCTION__))
;
21902
21903 // Catch shift-by-constant.
21904 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
21905 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
21906 CShAmt->getZExtValue(), DAG);
21907
21908 // Change opcode to non-immediate version.
21909 Opc = getTargetVShiftUniformOpcode(Opc, true);
21910
21911 // Need to build a vector containing shift amount.
21912 // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
21913 // +====================+============+=======================================+
21914 // | ShAmt is | HasSSE4.1? | Construct ShAmt vector as |
21915 // +====================+============+=======================================+
21916 // | i64 | Yes, No | Use ShAmt as lowest elt |
21917 // | i32 | Yes | zero-extend in-reg |
21918 // | (i32 zext(i16/i8)) | Yes | zero-extend in-reg |
21919 // | (i32 zext(i16/i8)) | No | byte-shift-in-reg |
21920 // | i16/i32 | No | v4i32 build_vector(ShAmt, 0, ud, ud)) |
21921 // +====================+============+=======================================+
21922
21923 if (SVT == MVT::i64)
21924 ShAmt = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(ShAmt), MVT::v2i64, ShAmt);
21925 else if (ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
21926 ShAmt.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
21927 (ShAmt.getOperand(0).getSimpleValueType() == MVT::i16 ||
21928 ShAmt.getOperand(0).getSimpleValueType() == MVT::i8)) {
21929 ShAmt = ShAmt.getOperand(0);
21930 MVT AmtTy = ShAmt.getSimpleValueType() == MVT::i8 ? MVT::v16i8 : MVT::v8i16;
21931 ShAmt = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(ShAmt), AmtTy, ShAmt);
21932 if (Subtarget.hasSSE41())
21933 ShAmt = DAG.getNode(ISD::ZERO_EXTEND_VECTOR_INREG, SDLoc(ShAmt),
21934 MVT::v2i64, ShAmt);
21935 else {
21936 SDValue ByteShift = DAG.getConstant(
21937 (128 - AmtTy.getScalarSizeInBits()) / 8, SDLoc(ShAmt), MVT::i8);
21938 ShAmt = DAG.getBitcast(MVT::v16i8, ShAmt);
21939 ShAmt = DAG.getNode(X86ISD::VSHLDQ, SDLoc(ShAmt), MVT::v16i8, ShAmt,
21940 ByteShift);
21941 ShAmt = DAG.getNode(X86ISD::VSRLDQ, SDLoc(ShAmt), MVT::v16i8, ShAmt,
21942 ByteShift);
21943 }
21944 } else if (Subtarget.hasSSE41() &&
21945 ShAmt.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
21946 ShAmt = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(ShAmt), MVT::v4i32, ShAmt);
21947 ShAmt = DAG.getNode(ISD::ZERO_EXTEND_VECTOR_INREG, SDLoc(ShAmt),
21948 MVT::v2i64, ShAmt);
21949 } else {
21950 SDValue ShOps[4] = {ShAmt, DAG.getConstant(0, dl, SVT), DAG.getUNDEF(SVT),
21951 DAG.getUNDEF(SVT)};
21952 ShAmt = DAG.getBuildVector(MVT::v4i32, dl, ShOps);
21953 }
21954
21955 // The return type has to be a 128-bit type with the same element
21956 // type as the input type.
21957 MVT EltVT = VT.getVectorElementType();
21958 MVT ShVT = MVT::getVectorVT(EltVT, 128 / EltVT.getSizeInBits());
21959
21960 ShAmt = DAG.getBitcast(ShVT, ShAmt);
21961 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
21962}
21963
21964/// Return Mask with the necessary casting or extending
21965/// for \p Mask according to \p MaskVT when lowering masking intrinsics
21966static SDValue getMaskNode(SDValue Mask, MVT MaskVT,
21967 const X86Subtarget &Subtarget, SelectionDAG &DAG,
21968 const SDLoc &dl) {
21969
21970 if (isAllOnesConstant(Mask))
21971 return DAG.getConstant(1, dl, MaskVT);
21972 if (X86::isZeroNode(Mask))
21973 return DAG.getConstant(0, dl, MaskVT);
21974
21975 assert(MaskVT.bitsLE(Mask.getSimpleValueType()) && "Unexpected mask size!")((MaskVT.bitsLE(Mask.getSimpleValueType()) && "Unexpected mask size!"
) ? static_cast<void> (0) : __assert_fail ("MaskVT.bitsLE(Mask.getSimpleValueType()) && \"Unexpected mask size!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 21975, __PRETTY_FUNCTION__))
;
21976
21977 if (Mask.getSimpleValueType() == MVT::i64 && Subtarget.is32Bit()) {
21978 assert(MaskVT == MVT::v64i1 && "Expected v64i1 mask!")((MaskVT == MVT::v64i1 && "Expected v64i1 mask!") ? static_cast
<void> (0) : __assert_fail ("MaskVT == MVT::v64i1 && \"Expected v64i1 mask!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 21978, __PRETTY_FUNCTION__))
;
21979 assert(Subtarget.hasBWI() && "Expected AVX512BW target!")((Subtarget.hasBWI() && "Expected AVX512BW target!") ?
static_cast<void> (0) : __assert_fail ("Subtarget.hasBWI() && \"Expected AVX512BW target!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 21979, __PRETTY_FUNCTION__))
;
21980 // In case 32bit mode, bitcast i64 is illegal, extend/split it.
21981 SDValue Lo, Hi;
21982 Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Mask,
21983 DAG.getConstant(0, dl, MVT::i32));
21984 Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Mask,
21985 DAG.getConstant(1, dl, MVT::i32));
21986
21987 Lo = DAG.getBitcast(MVT::v32i1, Lo);
21988 Hi = DAG.getBitcast(MVT::v32i1, Hi);
21989
21990 return DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, Lo, Hi);
21991 } else {
21992 MVT BitcastVT = MVT::getVectorVT(MVT::i1,
21993 Mask.getSimpleValueType().getSizeInBits());
21994 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
21995 // are extracted by EXTRACT_SUBVECTOR.
21996 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
21997 DAG.getBitcast(BitcastVT, Mask),
21998 DAG.getIntPtrConstant(0, dl));
21999 }
22000}
22001
22002/// Return (and \p Op, \p Mask) for compare instructions or
22003/// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
22004/// necessary casting or extending for \p Mask when lowering masking intrinsics
22005static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
22006 SDValue PreservedSrc,
22007 const X86Subtarget &Subtarget,
22008 SelectionDAG &DAG) {
22009 MVT VT = Op.getSimpleValueType();
22010 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
22011 unsigned OpcodeSelect = ISD::VSELECT;
22012 SDLoc dl(Op);
22013
22014 if (isAllOnesConstant(Mask))
22015 return Op;
22016
22017 SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
22018
22019 if (PreservedSrc.isUndef())
22020 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
22021 return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
22022}
22023
22024/// Creates an SDNode for a predicated scalar operation.
22025/// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
22026/// The mask is coming as MVT::i8 and it should be transformed
22027/// to MVT::v1i1 while lowering masking intrinsics.
22028/// The main difference between ScalarMaskingNode and VectorMaskingNode is using
22029/// "X86select" instead of "vselect". We just can't create the "vselect" node
22030/// for a scalar instruction.
22031static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
22032 SDValue PreservedSrc,
22033 const X86Subtarget &Subtarget,
22034 SelectionDAG &DAG) {
22035
22036 if (auto *MaskConst = dyn_cast<ConstantSDNode>(Mask))
22037 if (MaskConst->getZExtValue() & 0x1)
22038 return Op;
22039
22040 MVT VT = Op.getSimpleValueType();
22041 SDLoc dl(Op);
22042
22043 assert(Mask.getValueType() == MVT::i8 && "Unexpect type")((Mask.getValueType() == MVT::i8 && "Unexpect type") ?
static_cast<void> (0) : __assert_fail ("Mask.getValueType() == MVT::i8 && \"Unexpect type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 22043, __PRETTY_FUNCTION__))
;
22044 SDValue IMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v1i1,
22045 DAG.getBitcast(MVT::v8i1, Mask),
22046 DAG.getIntPtrConstant(0, dl));
22047 if (Op.getOpcode() == X86ISD::FSETCCM ||
22048 Op.getOpcode() == X86ISD::FSETCCM_SAE ||
22049 Op.getOpcode() == X86ISD::VFPCLASSS)
22050 return DAG.getNode(ISD::AND, dl, VT, Op, IMask);
22051
22052 if (PreservedSrc.isUndef())
22053 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
22054 return DAG.getNode(X86ISD::SELECTS, dl, VT, IMask, Op, PreservedSrc);
22055}
22056
22057static int getSEHRegistrationNodeSize(const Function *Fn) {
22058 if (!Fn->hasPersonalityFn())
22059 report_fatal_error(
22060 "querying registration node size for function without personality");
22061 // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
22062 // WinEHStatePass for the full struct definition.
22063 switch (classifyEHPersonality(Fn->getPersonalityFn())) {
22064 case EHPersonality::MSVC_X86SEH: return 24;
22065 case EHPersonality::MSVC_CXX: return 16;
22066 default: break;
22067 }
22068 report_fatal_error(
22069 "can only recover FP for 32-bit MSVC EH personality functions");
22070}
22071
22072/// When the MSVC runtime transfers control to us, either to an outlined
22073/// function or when returning to a parent frame after catching an exception, we
22074/// recover the parent frame pointer by doing arithmetic on the incoming EBP.
22075/// Here's the math:
22076/// RegNodeBase = EntryEBP - RegNodeSize
22077/// ParentFP = RegNodeBase - ParentFrameOffset
22078/// Subtracting RegNodeSize takes us to the offset of the registration node, and
22079/// subtracting the offset (negative on x86) takes us back to the parent FP.
22080static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
22081 SDValue EntryEBP) {
22082 MachineFunction &MF = DAG.getMachineFunction();
22083 SDLoc dl;
22084
22085 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22086 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
22087
22088 // It's possible that the parent function no longer has a personality function
22089 // if the exceptional code was optimized away, in which case we just return
22090 // the incoming EBP.
22091 if (!Fn->hasPersonalityFn())
22092 return EntryEBP;
22093
22094 // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
22095 // registration, or the .set_setframe offset.
22096 MCSymbol *OffsetSym =
22097 MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
22098 GlobalValue::dropLLVMManglingEscape(Fn->getName()));
22099 SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
22100 SDValue ParentFrameOffset =
22101 DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
22102
22103 // Return EntryEBP + ParentFrameOffset for x64. This adjusts from RSP after
22104 // prologue to RBP in the parent function.
22105 const X86Subtarget &Subtarget =
22106 static_cast<const X86Subtarget &>(DAG.getSubtarget());
22107 if (Subtarget.is64Bit())
22108 return DAG.getNode(ISD::ADD, dl, PtrVT, EntryEBP, ParentFrameOffset);
22109
22110 int RegNodeSize = getSEHRegistrationNodeSize(Fn);
22111 // RegNodeBase = EntryEBP - RegNodeSize
22112 // ParentFP = RegNodeBase - ParentFrameOffset
22113 SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
22114 DAG.getConstant(RegNodeSize, dl, PtrVT));
22115 return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, ParentFrameOffset);
22116}
22117
22118SDValue X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
22119 SelectionDAG &DAG) const {
22120 // Helper to detect if the operand is CUR_DIRECTION rounding mode.
22121 auto isRoundModeCurDirection = [](SDValue Rnd) {
22122 if (auto *C = dyn_cast<ConstantSDNode>(Rnd))
22123 return C->getZExtValue() == X86::STATIC_ROUNDING::CUR_DIRECTION;
22124
22125 return false;
22126 };
22127 auto isRoundModeSAE = [](SDValue Rnd) {
22128 if (auto *C = dyn_cast<ConstantSDNode>(Rnd))
22129 return C->getZExtValue() == X86::STATIC_ROUNDING::NO_EXC;
22130
22131 return false;
22132 };
22133 auto isRoundModeSAEToX = [](SDValue Rnd, unsigned &RC) {
22134 if (auto *C = dyn_cast<ConstantSDNode>(Rnd)) {
22135 RC = C->getZExtValue();
22136 if (RC & X86::STATIC_ROUNDING::NO_EXC) {
22137 // Clear the NO_EXC bit and check remaining bits.
22138 RC ^= X86::STATIC_ROUNDING::NO_EXC;
22139 return RC == X86::STATIC_ROUNDING::TO_NEAREST_INT ||
22140 RC == X86::STATIC_ROUNDING::TO_NEG_INF ||
22141 RC == X86::STATIC_ROUNDING::TO_POS_INF ||
22142 RC == X86::STATIC_ROUNDING::TO_ZERO;
22143 }
22144 }
22145
22146 return false;
22147 };
22148
22149 SDLoc dl(Op);
22150 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
22151 MVT VT = Op.getSimpleValueType();
22152 const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
22153 if (IntrData) {
22154 switch(IntrData->Type) {
22155 case INTR_TYPE_1OP: {
22156 // We specify 2 possible opcodes for intrinsics with rounding modes.
22157 // First, we check if the intrinsic may have non-default rounding mode,
22158 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
22159 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
22160 if (IntrWithRoundingModeOpcode != 0) {
22161 SDValue Rnd = Op.getOperand(2);
22162 unsigned RC = 0;
22163 if (isRoundModeSAEToX(Rnd, RC))
22164 return DAG.getNode(IntrWithRoundingModeOpcode, dl, Op.getValueType(),
22165 Op.getOperand(1),
22166 DAG.getTargetConstant(RC, dl, MVT::i32));
22167 if (!isRoundModeCurDirection(Rnd))
22168 return SDValue();
22169 }
22170 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
22171 }
22172 case INTR_TYPE_1OP_SAE: {
22173 SDValue Sae = Op.getOperand(2);
22174
22175 unsigned Opc;
22176 if (isRoundModeCurDirection(Sae))
22177 Opc = IntrData->Opc0;
22178 else if (isRoundModeSAE(Sae))
22179 Opc = IntrData->Opc1;
22180 else
22181 return SDValue();
22182
22183 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1));
22184 }
22185 case INTR_TYPE_2OP: {
22186 SDValue Src2 = Op.getOperand(2);
22187
22188 // We specify 2 possible opcodes for intrinsics with rounding modes.
22189 // First, we check if the intrinsic may have non-default rounding mode,
22190 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
22191 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
22192 if (IntrWithRoundingModeOpcode != 0) {
22193 SDValue Rnd = Op.getOperand(3);
22194 unsigned RC = 0;
22195 if (isRoundModeSAEToX(Rnd, RC))
22196 return DAG.getNode(IntrWithRoundingModeOpcode, dl, Op.getValueType(),
22197 Op.getOperand(1), Src2,
22198 DAG.getTargetConstant(RC, dl, MVT::i32));
22199 if (!isRoundModeCurDirection(Rnd))
22200 return SDValue();
22201 }
22202
22203 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
22204 Op.getOperand(1), Src2);
22205 }
22206 case INTR_TYPE_2OP_SAE: {
22207 SDValue Sae = Op.getOperand(3);
22208
22209 unsigned Opc;
22210 if (isRoundModeCurDirection(Sae))
22211 Opc = IntrData->Opc0;
22212 else if (isRoundModeSAE(Sae))
22213 Opc = IntrData->Opc1;
22214 else
22215 return SDValue();
22216
22217 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
22218 Op.getOperand(2));
22219 }
22220 case INTR_TYPE_3OP:
22221 case INTR_TYPE_3OP_IMM8: {
22222 SDValue Src1 = Op.getOperand(1);
22223 SDValue Src2 = Op.getOperand(2);
22224 SDValue Src3 = Op.getOperand(3);
22225
22226 if (IntrData->Type == INTR_TYPE_3OP_IMM8)
22227 Src3 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src3);
22228
22229 // We specify 2 possible opcodes for intrinsics with rounding modes.
22230 // First, we check if the intrinsic may have non-default rounding mode,
22231 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
22232 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
22233 if (IntrWithRoundingModeOpcode != 0) {
22234 SDValue Rnd = Op.getOperand(4);
22235 unsigned RC = 0;
22236 if (isRoundModeSAEToX(Rnd, RC))
22237 return DAG.getNode(IntrWithRoundingModeOpcode, dl, Op.getValueType(),
22238 Src1, Src2, Src3,
22239 DAG.getTargetConstant(RC, dl, MVT::i32));
22240 if (!isRoundModeCurDirection(Rnd))
22241 return SDValue();
22242 }
22243
22244 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
22245 Src1, Src2, Src3);
22246 }
22247 case INTR_TYPE_4OP:
22248 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
22249 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
22250 case INTR_TYPE_1OP_MASK: {
22251 SDValue Src = Op.getOperand(1);
22252 SDValue PassThru = Op.getOperand(2);
22253 SDValue Mask = Op.getOperand(3);
22254 // We add rounding mode to the Node when
22255 // - RC Opcode is specified and
22256 // - RC is not "current direction".
22257 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
22258 if (IntrWithRoundingModeOpcode != 0) {
22259 SDValue Rnd = Op.getOperand(4);
22260 unsigned RC = 0;
22261 if (isRoundModeSAEToX(Rnd, RC))
22262 return getVectorMaskingNode(
22263 DAG.getNode(IntrWithRoundingModeOpcode, dl, Op.getValueType(),
22264 Src, DAG.getTargetConstant(RC, dl, MVT::i32)),
22265 Mask, PassThru, Subtarget, DAG);
22266 if (!isRoundModeCurDirection(Rnd))
22267 return SDValue();
22268 }
22269 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
22270 Mask, PassThru, Subtarget, DAG);
22271 }
22272 case INTR_TYPE_1OP_MASK_SAE: {
22273 SDValue Src = Op.getOperand(1);
22274 SDValue PassThru = Op.getOperand(2);
22275 SDValue Mask = Op.getOperand(3);
22276 SDValue Rnd = Op.getOperand(4);
22277
22278 unsigned Opc;
22279 if (isRoundModeCurDirection(Rnd))
22280 Opc = IntrData->Opc0;
22281 else if (isRoundModeSAE(Rnd))
22282 Opc = IntrData->Opc1;
22283 else
22284 return SDValue();
22285
22286 return getVectorMaskingNode(DAG.getNode(Opc, dl, VT, Src),
22287 Mask, PassThru, Subtarget, DAG);
22288 }
22289 case INTR_TYPE_SCALAR_MASK: {
22290 SDValue Src1 = Op.getOperand(1);
22291 SDValue Src2 = Op.getOperand(2);
22292 SDValue passThru = Op.getOperand(3);
22293 SDValue Mask = Op.getOperand(4);
22294 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
22295 // There are 2 kinds of intrinsics in this group:
22296 // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
22297 // (2) With rounding mode and sae - 7 operands.
22298 bool HasRounding = IntrWithRoundingModeOpcode != 0;
22299 if (Op.getNumOperands() == (5U + HasRounding)) {
22300 if (HasRounding) {
22301 SDValue Rnd = Op.getOperand(5);
22302 unsigned RC = 0;
22303 if (isRoundModeSAEToX(Rnd, RC))
22304 return getScalarMaskingNode(
22305 DAG.getNode(IntrWithRoundingModeOpcode, dl, VT, Src1, Src2,
22306 DAG.getTargetConstant(RC, dl, MVT::i32)),
22307 Mask, passThru, Subtarget, DAG);
22308 if (!isRoundModeCurDirection(Rnd))
22309 return SDValue();
22310 }
22311 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1,
22312 Src2),
22313 Mask, passThru, Subtarget, DAG);
22314 }
22315
22316 assert(Op.getNumOperands() == (6U + HasRounding) &&((Op.getNumOperands() == (6U + HasRounding) && "Unexpected intrinsic form"
) ? static_cast<void> (0) : __assert_fail ("Op.getNumOperands() == (6U + HasRounding) && \"Unexpected intrinsic form\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 22317, __PRETTY_FUNCTION__))
22317 "Unexpected intrinsic form")((Op.getNumOperands() == (6U + HasRounding) && "Unexpected intrinsic form"
) ? static_cast<void> (0) : __assert_fail ("Op.getNumOperands() == (6U + HasRounding) && \"Unexpected intrinsic form\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 22317, __PRETTY_FUNCTION__))
;
22318 SDValue RoundingMode = Op.getOperand(5);
22319 unsigned Opc = IntrData->Opc0;
22320 if (HasRounding) {
22321 SDValue Sae = Op.getOperand(6);
22322 if (isRoundModeSAE(Sae))
22323 Opc = IntrWithRoundingModeOpcode;
22324 else if (!isRoundModeCurDirection(Sae))
22325 return SDValue();
22326 }
22327 return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1,
22328 Src2, RoundingMode),
22329 Mask, passThru, Subtarget, DAG);
22330 }
22331 case INTR_TYPE_SCALAR_MASK_RND: {
22332 SDValue Src1 = Op.getOperand(1);
22333 SDValue Src2 = Op.getOperand(2);
22334 SDValue passThru = Op.getOperand(3);
22335 SDValue Mask = Op.getOperand(4);
22336 SDValue Rnd = Op.getOperand(5);
22337
22338 SDValue NewOp;
22339 unsigned RC = 0;
22340 if (isRoundModeCurDirection(Rnd))
22341 NewOp = DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2);
22342 else if (isRoundModeSAEToX(Rnd, RC))
22343 NewOp = DAG.getNode(IntrData->Opc1, dl, VT, Src1, Src2,
22344 DAG.getTargetConstant(RC, dl, MVT::i32));
22345 else
22346 return SDValue();
22347
22348 return getScalarMaskingNode(NewOp, Mask, passThru, Subtarget, DAG);
22349 }
22350 case INTR_TYPE_SCALAR_MASK_SAE: {
22351 SDValue Src1 = Op.getOperand(1);
22352 SDValue Src2 = Op.getOperand(2);
22353 SDValue passThru = Op.getOperand(3);
22354 SDValue Mask = Op.getOperand(4);
22355 SDValue Sae = Op.getOperand(5);
22356 unsigned Opc;
22357 if (isRoundModeCurDirection(Sae))
22358 Opc = IntrData->Opc0;
22359 else if (isRoundModeSAE(Sae))
22360 Opc = IntrData->Opc1;
22361 else
22362 return SDValue();
22363
22364 return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2),
22365 Mask, passThru, Subtarget, DAG);
22366 }
22367 case INTR_TYPE_2OP_MASK: {
22368 SDValue Src1 = Op.getOperand(1);
22369 SDValue Src2 = Op.getOperand(2);
22370 SDValue PassThru = Op.getOperand(3);
22371 SDValue Mask = Op.getOperand(4);
22372 SDValue NewOp;
22373 if (IntrData->Opc1 != 0) {
22374 SDValue Rnd = Op.getOperand(5);
22375 unsigned RC = 0;
22376 if (isRoundModeSAEToX(Rnd, RC))
22377 NewOp = DAG.getNode(IntrData->Opc1, dl, VT, Src1, Src2,
22378 DAG.getTargetConstant(RC, dl, MVT::i32));
22379 else if (!isRoundModeCurDirection(Rnd))
22380 return SDValue();
22381 }
22382 if (!NewOp)
22383 NewOp = DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2);
22384 return getVectorMaskingNode(NewOp, Mask, PassThru, Subtarget, DAG);
22385 }
22386 case INTR_TYPE_2OP_MASK_SAE: {
22387 SDValue Src1 = Op.getOperand(1);
22388 SDValue Src2 = Op.getOperand(2);
22389 SDValue PassThru = Op.getOperand(3);
22390 SDValue Mask = Op.getOperand(4);
22391
22392 unsigned Opc = IntrData->Opc0;
22393 if (IntrData->Opc1 != 0) {
22394 SDValue Sae = Op.getOperand(5);
22395 if (isRoundModeSAE(Sae))
22396 Opc = IntrData->Opc1;
22397 else if (!isRoundModeCurDirection(Sae))
22398 return SDValue();
22399 }
22400
22401 return getVectorMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2),
22402 Mask, PassThru, Subtarget, DAG);
22403 }
22404 case INTR_TYPE_3OP_SCALAR_MASK_SAE: {
22405 SDValue Src1 = Op.getOperand(1);
22406 SDValue Src2 = Op.getOperand(2);
22407 SDValue Src3 = Op.getOperand(3);
22408 SDValue PassThru = Op.getOperand(4);
22409 SDValue Mask = Op.getOperand(5);
22410 SDValue Sae = Op.getOperand(6);
22411 unsigned Opc;
22412 if (isRoundModeCurDirection(Sae))
22413 Opc = IntrData->Opc0;
22414 else if (isRoundModeSAE(Sae))
22415 Opc = IntrData->Opc1;
22416 else
22417 return SDValue();
22418
22419 return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2, Src3),
22420 Mask, PassThru, Subtarget, DAG);
22421 }
22422 case INTR_TYPE_3OP_MASK_SAE: {
22423 SDValue Src1 = Op.getOperand(1);
22424 SDValue Src2 = Op.getOperand(2);
22425 SDValue Src3 = Op.getOperand(3);
22426 SDValue PassThru = Op.getOperand(4);
22427 SDValue Mask = Op.getOperand(5);
22428
22429 unsigned Opc = IntrData->Opc0;
22430 if (IntrData->Opc1 != 0) {
22431 SDValue Sae = Op.getOperand(6);
22432 if (isRoundModeSAE(Sae))
22433 Opc = IntrData->Opc1;
22434 else if (!isRoundModeCurDirection(Sae))
22435 return SDValue();
22436 }
22437 return getVectorMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2, Src3),
22438 Mask, PassThru, Subtarget, DAG);
22439 }
22440 case BLENDV: {
22441 SDValue Src1 = Op.getOperand(1);
22442 SDValue Src2 = Op.getOperand(2);
22443 SDValue Src3 = Op.getOperand(3);
22444
22445 EVT MaskVT = Src3.getValueType().changeVectorElementTypeToInteger();
22446 Src3 = DAG.getBitcast(MaskVT, Src3);
22447
22448 // Reverse the operands to match VSELECT order.
22449 return DAG.getNode(IntrData->Opc0, dl, VT, Src3, Src2, Src1);
22450 }
22451 case VPERM_2OP : {
22452 SDValue Src1 = Op.getOperand(1);
22453 SDValue Src2 = Op.getOperand(2);
22454
22455 // Swap Src1 and Src2 in the node creation
22456 return DAG.getNode(IntrData->Opc0, dl, VT,Src2, Src1);
22457 }
22458 case IFMA_OP:
22459 // NOTE: We need to swizzle the operands to pass the multiply operands
22460 // first.
22461 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
22462 Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
22463 case FPCLASSS: {
22464 SDValue Src1 = Op.getOperand(1);
22465 SDValue Imm = Op.getOperand(2);
22466 SDValue Mask = Op.getOperand(3);
22467 SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MVT::v1i1, Src1, Imm);
22468 SDValue FPclassMask = getScalarMaskingNode(FPclass, Mask, SDValue(),
22469 Subtarget, DAG);
22470 // Need to fill with zeros to ensure the bitcast will produce zeroes
22471 // for the upper bits. An EXTRACT_ELEMENT here wouldn't guarantee that.
22472 SDValue Ins = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, MVT::v8i1,
22473 DAG.getConstant(0, dl, MVT::v8i1),
22474 FPclassMask, DAG.getIntPtrConstant(0, dl));
22475 return DAG.getBitcast(MVT::i8, Ins);
22476 }
22477
22478 case CMP_MASK_CC: {
22479 MVT MaskVT = Op.getSimpleValueType();
22480 SDValue CC = Op.getOperand(3);
22481 CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
22482 // We specify 2 possible opcodes for intrinsics with rounding modes.
22483 // First, we check if the intrinsic may have non-default rounding mode,
22484 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
22485 if (IntrData->Opc1 != 0) {
22486 SDValue Sae = Op.getOperand(4);
22487 if (isRoundModeSAE(Sae))
22488 return DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
22489 Op.getOperand(2), CC, Sae);
22490 if (!isRoundModeCurDirection(Sae))
22491 return SDValue();
22492 }
22493 //default rounding mode
22494 return DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
22495 Op.getOperand(2), CC);
22496 }
22497 case CMP_MASK_SCALAR_CC: {
22498 SDValue Src1 = Op.getOperand(1);
22499 SDValue Src2 = Op.getOperand(2);
22500 SDValue CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(3));
22501 SDValue Mask = Op.getOperand(4);
22502
22503 SDValue Cmp;
22504 if (IntrData->Opc1 != 0) {
22505 SDValue Sae = Op.getOperand(5);
22506 if (isRoundModeSAE(Sae))
22507 Cmp = DAG.getNode(IntrData->Opc1, dl, MVT::v1i1, Src1, Src2, CC, Sae);
22508 else if (!isRoundModeCurDirection(Sae))
22509 return SDValue();
22510 }
22511 //default rounding mode
22512 if (!Cmp.getNode())
22513 Cmp = DAG.getNode(IntrData->Opc0, dl, MVT::v1i1, Src1, Src2, CC);
22514
22515 SDValue CmpMask = getScalarMaskingNode(Cmp, Mask, SDValue(),
22516 Subtarget, DAG);
22517 // Need to fill with zeros to ensure the bitcast will produce zeroes
22518 // for the upper bits. An EXTRACT_ELEMENT here wouldn't guarantee that.
22519 SDValue Ins = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, MVT::v8i1,
22520 DAG.getConstant(0, dl, MVT::v8i1),
22521 CmpMask, DAG.getIntPtrConstant(0, dl));
22522 return DAG.getBitcast(MVT::i8, Ins);
22523 }
22524 case COMI: { // Comparison intrinsics
22525 ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
22526 SDValue LHS = Op.getOperand(1);
22527 SDValue RHS = Op.getOperand(2);
22528 SDValue Comi = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
22529 SDValue InvComi = DAG.getNode(IntrData->Opc0, dl, MVT::i32, RHS, LHS);
22530 SDValue SetCC;
22531 switch (CC) {
22532 case ISD::SETEQ: { // (ZF = 0 and PF = 0)
22533 SetCC = getSETCC(X86::COND_E, Comi, dl, DAG);
22534 SDValue SetNP = getSETCC(X86::COND_NP, Comi, dl, DAG);
22535 SetCC = DAG.getNode(ISD::AND, dl, MVT::i8, SetCC, SetNP);
22536 break;
22537 }
22538 case ISD::SETNE: { // (ZF = 1 or PF = 1)
22539 SetCC = getSETCC(X86::COND_NE, Comi, dl, DAG);
22540 SDValue SetP = getSETCC(X86::COND_P, Comi, dl, DAG);
22541 SetCC = DAG.getNode(ISD::OR, dl, MVT::i8, SetCC, SetP);
22542 break;
22543 }
22544 case ISD::SETGT: // (CF = 0 and ZF = 0)
22545 SetCC = getSETCC(X86::COND_A, Comi, dl, DAG);
22546 break;
22547 case ISD::SETLT: { // The condition is opposite to GT. Swap the operands.
22548 SetCC = getSETCC(X86::COND_A, InvComi, dl, DAG);
22549 break;
22550 }
22551 case ISD::SETGE: // CF = 0
22552 SetCC = getSETCC(X86::COND_AE, Comi, dl, DAG);
22553 break;
22554 case ISD::SETLE: // The condition is opposite to GE. Swap the operands.
22555 SetCC = getSETCC(X86::COND_AE, InvComi, dl, DAG);
22556 break;
22557 default:
22558 llvm_unreachable("Unexpected illegal condition!")::llvm::llvm_unreachable_internal("Unexpected illegal condition!"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 22558)
;
22559 }
22560 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
22561 }
22562 case COMI_RM: { // Comparison intrinsics with Sae
22563 SDValue LHS = Op.getOperand(1);
22564 SDValue RHS = Op.getOperand(2);
22565 unsigned CondVal = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
22566 SDValue Sae = Op.getOperand(4);
22567
22568 SDValue FCmp;
22569 if (isRoundModeCurDirection(Sae))
22570 FCmp = DAG.getNode(X86ISD::FSETCCM, dl, MVT::v1i1, LHS, RHS,
22571 DAG.getConstant(CondVal, dl, MVT::i8));
22572 else if (isRoundModeSAE(Sae))
22573 FCmp = DAG.getNode(X86ISD::FSETCCM_SAE, dl, MVT::v1i1, LHS, RHS,
22574 DAG.getConstant(CondVal, dl, MVT::i8), Sae);
22575 else
22576 return SDValue();
22577 // Need to fill with zeros to ensure the bitcast will produce zeroes
22578 // for the upper bits. An EXTRACT_ELEMENT here wouldn't guarantee that.
22579 SDValue Ins = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, MVT::v16i1,
22580 DAG.getConstant(0, dl, MVT::v16i1),
22581 FCmp, DAG.getIntPtrConstant(0, dl));
22582 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32,
22583 DAG.getBitcast(MVT::i16, Ins));
22584 }
22585 case VSHIFT:
22586 return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
22587 Op.getOperand(1), Op.getOperand(2), Subtarget,
22588 DAG);
22589 case COMPRESS_EXPAND_IN_REG: {
22590 SDValue Mask = Op.getOperand(3);
22591 SDValue DataToCompress = Op.getOperand(1);
22592 SDValue PassThru = Op.getOperand(2);
22593 if (ISD::isBuildVectorAllOnes(Mask.getNode())) // return data as is
22594 return Op.getOperand(1);
22595
22596 // Avoid false dependency.
22597 if (PassThru.isUndef())
22598 PassThru = DAG.getConstant(0, dl, VT);
22599
22600 return DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress, PassThru,
22601 Mask);
22602 }
22603 case FIXUPIMM:
22604 case FIXUPIMM_MASKZ: {
22605 SDValue Src1 = Op.getOperand(1);
22606 SDValue Src2 = Op.getOperand(2);
22607 SDValue Src3 = Op.getOperand(3);
22608 SDValue Imm = Op.getOperand(4);
22609 SDValue Mask = Op.getOperand(5);
22610 SDValue Passthru = (IntrData->Type == FIXUPIMM)
22611 ? Src1
22612 : getZeroVector(VT, Subtarget, DAG, dl);
22613
22614 unsigned Opc = IntrData->Opc0;
22615 if (IntrData->Opc1 != 0) {
22616 SDValue Sae = Op.getOperand(6);
22617 if (isRoundModeSAE(Sae))
22618 Opc = IntrData->Opc1;
22619 else if (!isRoundModeCurDirection(Sae))
22620 return SDValue();
22621 }
22622
22623 SDValue FixupImm = DAG.getNode(Opc, dl, VT, Src1, Src2, Src3, Imm);
22624
22625 if (Opc == X86ISD::VFIXUPIMM || Opc == X86ISD::VFIXUPIMM_SAE)
22626 return getVectorMaskingNode(FixupImm, Mask, Passthru, Subtarget, DAG);
22627
22628 return getScalarMaskingNode(FixupImm, Mask, Passthru, Subtarget, DAG);
22629 }
22630 case ROUNDP: {
22631 assert(IntrData->Opc0 == X86ISD::VRNDSCALE && "Unexpected opcode")((IntrData->Opc0 == X86ISD::VRNDSCALE && "Unexpected opcode"
) ? static_cast<void> (0) : __assert_fail ("IntrData->Opc0 == X86ISD::VRNDSCALE && \"Unexpected opcode\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 22631, __PRETTY_FUNCTION__))
;
22632 // Clear the upper bits of the rounding immediate so that the legacy
22633 // intrinsic can't trigger the scaling behavior of VRNDSCALE.
22634 SDValue RoundingMode = DAG.getNode(ISD::AND, dl, MVT::i32,
22635 Op.getOperand(2),
22636 DAG.getConstant(0xf, dl, MVT::i32));
22637 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
22638 Op.getOperand(1), RoundingMode);
22639 }
22640 case ROUNDS: {
22641 assert(IntrData->Opc0 == X86ISD::VRNDSCALES && "Unexpected opcode")((IntrData->Opc0 == X86ISD::VRNDSCALES && "Unexpected opcode"
) ? static_cast<void> (0) : __assert_fail ("IntrData->Opc0 == X86ISD::VRNDSCALES && \"Unexpected opcode\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 22641, __PRETTY_FUNCTION__))
;
22642 // Clear the upper bits of the rounding immediate so that the legacy
22643 // intrinsic can't trigger the scaling behavior of VRNDSCALE.
22644 SDValue RoundingMode = DAG.getNode(ISD::AND, dl, MVT::i32,
22645 Op.getOperand(3),
22646 DAG.getConstant(0xf, dl, MVT::i32));
22647 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(),
22648 Op.getOperand(1), Op.getOperand(2), RoundingMode);
22649 }
22650 // ADC/ADCX/SBB
22651 case ADX: {
22652 SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
22653 SDVTList VTs = DAG.getVTList(Op.getOperand(2).getValueType(), MVT::i32);
22654
22655 SDValue Res;
22656 // If the carry in is zero, then we should just use ADD/SUB instead of
22657 // ADC/SBB.
22658 if (isNullConstant(Op.getOperand(1))) {
22659 Res = DAG.getNode(IntrData->Opc1, dl, VTs, Op.getOperand(2),
22660 Op.getOperand(3));
22661 } else {
22662 SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(1),
22663 DAG.getConstant(-1, dl, MVT::i8));
22664 Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(2),
22665 Op.getOperand(3), GenCF.getValue(1));
22666 }
22667 SDValue SetCC = getSETCC(X86::COND_B, Res.getValue(1), dl, DAG);
22668 SDValue Results[] = { SetCC, Res };
22669 return DAG.getMergeValues(Results, dl);
22670 }
22671 case CVTPD2PS_MASK:
22672 case CVTPD2DQ_MASK:
22673 case CVTQQ2PS_MASK:
22674 case TRUNCATE_TO_REG: {
22675 SDValue Src = Op.getOperand(1);
22676 SDValue PassThru = Op.getOperand(2);
22677 SDValue Mask = Op.getOperand(3);
22678
22679 if (isAllOnesConstant(Mask))
22680 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Src);
22681
22682 MVT SrcVT = Src.getSimpleValueType();
22683 MVT MaskVT = MVT::getVectorVT(MVT::i1, SrcVT.getVectorNumElements());
22684 Mask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
22685 return DAG.getNode(IntrData->Opc1, dl, Op.getValueType(), Src, PassThru,
22686 Mask);
22687 }
22688 case CVTPS2PH_MASK: {
22689 SDValue Src = Op.getOperand(1);
22690 SDValue Rnd = Op.getOperand(2);
22691 SDValue PassThru = Op.getOperand(3);
22692 SDValue Mask = Op.getOperand(4);
22693
22694 if (isAllOnesConstant(Mask))
22695 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Src, Rnd);
22696
22697 MVT SrcVT = Src.getSimpleValueType();
22698 MVT MaskVT = MVT::getVectorVT(MVT::i1, SrcVT.getVectorNumElements());
22699 Mask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
22700 return DAG.getNode(IntrData->Opc1, dl, Op.getValueType(), Src, Rnd,
22701 PassThru, Mask);
22702
22703 }
22704 case CVTNEPS2BF16_MASK: {
22705 SDValue Src = Op.getOperand(1);
22706 SDValue PassThru = Op.getOperand(2);
22707 SDValue Mask = Op.getOperand(3);
22708
22709 if (ISD::isBuildVectorAllOnes(Mask.getNode()))
22710 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Src);
22711
22712 // Break false dependency.
22713 if (PassThru.isUndef())
22714 PassThru = DAG.getConstant(0, dl, PassThru.getValueType());
22715
22716 return DAG.getNode(IntrData->Opc1, dl, Op.getValueType(), Src, PassThru,
22717 Mask);
22718 }
22719 default:
22720 break;
22721 }
22722 }
22723
22724 switch (IntNo) {
22725 default: return SDValue(); // Don't custom lower most intrinsics.
22726
22727 // ptest and testp intrinsics. The intrinsic these come from are designed to
22728 // return an integer value, not just an instruction so lower it to the ptest
22729 // or testp pattern and a setcc for the result.
22730 case Intrinsic::x86_avx512_ktestc_b:
22731 case Intrinsic::x86_avx512_ktestc_w:
22732 case Intrinsic::x86_avx512_ktestc_d:
22733 case Intrinsic::x86_avx512_ktestc_q:
22734 case Intrinsic::x86_avx512_ktestz_b:
22735 case Intrinsic::x86_avx512_ktestz_w:
22736 case Intrinsic::x86_avx512_ktestz_d:
22737 case Intrinsic::x86_avx512_ktestz_q:
22738 case Intrinsic::x86_sse41_ptestz:
22739 case Intrinsic::x86_sse41_ptestc:
22740 case Intrinsic::x86_sse41_ptestnzc:
22741 case Intrinsic::x86_avx_ptestz_256:
22742 case Intrinsic::x86_avx_ptestc_256:
22743 case Intrinsic::x86_avx_ptestnzc_256:
22744 case Intrinsic::x86_avx_vtestz_ps:
22745 case Intrinsic::x86_avx_vtestc_ps:
22746 case Intrinsic::x86_avx_vtestnzc_ps:
22747 case Intrinsic::x86_avx_vtestz_pd:
22748 case Intrinsic::x86_avx_vtestc_pd:
22749 case Intrinsic::x86_avx_vtestnzc_pd:
22750 case Intrinsic::x86_avx_vtestz_ps_256:
22751 case Intrinsic::x86_avx_vtestc_ps_256:
22752 case Intrinsic::x86_avx_vtestnzc_ps_256:
22753 case Intrinsic::x86_avx_vtestz_pd_256:
22754 case Intrinsic::x86_avx_vtestc_pd_256:
22755 case Intrinsic::x86_avx_vtestnzc_pd_256: {
22756 unsigned TestOpc = X86ISD::PTEST;
22757 X86::CondCode X86CC;
22758 switch (IntNo) {
22759 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.")::llvm::llvm_unreachable_internal("Bad fallthrough in Intrinsic lowering."
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 22759)
;
22760 case Intrinsic::x86_avx512_ktestc_b:
22761 case Intrinsic::x86_avx512_ktestc_w:
22762 case Intrinsic::x86_avx512_ktestc_d:
22763 case Intrinsic::x86_avx512_ktestc_q:
22764 // CF = 1
22765 TestOpc = X86ISD::KTEST;
22766 X86CC = X86::COND_B;
22767 break;
22768 case Intrinsic::x86_avx512_ktestz_b:
22769 case Intrinsic::x86_avx512_ktestz_w:
22770 case Intrinsic::x86_avx512_ktestz_d:
22771 case Intrinsic::x86_avx512_ktestz_q:
22772 TestOpc = X86ISD::KTEST;
22773 X86CC = X86::COND_E;
22774 break;
22775 case Intrinsic::x86_avx_vtestz_ps:
22776 case Intrinsic::x86_avx_vtestz_pd:
22777 case Intrinsic::x86_avx_vtestz_ps_256:
22778 case Intrinsic::x86_avx_vtestz_pd_256:
22779 TestOpc = X86ISD::TESTP;
22780 LLVM_FALLTHROUGH[[clang::fallthrough]];
22781 case Intrinsic::x86_sse41_ptestz:
22782 case Intrinsic::x86_avx_ptestz_256:
22783 // ZF = 1
22784 X86CC = X86::COND_E;
22785 break;
22786 case Intrinsic::x86_avx_vtestc_ps:
22787 case Intrinsic::x86_avx_vtestc_pd:
22788 case Intrinsic::x86_avx_vtestc_ps_256:
22789 case Intrinsic::x86_avx_vtestc_pd_256:
22790 TestOpc = X86ISD::TESTP;
22791 LLVM_FALLTHROUGH[[clang::fallthrough]];
22792 case Intrinsic::x86_sse41_ptestc:
22793 case Intrinsic::x86_avx_ptestc_256:
22794 // CF = 1
22795 X86CC = X86::COND_B;
22796 break;
22797 case Intrinsic::x86_avx_vtestnzc_ps:
22798 case Intrinsic::x86_avx_vtestnzc_pd:
22799 case Intrinsic::x86_avx_vtestnzc_ps_256:
22800 case Intrinsic::x86_avx_vtestnzc_pd_256:
22801 TestOpc = X86ISD::TESTP;
22802 LLVM_FALLTHROUGH[[clang::fallthrough]];
22803 case Intrinsic::x86_sse41_ptestnzc:
22804 case Intrinsic::x86_avx_ptestnzc_256:
22805 // ZF and CF = 0
22806 X86CC = X86::COND_A;
22807 break;
22808 }
22809
22810 SDValue LHS = Op.getOperand(1);
22811 SDValue RHS = Op.getOperand(2);
22812 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
22813 SDValue SetCC = getSETCC(X86CC, Test, dl, DAG);
22814 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
22815 }
22816
22817 case Intrinsic::x86_sse42_pcmpistria128:
22818 case Intrinsic::x86_sse42_pcmpestria128:
22819 case Intrinsic::x86_sse42_pcmpistric128:
22820 case Intrinsic::x86_sse42_pcmpestric128:
22821 case Intrinsic::x86_sse42_pcmpistrio128:
22822 case Intrinsic::x86_sse42_pcmpestrio128:
22823 case Intrinsic::x86_sse42_pcmpistris128:
22824 case Intrinsic::x86_sse42_pcmpestris128:
22825 case Intrinsic::x86_sse42_pcmpistriz128:
22826 case Intrinsic::x86_sse42_pcmpestriz128: {
22827 unsigned Opcode;
22828 X86::CondCode X86CC;
22829 switch (IntNo) {
22830 default: llvm_unreachable("Impossible intrinsic")::llvm::llvm_unreachable_internal("Impossible intrinsic", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 22830)
; // Can't reach here.
22831 case Intrinsic::x86_sse42_pcmpistria128:
22832 Opcode = X86ISD::PCMPISTR;
22833 X86CC = X86::COND_A;
22834 break;
22835 case Intrinsic::x86_sse42_pcmpestria128:
22836 Opcode = X86ISD::PCMPESTR;
22837 X86CC = X86::COND_A;
22838 break;
22839 case Intrinsic::x86_sse42_pcmpistric128:
22840 Opcode = X86ISD::PCMPISTR;
22841 X86CC = X86::COND_B;
22842 break;
22843 case Intrinsic::x86_sse42_pcmpestric128:
22844 Opcode = X86ISD::PCMPESTR;
22845 X86CC = X86::COND_B;
22846 break;
22847 case Intrinsic::x86_sse42_pcmpistrio128:
22848 Opcode = X86ISD::PCMPISTR;
22849 X86CC = X86::COND_O;
22850 break;
22851 case Intrinsic::x86_sse42_pcmpestrio128:
22852 Opcode = X86ISD::PCMPESTR;
22853 X86CC = X86::COND_O;
22854 break;
22855 case Intrinsic::x86_sse42_pcmpistris128:
22856 Opcode = X86ISD::PCMPISTR;
22857 X86CC = X86::COND_S;
22858 break;
22859 case Intrinsic::x86_sse42_pcmpestris128:
22860 Opcode = X86ISD::PCMPESTR;
22861 X86CC = X86::COND_S;
22862 break;
22863 case Intrinsic::x86_sse42_pcmpistriz128:
22864 Opcode = X86ISD::PCMPISTR;
22865 X86CC = X86::COND_E;
22866 break;
22867 case Intrinsic::x86_sse42_pcmpestriz128:
22868 Opcode = X86ISD::PCMPESTR;
22869 X86CC = X86::COND_E;
22870 break;
22871 }
22872 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
22873 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::v16i8, MVT::i32);
22874 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps).getValue(2);
22875 SDValue SetCC = getSETCC(X86CC, PCMP, dl, DAG);
22876 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
22877 }
22878
22879 case Intrinsic::x86_sse42_pcmpistri128:
22880 case Intrinsic::x86_sse42_pcmpestri128: {
22881 unsigned Opcode;
22882 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
22883 Opcode = X86ISD::PCMPISTR;
22884 else
22885 Opcode = X86ISD::PCMPESTR;
22886
22887 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
22888 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::v16i8, MVT::i32);
22889 return DAG.getNode(Opcode, dl, VTs, NewOps);
22890 }
22891
22892 case Intrinsic::x86_sse42_pcmpistrm128:
22893 case Intrinsic::x86_sse42_pcmpestrm128: {
22894 unsigned Opcode;
22895 if (IntNo == Intrinsic::x86_sse42_pcmpistrm128)
22896 Opcode = X86ISD::PCMPISTR;
22897 else
22898 Opcode = X86ISD::PCMPESTR;
22899
22900 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
22901 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::v16i8, MVT::i32);
22902 return DAG.getNode(Opcode, dl, VTs, NewOps).getValue(1);
22903 }
22904
22905 case Intrinsic::eh_sjlj_lsda: {
22906 MachineFunction &MF = DAG.getMachineFunction();
22907 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22908 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
22909 auto &Context = MF.getMMI().getContext();
22910 MCSymbol *S = Context.getOrCreateSymbol(Twine("GCC_except_table") +
22911 Twine(MF.getFunctionNumber()));
22912 return DAG.getNode(getGlobalWrapperKind(), dl, VT,
22913 DAG.getMCSymbol(S, PtrVT));
22914 }
22915
22916 case Intrinsic::x86_seh_lsda: {
22917 // Compute the symbol for the LSDA. We know it'll get emitted later.
22918 MachineFunction &MF = DAG.getMachineFunction();
22919 SDValue Op1 = Op.getOperand(1);
22920 auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
22921 MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
22922 GlobalValue::dropLLVMManglingEscape(Fn->getName()));
22923
22924 // Generate a simple absolute symbol reference. This intrinsic is only
22925 // supported on 32-bit Windows, which isn't PIC.
22926 SDValue Result = DAG.getMCSymbol(LSDASym, VT);
22927 return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
22928 }
22929
22930 case Intrinsic::eh_recoverfp: {
22931 SDValue FnOp = Op.getOperand(1);
22932 SDValue IncomingFPOp = Op.getOperand(2);
22933 GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
22934 auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
22935 if (!Fn)
22936 report_fatal_error(
22937 "llvm.eh.recoverfp must take a function as the first argument");
22938 return recoverFramePointer(DAG, Fn, IncomingFPOp);
22939 }
22940
22941 case Intrinsic::localaddress: {
22942 // Returns one of the stack, base, or frame pointer registers, depending on
22943 // which is used to reference local variables.
22944 MachineFunction &MF = DAG.getMachineFunction();
22945 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
22946 unsigned Reg;
22947 if (RegInfo->hasBasePointer(MF))
22948 Reg = RegInfo->getBaseRegister();
22949 else { // Handles the SP or FP case.
22950 bool CantUseFP = RegInfo->needsStackRealignment(MF);
22951 if (CantUseFP)
22952 Reg = RegInfo->getPtrSizedStackRegister(MF);
22953 else
22954 Reg = RegInfo->getPtrSizedFrameRegister(MF);
22955 }
22956 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
22957 }
22958
22959 case Intrinsic::x86_avx512_vp2intersect_q_512:
22960 case Intrinsic::x86_avx512_vp2intersect_q_256:
22961 case Intrinsic::x86_avx512_vp2intersect_q_128:
22962 case Intrinsic::x86_avx512_vp2intersect_d_512:
22963 case Intrinsic::x86_avx512_vp2intersect_d_256:
22964 case Intrinsic::x86_avx512_vp2intersect_d_128: {
22965 MVT MaskVT = Op.getSimpleValueType();
22966
22967 SDVTList VTs = DAG.getVTList(MVT::Untyped, MVT::Other);
22968 SDLoc DL(Op);
22969
22970 SDValue Operation =
22971 DAG.getNode(X86ISD::VP2INTERSECT, DL, VTs,
22972 Op->getOperand(1), Op->getOperand(2));
22973
22974 SDValue Result0 = DAG.getTargetExtractSubreg(X86::sub_mask_0, DL,
22975 MaskVT, Operation);
22976 SDValue Result1 = DAG.getTargetExtractSubreg(X86::sub_mask_1, DL,
22977 MaskVT, Operation);
22978 return DAG.getMergeValues({Result0, Result1}, DL);
22979 }
22980 }
22981}
22982
22983static SDValue getAVX2GatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
22984 SDValue Src, SDValue Mask, SDValue Base,
22985 SDValue Index, SDValue ScaleOp, SDValue Chain,
22986 const X86Subtarget &Subtarget) {
22987 SDLoc dl(Op);
22988 auto *C = dyn_cast<ConstantSDNode>(ScaleOp);
22989 // Scale must be constant.
22990 if (!C)
22991 return SDValue();
22992 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
22993 EVT MaskVT = Mask.getValueType().changeVectorElementTypeToInteger();
22994 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
22995 // If source is undef or we know it won't be used, use a zero vector
22996 // to break register dependency.
22997 // TODO: use undef instead and let BreakFalseDeps deal with it?
22998 if (Src.isUndef() || ISD::isBuildVectorAllOnes(Mask.getNode()))
22999 Src = getZeroVector(Op.getSimpleValueType(), Subtarget, DAG, dl);
23000
23001 MemIntrinsicSDNode *MemIntr = cast<MemIntrinsicSDNode>(Op);
23002
23003 SDValue Ops[] = {Chain, Src, Mask, Base, Index, Scale };
23004 SDValue Res = DAG.getTargetMemSDNode<X86MaskedGatherSDNode>(
23005 VTs, Ops, dl, MemIntr->getMemoryVT(), MemIntr->getMemOperand());
23006 return DAG.getMergeValues({ Res, Res.getValue(2) }, dl);
23007}
23008
23009static SDValue getGatherNode(SDValue Op, SelectionDAG &DAG,
23010 SDValue Src, SDValue Mask, SDValue Base,
23011 SDValue Index, SDValue ScaleOp, SDValue Chain,
23012 const X86Subtarget &Subtarget) {
23013 MVT VT = Op.getSimpleValueType();
23014 SDLoc dl(Op);
23015 auto *C = dyn_cast<ConstantSDNode>(ScaleOp);
23016 // Scale must be constant.
23017 if (!C)
23018 return SDValue();
23019 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
23020 unsigned MinElts = std::min(Index.getSimpleValueType().getVectorNumElements(),
23021 VT.getVectorNumElements());
23022 MVT MaskVT = MVT::getVectorVT(MVT::i1, MinElts);
23023
23024 // We support two versions of the gather intrinsics. One with scalar mask and
23025 // one with vXi1 mask. Convert scalar to vXi1 if necessary.
23026 if (Mask.getValueType() != MaskVT)
23027 Mask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
23028
23029 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
23030 // If source is undef or we know it won't be used, use a zero vector
23031 // to break register dependency.
23032 // TODO: use undef instead and let BreakFalseDeps deal with it?
23033 if (Src.isUndef() || ISD::isBuildVectorAllOnes(Mask.getNode()))
23034 Src = getZeroVector(Op.getSimpleValueType(), Subtarget, DAG, dl);
23035
23036 MemIntrinsicSDNode *MemIntr = cast<MemIntrinsicSDNode>(Op);
23037
23038 SDValue Ops[] = {Chain, Src, Mask, Base, Index, Scale };
23039 SDValue Res = DAG.getTargetMemSDNode<X86MaskedGatherSDNode>(
23040 VTs, Ops, dl, MemIntr->getMemoryVT(), MemIntr->getMemOperand());
23041 return DAG.getMergeValues({ Res, Res.getValue(2) }, dl);
23042}
23043
23044static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
23045 SDValue Src, SDValue Mask, SDValue Base,
23046 SDValue Index, SDValue ScaleOp, SDValue Chain,
23047 const X86Subtarget &Subtarget) {
23048 SDLoc dl(Op);
23049 auto *C = dyn_cast<ConstantSDNode>(ScaleOp);
23050 // Scale must be constant.
23051 if (!C)
23052 return SDValue();
23053 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
23054 unsigned MinElts = std::min(Index.getSimpleValueType().getVectorNumElements(),
23055 Src.getSimpleValueType().getVectorNumElements());
23056 MVT MaskVT = MVT::getVectorVT(MVT::i1, MinElts);
23057
23058 // We support two versions of the scatter intrinsics. One with scalar mask and
23059 // one with vXi1 mask. Convert scalar to vXi1 if necessary.
23060 if (Mask.getValueType() != MaskVT)
23061 Mask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
23062
23063 MemIntrinsicSDNode *MemIntr = cast<MemIntrinsicSDNode>(Op);
23064
23065 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
23066 SDValue Ops[] = {Chain, Src, Mask, Base, Index, Scale};
23067 SDValue Res = DAG.getTargetMemSDNode<X86MaskedScatterSDNode>(
23068 VTs, Ops, dl, MemIntr->getMemoryVT(), MemIntr->getMemOperand());
23069 return Res.getValue(1);
23070}
23071
23072static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
23073 SDValue Mask, SDValue Base, SDValue Index,
23074 SDValue ScaleOp, SDValue Chain,
23075 const X86Subtarget &Subtarget) {
23076 SDLoc dl(Op);
23077 auto *C = dyn_cast<ConstantSDNode>(ScaleOp);
23078 // Scale must be constant.
23079 if (!C)
23080 return SDValue();
23081 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
23082 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
23083 SDValue Segment = DAG.getRegister(0, MVT::i32);
23084 MVT MaskVT =
23085 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
23086 SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
23087 SDValue Ops[] = {VMask, Base, Scale, Index, Disp, Segment, Chain};
23088 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
23089 return SDValue(Res, 0);
23090}
23091
23092/// Handles the lowering of builtin intrinsics with chain that return their
23093/// value into registers EDX:EAX.
23094/// If operand ScrReg is a valid register identifier, then operand 2 of N is
23095/// copied to SrcReg. The assumption is that SrcReg is an implicit input to
23096/// TargetOpcode.
23097/// Returns a Glue value which can be used to add extra copy-from-reg if the
23098/// expanded intrinsics implicitly defines extra registers (i.e. not just
23099/// EDX:EAX).
23100static SDValue expandIntrinsicWChainHelper(SDNode *N, const SDLoc &DL,
23101 SelectionDAG &DAG,
23102 unsigned TargetOpcode,
23103 unsigned SrcReg,
23104 const X86Subtarget &Subtarget,
23105 SmallVectorImpl<SDValue> &Results) {
23106 SDValue Chain = N->getOperand(0);
23107 SDValue Glue;
23108
23109 if (SrcReg) {
23110 assert(N->getNumOperands() == 3 && "Unexpected number of operands!")((N->getNumOperands() == 3 && "Unexpected number of operands!"
) ? static_cast<void> (0) : __assert_fail ("N->getNumOperands() == 3 && \"Unexpected number of operands!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 23110, __PRETTY_FUNCTION__))
;
23111 Chain = DAG.getCopyToReg(Chain, DL, SrcReg, N->getOperand(2), Glue);
23112 Glue = Chain.getValue(1);
23113 }
23114
23115 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
23116 SDValue N1Ops[] = {Chain, Glue};
23117 SDNode *N1 = DAG.getMachineNode(
23118 TargetOpcode, DL, Tys, ArrayRef<SDValue>(N1Ops, Glue.getNode() ? 2 : 1));
23119 Chain = SDValue(N1, 0);
23120
23121 // Reads the content of XCR and returns it in registers EDX:EAX.
23122 SDValue LO, HI;
23123 if (Subtarget.is64Bit()) {
23124 LO = DAG.getCopyFromReg(Chain, DL, X86::RAX, MVT::i64, SDValue(N1, 1));
23125 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
23126 LO.getValue(2));
23127 } else {
23128 LO = DAG.getCopyFromReg(Chain, DL, X86::EAX, MVT::i32, SDValue(N1, 1));
23129 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
23130 LO.getValue(2));
23131 }
23132 Chain = HI.getValue(1);
23133 Glue = HI.getValue(2);
23134
23135 if (Subtarget.is64Bit()) {
23136 // Merge the two 32-bit values into a 64-bit one.
23137 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
23138 DAG.getConstant(32, DL, MVT::i8));
23139 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
23140 Results.push_back(Chain);
23141 return Glue;
23142 }
23143
23144 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
23145 SDValue Ops[] = { LO, HI };
23146 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
23147 Results.push_back(Pair);
23148 Results.push_back(Chain);
23149 return Glue;
23150}
23151
23152/// Handles the lowering of builtin intrinsics that read the time stamp counter
23153/// (x86_rdtsc and x86_rdtscp). This function is also used to custom lower
23154/// READCYCLECOUNTER nodes.
23155static void getReadTimeStampCounter(SDNode *N, const SDLoc &DL, unsigned Opcode,
23156 SelectionDAG &DAG,
23157 const X86Subtarget &Subtarget,
23158 SmallVectorImpl<SDValue> &Results) {
23159 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
23160 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
23161 // and the EAX register is loaded with the low-order 32 bits.
23162 SDValue Glue = expandIntrinsicWChainHelper(N, DL, DAG, Opcode,
23163 /* NoRegister */0, Subtarget,
23164 Results);
23165 if (Opcode != X86::RDTSCP)
23166 return;
23167
23168 SDValue Chain = Results[1];
23169 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
23170 // the ECX register. Add 'ecx' explicitly to the chain.
23171 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32, Glue);
23172 Results[1] = ecx;
23173 Results.push_back(ecx.getValue(1));
23174}
23175
23176static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget &Subtarget,
23177 SelectionDAG &DAG) {
23178 SmallVector<SDValue, 3> Results;
23179 SDLoc DL(Op);
23180 getReadTimeStampCounter(Op.getNode(), DL, X86::RDTSC, DAG, Subtarget,
23181 Results);
23182 return DAG.getMergeValues(Results, DL);
23183}
23184
23185static SDValue MarkEHRegistrationNode(SDValue Op, SelectionDAG &DAG) {
23186 MachineFunction &MF = DAG.getMachineFunction();
23187 SDValue Chain = Op.getOperand(0);
23188 SDValue RegNode = Op.getOperand(2);
23189 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
23190 if (!EHInfo)
23191 report_fatal_error("EH registrations only live in functions using WinEH");
23192
23193 // Cast the operand to an alloca, and remember the frame index.
23194 auto *FINode = dyn_cast<FrameIndexSDNode>(RegNode);
23195 if (!FINode)
23196 report_fatal_error("llvm.x86.seh.ehregnode expects a static alloca");
23197 EHInfo->EHRegNodeFrameIndex = FINode->getIndex();
23198
23199 // Return the chain operand without making any DAG nodes.
23200 return Chain;
23201}
23202
23203static SDValue MarkEHGuard(SDValue Op, SelectionDAG &DAG) {
23204 MachineFunction &MF = DAG.getMachineFunction();
23205 SDValue Chain = Op.getOperand(0);
23206 SDValue EHGuard = Op.getOperand(2);
23207 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
23208 if (!EHInfo)
23209 report_fatal_error("EHGuard only live in functions using WinEH");
23210
23211 // Cast the operand to an alloca, and remember the frame index.
23212 auto *FINode = dyn_cast<FrameIndexSDNode>(EHGuard);
23213 if (!FINode)
23214 report_fatal_error("llvm.x86.seh.ehguard expects a static alloca");
23215 EHInfo->EHGuardFrameIndex = FINode->getIndex();
23216
23217 // Return the chain operand without making any DAG nodes.
23218 return Chain;
23219}
23220
23221/// Emit Truncating Store with signed or unsigned saturation.
23222static SDValue
23223EmitTruncSStore(bool SignedSat, SDValue Chain, const SDLoc &Dl, SDValue Val,
23224 SDValue Ptr, EVT MemVT, MachineMemOperand *MMO,
23225 SelectionDAG &DAG) {
23226
23227 SDVTList VTs = DAG.getVTList(MVT::Other);
23228 SDValue Undef = DAG.getUNDEF(Ptr.getValueType());
23229 SDValue Ops[] = { Chain, Val, Ptr, Undef };
23230 return SignedSat ?
23231 DAG.getTargetMemSDNode<TruncSStoreSDNode>(VTs, Ops, Dl, MemVT, MMO) :
23232 DAG.getTargetMemSDNode<TruncUSStoreSDNode>(VTs, Ops, Dl, MemVT, MMO);
23233}
23234
23235/// Emit Masked Truncating Store with signed or unsigned saturation.
23236static SDValue
23237EmitMaskedTruncSStore(bool SignedSat, SDValue Chain, const SDLoc &Dl,
23238 SDValue Val, SDValue Ptr, SDValue Mask, EVT MemVT,
23239 MachineMemOperand *MMO, SelectionDAG &DAG) {
23240
23241 SDVTList VTs = DAG.getVTList(MVT::Other);
23242 SDValue Ops[] = { Chain, Val, Ptr, Mask };
23243 return SignedSat ?
23244 DAG.getTargetMemSDNode<MaskedTruncSStoreSDNode>(VTs, Ops, Dl, MemVT, MMO) :
23245 DAG.getTargetMemSDNode<MaskedTruncUSStoreSDNode>(VTs, Ops, Dl, MemVT, MMO);
23246}
23247
23248static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget &Subtarget,
23249 SelectionDAG &DAG) {
23250 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
23251
23252 const IntrinsicData *IntrData = getIntrinsicWithChain(IntNo);
23253 if (!IntrData) {
23254 switch (IntNo) {
23255 case llvm::Intrinsic::x86_seh_ehregnode:
23256 return MarkEHRegistrationNode(Op, DAG);
23257 case llvm::Intrinsic::x86_seh_ehguard:
23258 return MarkEHGuard(Op, DAG);
23259 case llvm::Intrinsic::x86_rdpkru: {
23260 SDLoc dl(Op);
23261 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
23262 // Create a RDPKRU node and pass 0 to the ECX parameter.
23263 return DAG.getNode(X86ISD::RDPKRU, dl, VTs, Op.getOperand(0),
23264 DAG.getConstant(0, dl, MVT::i32));
23265 }
23266 case llvm::Intrinsic::x86_wrpkru: {
23267 SDLoc dl(Op);
23268 // Create a WRPKRU node, pass the input to the EAX parameter, and pass 0
23269 // to the EDX and ECX parameters.
23270 return DAG.getNode(X86ISD::WRPKRU, dl, MVT::Other,
23271 Op.getOperand(0), Op.getOperand(2),
23272 DAG.getConstant(0, dl, MVT::i32),
23273 DAG.getConstant(0, dl, MVT::i32));
23274 }
23275 case llvm::Intrinsic::x86_flags_read_u32:
23276 case llvm::Intrinsic::x86_flags_read_u64:
23277 case llvm::Intrinsic::x86_flags_write_u32:
23278 case llvm::Intrinsic::x86_flags_write_u64: {
23279 // We need a frame pointer because this will get lowered to a PUSH/POP
23280 // sequence.
23281 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
23282 MFI.setHasCopyImplyingStackAdjustment(true);
23283 // Don't do anything here, we will expand these intrinsics out later
23284 // during ExpandISelPseudos in EmitInstrWithCustomInserter.
23285 return SDValue();
23286 }
23287 case Intrinsic::x86_lwpins32:
23288 case Intrinsic::x86_lwpins64:
23289 case Intrinsic::x86_umwait:
23290 case Intrinsic::x86_tpause: {
23291 SDLoc dl(Op);
23292 SDValue Chain = Op->getOperand(0);
23293 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
23294 unsigned Opcode;
23295
23296 switch (IntNo) {
23297 default: llvm_unreachable("Impossible intrinsic")::llvm::llvm_unreachable_internal("Impossible intrinsic", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 23297)
;
23298 case Intrinsic::x86_umwait:
23299 Opcode = X86ISD::UMWAIT;
23300 break;
23301 case Intrinsic::x86_tpause:
23302 Opcode = X86ISD::TPAUSE;
23303 break;
23304 case Intrinsic::x86_lwpins32:
23305 case Intrinsic::x86_lwpins64:
23306 Opcode = X86ISD::LWPINS;
23307 break;
23308 }
23309
23310 SDValue Operation =
23311 DAG.getNode(Opcode, dl, VTs, Chain, Op->getOperand(2),
23312 Op->getOperand(3), Op->getOperand(4));
23313 SDValue SetCC = getSETCC(X86::COND_B, Operation.getValue(0), dl, DAG);
23314 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), SetCC,
23315 Operation.getValue(1));
23316 }
23317 case Intrinsic::x86_enqcmd:
23318 case Intrinsic::x86_enqcmds: {
23319 SDLoc dl(Op);
23320 SDValue Chain = Op.getOperand(0);
23321 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
23322 unsigned Opcode;
23323 switch (IntNo) {
23324 default: llvm_unreachable("Impossible intrinsic!")::llvm::llvm_unreachable_internal("Impossible intrinsic!", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 23324)
;
23325 case Intrinsic::x86_enqcmd:
23326 Opcode = X86ISD::ENQCMD;
23327 break;
23328 case Intrinsic::x86_enqcmds:
23329 Opcode = X86ISD::ENQCMDS;
23330 break;
23331 }
23332 SDValue Operation = DAG.getNode(Opcode, dl, VTs, Chain, Op.getOperand(2),
23333 Op.getOperand(3));
23334 SDValue SetCC = getSETCC(X86::COND_E, Operation.getValue(0), dl, DAG);
23335 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), SetCC,
23336 Operation.getValue(1));
23337 }
23338 }
23339 return SDValue();
23340 }
23341
23342 SDLoc dl(Op);
23343 switch(IntrData->Type) {
23344 default: llvm_unreachable("Unknown Intrinsic Type")::llvm::llvm_unreachable_internal("Unknown Intrinsic Type", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 23344)
;
23345 case RDSEED:
23346 case RDRAND: {
23347 // Emit the node with the right value type.
23348 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32, MVT::Other);
23349 SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
23350
23351 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
23352 // Otherwise return the value from Rand, which is always 0, casted to i32.
23353 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
23354 DAG.getConstant(1, dl, Op->getValueType(1)),
23355 DAG.getConstant(X86::COND_B, dl, MVT::i8),
23356 SDValue(Result.getNode(), 1) };
23357 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl, Op->getValueType(1), Ops);
23358
23359 // Return { result, isValid, chain }.
23360 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
23361 SDValue(Result.getNode(), 2));
23362 }
23363 case GATHER_AVX2: {
23364 SDValue Chain = Op.getOperand(0);
23365 SDValue Src = Op.getOperand(2);
23366 SDValue Base = Op.getOperand(3);
23367 SDValue Index = Op.getOperand(4);
23368 SDValue Mask = Op.getOperand(5);
23369 SDValue Scale = Op.getOperand(6);
23370 return getAVX2GatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
23371 Scale, Chain, Subtarget);
23372 }
23373 case GATHER: {
23374 //gather(v1, mask, index, base, scale);
23375 SDValue Chain = Op.getOperand(0);
23376 SDValue Src = Op.getOperand(2);
23377 SDValue Base = Op.getOperand(3);
23378 SDValue Index = Op.getOperand(4);
23379 SDValue Mask = Op.getOperand(5);
23380 SDValue Scale = Op.getOperand(6);
23381 return getGatherNode(Op, DAG, Src, Mask, Base, Index, Scale,
23382 Chain, Subtarget);
23383 }
23384 case SCATTER: {
23385 //scatter(base, mask, index, v1, scale);
23386 SDValue Chain = Op.getOperand(0);
23387 SDValue Base = Op.getOperand(2);
23388 SDValue Mask = Op.getOperand(3);
23389 SDValue Index = Op.getOperand(4);
23390 SDValue Src = Op.getOperand(5);
23391 SDValue Scale = Op.getOperand(6);
23392 return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
23393 Scale, Chain, Subtarget);
23394 }
23395 case PREFETCH: {
23396 SDValue Hint = Op.getOperand(6);
23397 unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
23398 assert((HintVal == 2 || HintVal == 3) &&(((HintVal == 2 || HintVal == 3) && "Wrong prefetch hint in intrinsic: should be 2 or 3"
) ? static_cast<void> (0) : __assert_fail ("(HintVal == 2 || HintVal == 3) && \"Wrong prefetch hint in intrinsic: should be 2 or 3\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 23399, __PRETTY_FUNCTION__))
23399 "Wrong prefetch hint in intrinsic: should be 2 or 3")(((HintVal == 2 || HintVal == 3) && "Wrong prefetch hint in intrinsic: should be 2 or 3"
) ? static_cast<void> (0) : __assert_fail ("(HintVal == 2 || HintVal == 3) && \"Wrong prefetch hint in intrinsic: should be 2 or 3\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 23399, __PRETTY_FUNCTION__))
;
23400 unsigned Opcode = (HintVal == 2 ? IntrData->Opc1 : IntrData->Opc0);
23401 SDValue Chain = Op.getOperand(0);
23402 SDValue Mask = Op.getOperand(2);
23403 SDValue Index = Op.getOperand(3);
23404 SDValue Base = Op.getOperand(4);
23405 SDValue Scale = Op.getOperand(5);
23406 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain,
23407 Subtarget);
23408 }
23409 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
23410 case RDTSC: {
23411 SmallVector<SDValue, 2> Results;
23412 getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
23413 Results);
23414 return DAG.getMergeValues(Results, dl);
23415 }
23416 // Read Performance Monitoring Counters.
23417 case RDPMC:
23418 // GetExtended Control Register.
23419 case XGETBV: {
23420 SmallVector<SDValue, 2> Results;
23421
23422 // RDPMC uses ECX to select the index of the performance counter to read.
23423 // XGETBV uses ECX to select the index of the XCR register to return.
23424 // The result is stored into registers EDX:EAX.
23425 expandIntrinsicWChainHelper(Op.getNode(), dl, DAG, IntrData->Opc0, X86::ECX,
23426 Subtarget, Results);
23427 return DAG.getMergeValues(Results, dl);
23428 }
23429 // XTEST intrinsics.
23430 case XTEST: {
23431 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
23432 SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
23433
23434 SDValue SetCC = getSETCC(X86::COND_NE, InTrans, dl, DAG);
23435 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
23436 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
23437 Ret, SDValue(InTrans.getNode(), 1));
23438 }
23439 case TRUNCATE_TO_MEM_VI8:
23440 case TRUNCATE_TO_MEM_VI16:
23441 case TRUNCATE_TO_MEM_VI32: {
23442 SDValue Mask = Op.getOperand(4);
23443 SDValue DataToTruncate = Op.getOperand(3);
23444 SDValue Addr = Op.getOperand(2);
23445 SDValue Chain = Op.getOperand(0);
23446
23447 MemIntrinsicSDNode *MemIntr = dyn_cast<MemIntrinsicSDNode>(Op);
23448 assert(MemIntr && "Expected MemIntrinsicSDNode!")((MemIntr && "Expected MemIntrinsicSDNode!") ? static_cast
<void> (0) : __assert_fail ("MemIntr && \"Expected MemIntrinsicSDNode!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 23448, __PRETTY_FUNCTION__))
;
23449
23450 EVT MemVT = MemIntr->getMemoryVT();
23451
23452 uint16_t TruncationOp = IntrData->Opc0;
23453 switch (TruncationOp) {
23454 case X86ISD::VTRUNC: {
23455 if (isAllOnesConstant(Mask)) // return just a truncate store
23456 return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr, MemVT,
23457 MemIntr->getMemOperand());
23458
23459 MVT MaskVT = MVT::getVectorVT(MVT::i1, MemVT.getVectorNumElements());
23460 SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
23461
23462 return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr, VMask, MemVT,
23463 MemIntr->getMemOperand(), true /* truncating */);
23464 }
23465 case X86ISD::VTRUNCUS:
23466 case X86ISD::VTRUNCS: {
23467 bool IsSigned = (TruncationOp == X86ISD::VTRUNCS);
23468 if (isAllOnesConstant(Mask))
23469 return EmitTruncSStore(IsSigned, Chain, dl, DataToTruncate, Addr, MemVT,
23470 MemIntr->getMemOperand(), DAG);
23471
23472 MVT MaskVT = MVT::getVectorVT(MVT::i1, MemVT.getVectorNumElements());
23473 SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
23474
23475 return EmitMaskedTruncSStore(IsSigned, Chain, dl, DataToTruncate, Addr,
23476 VMask, MemVT, MemIntr->getMemOperand(), DAG);
23477 }
23478 default:
23479 llvm_unreachable("Unsupported truncstore intrinsic")::llvm::llvm_unreachable_internal("Unsupported truncstore intrinsic"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 23479)
;
23480 }
23481 }
23482 }
23483}
23484
23485SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
23486 SelectionDAG &DAG) const {
23487 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
23488 MFI.setReturnAddressIsTaken(true);
23489
23490 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
23491 return SDValue();
23492
23493 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
23494 SDLoc dl(Op);
23495 EVT PtrVT = getPointerTy(DAG.getDataLayout());
23496
23497 if (Depth > 0) {
23498 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
23499 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
23500 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
23501 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
23502 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
23503 MachinePointerInfo());
23504 }
23505
23506 // Just load the return address.
23507 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
23508 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
23509 MachinePointerInfo());
23510}
23511
23512SDValue X86TargetLowering::LowerADDROFRETURNADDR(SDValue Op,
23513 SelectionDAG &DAG) const {
23514 DAG.getMachineFunction().getFrameInfo().setReturnAddressIsTaken(true);
23515 return getReturnAddressFrameIndex(DAG);
23516}
23517
23518SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
23519 MachineFunction &MF = DAG.getMachineFunction();
23520 MachineFrameInfo &MFI = MF.getFrameInfo();
23521 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
23522 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
23523 EVT VT = Op.getValueType();
23524
23525 MFI.setFrameAddressIsTaken(true);
23526
23527 if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
23528 // Depth > 0 makes no sense on targets which use Windows unwind codes. It
23529 // is not possible to crawl up the stack without looking at the unwind codes
23530 // simultaneously.
23531 int FrameAddrIndex = FuncInfo->getFAIndex();
23532 if (!FrameAddrIndex) {
23533 // Set up a frame object for the return address.
23534 unsigned SlotSize = RegInfo->getSlotSize();
23535 FrameAddrIndex = MF.getFrameInfo().CreateFixedObject(
23536 SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
23537 FuncInfo->setFAIndex(FrameAddrIndex);
23538 }
23539 return DAG.getFrameIndex(FrameAddrIndex, VT);
23540 }
23541
23542 unsigned FrameReg =
23543 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
23544 SDLoc dl(Op); // FIXME probably not meaningful
23545 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
23546 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||((((FrameReg == X86::RBP && VT == MVT::i64) || (FrameReg
== X86::EBP && VT == MVT::i32)) && "Invalid Frame Register!"
) ? static_cast<void> (0) : __assert_fail ("((FrameReg == X86::RBP && VT == MVT::i64) || (FrameReg == X86::EBP && VT == MVT::i32)) && \"Invalid Frame Register!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 23548, __PRETTY_FUNCTION__))
23547 (FrameReg == X86::EBP && VT == MVT::i32)) &&((((FrameReg == X86::RBP && VT == MVT::i64) || (FrameReg
== X86::EBP && VT == MVT::i32)) && "Invalid Frame Register!"
) ? static_cast<void> (0) : __assert_fail ("((FrameReg == X86::RBP && VT == MVT::i64) || (FrameReg == X86::EBP && VT == MVT::i32)) && \"Invalid Frame Register!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 23548, __PRETTY_FUNCTION__))
23548 "Invalid Frame Register!")((((FrameReg == X86::RBP && VT == MVT::i64) || (FrameReg
== X86::EBP && VT == MVT::i32)) && "Invalid Frame Register!"
) ? static_cast<void> (0) : __assert_fail ("((FrameReg == X86::RBP && VT == MVT::i64) || (FrameReg == X86::EBP && VT == MVT::i32)) && \"Invalid Frame Register!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 23548, __PRETTY_FUNCTION__))
;
23549 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
23550 while (Depth--)
23551 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
23552 MachinePointerInfo());
23553 return FrameAddr;
23554}
23555
23556// FIXME? Maybe this could be a TableGen attribute on some registers and
23557// this table could be generated automatically from RegInfo.
23558unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
23559 SelectionDAG &DAG) const {
23560 const TargetFrameLowering &TFI = *Subtarget.getFrameLowering();
23561 const MachineFunction &MF = DAG.getMachineFunction();
23562
23563 unsigned Reg = StringSwitch<unsigned>(RegName)
23564 .Case("esp", X86::ESP)
23565 .Case("rsp", X86::RSP)
23566 .Case("ebp", X86::EBP)
23567 .Case("rbp", X86::RBP)
23568 .Default(0);
23569
23570 if (Reg == X86::EBP || Reg == X86::RBP) {
23571 if (!TFI.hasFP(MF))
23572 report_fatal_error("register " + StringRef(RegName) +
23573 " is allocatable: function has no frame pointer");
23574#ifndef NDEBUG
23575 else {
23576 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
23577 unsigned FrameReg =
23578 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
23579 assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&(((FrameReg == X86::EBP || FrameReg == X86::RBP) && "Invalid Frame Register!"
) ? static_cast<void> (0) : __assert_fail ("(FrameReg == X86::EBP || FrameReg == X86::RBP) && \"Invalid Frame Register!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 23580, __PRETTY_FUNCTION__))
23580 "Invalid Frame Register!")(((FrameReg == X86::EBP || FrameReg == X86::RBP) && "Invalid Frame Register!"
) ? static_cast<void> (0) : __assert_fail ("(FrameReg == X86::EBP || FrameReg == X86::RBP) && \"Invalid Frame Register!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 23580, __PRETTY_FUNCTION__))
;
23581 }
23582#endif
23583 }
23584
23585 if (Reg)
23586 return Reg;
23587
23588 report_fatal_error("Invalid register name global variable");
23589}
23590
23591SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
23592 SelectionDAG &DAG) const {
23593 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
23594 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
23595}
23596
23597unsigned X86TargetLowering::getExceptionPointerRegister(
23598 const Constant *PersonalityFn) const {
23599 if (classifyEHPersonality(PersonalityFn) == EHPersonality::CoreCLR)
23600 return Subtarget.isTarget64BitLP64() ? X86::RDX : X86::EDX;
23601
23602 return Subtarget.isTarget64BitLP64() ? X86::RAX : X86::EAX;
23603}
23604
23605unsigned X86TargetLowering::getExceptionSelectorRegister(
23606 const Constant *PersonalityFn) const {
23607 // Funclet personalities don't use selectors (the runtime does the selection).
23608 assert(!isFuncletEHPersonality(classifyEHPersonality(PersonalityFn)))((!isFuncletEHPersonality(classifyEHPersonality(PersonalityFn
))) ? static_cast<void> (0) : __assert_fail ("!isFuncletEHPersonality(classifyEHPersonality(PersonalityFn))"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 23608, __PRETTY_FUNCTION__))
;
23609 return Subtarget.isTarget64BitLP64() ? X86::RDX : X86::EDX;
23610}
23611
23612bool X86TargetLowering::needsFixedCatchObjects() const {
23613 return Subtarget.isTargetWin64();
23614}
23615
23616SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
23617 SDValue Chain = Op.getOperand(0);
23618 SDValue Offset = Op.getOperand(1);
23619 SDValue Handler = Op.getOperand(2);
23620 SDLoc dl (Op);
23621
23622 EVT PtrVT = getPointerTy(DAG.getDataLayout());
23623 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
23624 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
23625 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||((((FrameReg == X86::RBP && PtrVT == MVT::i64) || (FrameReg
== X86::EBP && PtrVT == MVT::i32)) && "Invalid Frame Register!"
) ? static_cast<void> (0) : __assert_fail ("((FrameReg == X86::RBP && PtrVT == MVT::i64) || (FrameReg == X86::EBP && PtrVT == MVT::i32)) && \"Invalid Frame Register!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 23627, __PRETTY_FUNCTION__))
23626 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&((((FrameReg == X86::RBP && PtrVT == MVT::i64) || (FrameReg
== X86::EBP && PtrVT == MVT::i32)) && "Invalid Frame Register!"
) ? static_cast<void> (0) : __assert_fail ("((FrameReg == X86::RBP && PtrVT == MVT::i64) || (FrameReg == X86::EBP && PtrVT == MVT::i32)) && \"Invalid Frame Register!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 23627, __PRETTY_FUNCTION__))
23627 "Invalid Frame Register!")((((FrameReg == X86::RBP && PtrVT == MVT::i64) || (FrameReg
== X86::EBP && PtrVT == MVT::i32)) && "Invalid Frame Register!"
) ? static_cast<void> (0) : __assert_fail ("((FrameReg == X86::RBP && PtrVT == MVT::i64) || (FrameReg == X86::EBP && PtrVT == MVT::i32)) && \"Invalid Frame Register!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 23627, __PRETTY_FUNCTION__))
;
23628 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
23629 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
23630
23631 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
23632 DAG.getIntPtrConstant(RegInfo->getSlotSize(),
23633 dl));
23634 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
23635 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo());
23636 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
23637
23638 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
23639 DAG.getRegister(StoreAddrReg, PtrVT));
23640}
23641
23642SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
23643 SelectionDAG &DAG) const {
23644 SDLoc DL(Op);
23645 // If the subtarget is not 64bit, we may need the global base reg
23646 // after isel expand pseudo, i.e., after CGBR pass ran.
23647 // Therefore, ask for the GlobalBaseReg now, so that the pass
23648 // inserts the code for us in case we need it.
23649 // Otherwise, we will end up in a situation where we will
23650 // reference a virtual register that is not defined!
23651 if (!Subtarget.is64Bit()) {
23652 const X86InstrInfo *TII = Subtarget.getInstrInfo();
23653 (void)TII->getGlobalBaseReg(&DAG.getMachineFunction());
23654 }
23655 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
23656 DAG.getVTList(MVT::i32, MVT::Other),
23657 Op.getOperand(0), Op.getOperand(1));
23658}
23659
23660SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
23661 SelectionDAG &DAG) const {
23662 SDLoc DL(Op);
23663 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
23664 Op.getOperand(0), Op.getOperand(1));
23665}
23666
23667SDValue X86TargetLowering::lowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
23668 SelectionDAG &DAG) const {
23669 SDLoc DL(Op);
23670 return DAG.getNode(X86ISD::EH_SJLJ_SETUP_DISPATCH, DL, MVT::Other,
23671 Op.getOperand(0));
23672}
23673
23674static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
23675 return Op.getOperand(0);
23676}
23677
23678SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
23679 SelectionDAG &DAG) const {
23680 SDValue Root = Op.getOperand(0);
23681 SDValue Trmp = Op.getOperand(1); // trampoline
23682 SDValue FPtr = Op.getOperand(2); // nested function
23683 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
23684 SDLoc dl (Op);
23685
23686 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
23687 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
23688
23689 if (Subtarget.is64Bit()) {
23690 SDValue OutChains[6];
23691
23692 // Large code-model.
23693 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
23694 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
23695
23696 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
23697 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
23698
23699 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
23700
23701 // Load the pointer to the nested function into R11.
23702 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
23703 SDValue Addr = Trmp;
23704 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
23705 Addr, MachinePointerInfo(TrmpAddr));
23706
23707 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
23708 DAG.getConstant(2, dl, MVT::i64));
23709 OutChains[1] =
23710 DAG.getStore(Root, dl, FPtr, Addr, MachinePointerInfo(TrmpAddr, 2),
23711 /* Alignment = */ 2);
23712
23713 // Load the 'nest' parameter value into R10.
23714 // R10 is specified in X86CallingConv.td
23715 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
23716 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
23717 DAG.getConstant(10, dl, MVT::i64));
23718 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
23719 Addr, MachinePointerInfo(TrmpAddr, 10));
23720
23721 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
23722 DAG.getConstant(12, dl, MVT::i64));
23723 OutChains[3] =
23724 DAG.getStore(Root, dl, Nest, Addr, MachinePointerInfo(TrmpAddr, 12),
23725 /* Alignment = */ 2);
23726
23727 // Jump to the nested function.
23728 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
23729 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
23730 DAG.getConstant(20, dl, MVT::i64));
23731 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
23732 Addr, MachinePointerInfo(TrmpAddr, 20));
23733
23734 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
23735 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
23736 DAG.getConstant(22, dl, MVT::i64));
23737 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
23738 Addr, MachinePointerInfo(TrmpAddr, 22));
23739
23740 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
23741 } else {
23742 const Function *Func =
23743 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
23744 CallingConv::ID CC = Func->getCallingConv();
23745 unsigned NestReg;
23746
23747 switch (CC) {
23748 default:
23749 llvm_unreachable("Unsupported calling convention")::llvm::llvm_unreachable_internal("Unsupported calling convention"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 23749)
;
23750 case CallingConv::C:
23751 case CallingConv::X86_StdCall: {
23752 // Pass 'nest' parameter in ECX.
23753 // Must be kept in sync with X86CallingConv.td
23754 NestReg = X86::ECX;
23755
23756 // Check that ECX wasn't needed by an 'inreg' parameter.
23757 FunctionType *FTy = Func->getFunctionType();
23758 const AttributeList &Attrs = Func->getAttributes();
23759
23760 if (!Attrs.isEmpty() && !Func->isVarArg()) {
23761 unsigned InRegCount = 0;
23762 unsigned Idx = 1;
23763
23764 for (FunctionType::param_iterator I = FTy->param_begin(),
23765 E = FTy->param_end(); I != E; ++I, ++Idx)
23766 if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
23767 auto &DL = DAG.getDataLayout();
23768 // FIXME: should only count parameters that are lowered to integers.
23769 InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
23770 }
23771
23772 if (InRegCount > 2) {
23773 report_fatal_error("Nest register in use - reduce number of inreg"
23774 " parameters!");
23775 }
23776 }
23777 break;
23778 }
23779 case CallingConv::X86_FastCall:
23780 case CallingConv::X86_ThisCall:
23781 case CallingConv::Fast:
23782 // Pass 'nest' parameter in EAX.
23783 // Must be kept in sync with X86CallingConv.td
23784 NestReg = X86::EAX;
23785 break;
23786 }
23787
23788 SDValue OutChains[4];
23789 SDValue Addr, Disp;
23790
23791 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
23792 DAG.getConstant(10, dl, MVT::i32));
23793 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
23794
23795 // This is storing the opcode for MOV32ri.
23796 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
23797 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
23798 OutChains[0] =
23799 DAG.getStore(Root, dl, DAG.getConstant(MOV32ri | N86Reg, dl, MVT::i8),
23800 Trmp, MachinePointerInfo(TrmpAddr));
23801
23802 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
23803 DAG.getConstant(1, dl, MVT::i32));
23804 OutChains[1] =
23805 DAG.getStore(Root, dl, Nest, Addr, MachinePointerInfo(TrmpAddr, 1),
23806 /* Alignment = */ 1);
23807
23808 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
23809 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
23810 DAG.getConstant(5, dl, MVT::i32));
23811 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
23812 Addr, MachinePointerInfo(TrmpAddr, 5),
23813 /* Alignment = */ 1);
23814
23815 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
23816 DAG.getConstant(6, dl, MVT::i32));
23817 OutChains[3] =
23818 DAG.getStore(Root, dl, Disp, Addr, MachinePointerInfo(TrmpAddr, 6),
23819 /* Alignment = */ 1);
23820
23821 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
23822 }
23823}
23824
23825SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
23826 SelectionDAG &DAG) const {
23827 /*
23828 The rounding mode is in bits 11:10 of FPSR, and has the following
23829 settings:
23830 00 Round to nearest
23831 01 Round to -inf
23832 10 Round to +inf
23833 11 Round to 0
23834
23835 FLT_ROUNDS, on the other hand, expects the following:
23836 -1 Undefined
23837 0 Round to 0
23838 1 Round to nearest
23839 2 Round to +inf
23840 3 Round to -inf
23841
23842 To perform the conversion, we do:
23843 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
23844 */
23845
23846 MachineFunction &MF = DAG.getMachineFunction();
23847 const TargetFrameLowering &TFI = *Subtarget.getFrameLowering();
23848 unsigned StackAlignment = TFI.getStackAlignment();
23849 MVT VT = Op.getSimpleValueType();
23850 SDLoc DL(Op);
23851
23852 // Save FP Control Word to stack slot
23853 int SSFI = MF.getFrameInfo().CreateStackObject(2, StackAlignment, false);
23854 SDValue StackSlot =
23855 DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
23856
23857 MachineMemOperand *MMO =
23858 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
23859 MachineMemOperand::MOStore, 2, 2);
23860
23861 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
23862 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
23863 DAG.getVTList(MVT::Other),
23864 Ops, MVT::i16, MMO);
23865
23866 // Load FP Control Word from stack slot
23867 SDValue CWD =
23868 DAG.getLoad(MVT::i16, DL, Chain, StackSlot, MachinePointerInfo());
23869
23870 // Transform as necessary
23871 SDValue CWD1 =
23872 DAG.getNode(ISD::SRL, DL, MVT::i16,
23873 DAG.getNode(ISD::AND, DL, MVT::i16,
23874 CWD, DAG.getConstant(0x800, DL, MVT::i16)),
23875 DAG.getConstant(11, DL, MVT::i8));
23876 SDValue CWD2 =
23877 DAG.getNode(ISD::SRL, DL, MVT::i16,
23878 DAG.getNode(ISD::AND, DL, MVT::i16,
23879 CWD, DAG.getConstant(0x400, DL, MVT::i16)),
23880 DAG.getConstant(9, DL, MVT::i8));
23881
23882 SDValue RetVal =
23883 DAG.getNode(ISD::AND, DL, MVT::i16,
23884 DAG.getNode(ISD::ADD, DL, MVT::i16,
23885 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
23886 DAG.getConstant(1, DL, MVT::i16)),
23887 DAG.getConstant(3, DL, MVT::i16));
23888
23889 return DAG.getNode((VT.getSizeInBits() < 16 ?
23890 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
23891}
23892
23893// Split an unary integer op into 2 half sized ops.
23894static SDValue LowerVectorIntUnary(SDValue Op, SelectionDAG &DAG) {
23895 MVT VT = Op.getSimpleValueType();
23896 unsigned NumElems = VT.getVectorNumElements();
23897 unsigned SizeInBits = VT.getSizeInBits();
23898 MVT EltVT = VT.getVectorElementType();
23899 SDValue Src = Op.getOperand(0);
23900 assert(EltVT == Src.getSimpleValueType().getVectorElementType() &&((EltVT == Src.getSimpleValueType().getVectorElementType() &&
"Src and Op should have the same element type!") ? static_cast
<void> (0) : __assert_fail ("EltVT == Src.getSimpleValueType().getVectorElementType() && \"Src and Op should have the same element type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 23901, __PRETTY_FUNCTION__))
23901 "Src and Op should have the same element type!")((EltVT == Src.getSimpleValueType().getVectorElementType() &&
"Src and Op should have the same element type!") ? static_cast
<void> (0) : __assert_fail ("EltVT == Src.getSimpleValueType().getVectorElementType() && \"Src and Op should have the same element type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 23901, __PRETTY_FUNCTION__))
;
23902
23903 // Extract the Lo/Hi vectors
23904 SDLoc dl(Op);
23905 SDValue Lo = extractSubVector(Src, 0, DAG, dl, SizeInBits / 2);
23906 SDValue Hi = extractSubVector(Src, NumElems / 2, DAG, dl, SizeInBits / 2);
23907
23908 MVT NewVT = MVT::getVectorVT(EltVT, NumElems / 2);
23909 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
23910 DAG.getNode(Op.getOpcode(), dl, NewVT, Lo),
23911 DAG.getNode(Op.getOpcode(), dl, NewVT, Hi));
23912}
23913
23914// Decompose 256-bit ops into smaller 128-bit ops.
23915static SDValue Lower256IntUnary(SDValue Op, SelectionDAG &DAG) {
23916 assert(Op.getSimpleValueType().is256BitVector() &&((Op.getSimpleValueType().is256BitVector() && Op.getSimpleValueType
().isInteger() && "Only handle AVX 256-bit vector integer operation"
) ? static_cast<void> (0) : __assert_fail ("Op.getSimpleValueType().is256BitVector() && Op.getSimpleValueType().isInteger() && \"Only handle AVX 256-bit vector integer operation\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 23918, __PRETTY_FUNCTION__))
23917 Op.getSimpleValueType().isInteger() &&((Op.getSimpleValueType().is256BitVector() && Op.getSimpleValueType
().isInteger() && "Only handle AVX 256-bit vector integer operation"
) ? static_cast<void> (0) : __assert_fail ("Op.getSimpleValueType().is256BitVector() && Op.getSimpleValueType().isInteger() && \"Only handle AVX 256-bit vector integer operation\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 23918, __PRETTY_FUNCTION__))
23918 "Only handle AVX 256-bit vector integer operation")((Op.getSimpleValueType().is256BitVector() && Op.getSimpleValueType
().isInteger() && "Only handle AVX 256-bit vector integer operation"
) ? static_cast<void> (0) : __assert_fail ("Op.getSimpleValueType().is256BitVector() && Op.getSimpleValueType().isInteger() && \"Only handle AVX 256-bit vector integer operation\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 23918, __PRETTY_FUNCTION__))
;
23919 return LowerVectorIntUnary(Op, DAG);
23920}
23921
23922// Decompose 512-bit ops into smaller 256-bit ops.
23923static SDValue Lower512IntUnary(SDValue Op, SelectionDAG &DAG) {
23924 assert(Op.getSimpleValueType().is512BitVector() &&((Op.getSimpleValueType().is512BitVector() && Op.getSimpleValueType
().isInteger() && "Only handle AVX 512-bit vector integer operation"
) ? static_cast<void> (0) : __assert_fail ("Op.getSimpleValueType().is512BitVector() && Op.getSimpleValueType().isInteger() && \"Only handle AVX 512-bit vector integer operation\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 23926, __PRETTY_FUNCTION__))
23925 Op.getSimpleValueType().isInteger() &&((Op.getSimpleValueType().is512BitVector() && Op.getSimpleValueType
().isInteger() && "Only handle AVX 512-bit vector integer operation"
) ? static_cast<void> (0) : __assert_fail ("Op.getSimpleValueType().is512BitVector() && Op.getSimpleValueType().isInteger() && \"Only handle AVX 512-bit vector integer operation\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 23926, __PRETTY_FUNCTION__))
23926 "Only handle AVX 512-bit vector integer operation")((Op.getSimpleValueType().is512BitVector() && Op.getSimpleValueType
().isInteger() && "Only handle AVX 512-bit vector integer operation"
) ? static_cast<void> (0) : __assert_fail ("Op.getSimpleValueType().is512BitVector() && Op.getSimpleValueType().isInteger() && \"Only handle AVX 512-bit vector integer operation\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 23926, __PRETTY_FUNCTION__))
;
23927 return LowerVectorIntUnary(Op, DAG);
23928}
23929
23930/// Lower a vector CTLZ using native supported vector CTLZ instruction.
23931//
23932// i8/i16 vector implemented using dword LZCNT vector instruction
23933// ( sub(trunc(lzcnt(zext32(x)))) ). In case zext32(x) is illegal,
23934// split the vector, perform operation on it's Lo a Hi part and
23935// concatenate the results.
23936static SDValue LowerVectorCTLZ_AVX512CDI(SDValue Op, SelectionDAG &DAG,
23937 const X86Subtarget &Subtarget) {
23938 assert(Op.getOpcode() == ISD::CTLZ)((Op.getOpcode() == ISD::CTLZ) ? static_cast<void> (0) :
__assert_fail ("Op.getOpcode() == ISD::CTLZ", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 23938, __PRETTY_FUNCTION__))
;
23939 SDLoc dl(Op);
23940 MVT VT = Op.getSimpleValueType();
23941 MVT EltVT = VT.getVectorElementType();
23942 unsigned NumElems = VT.getVectorNumElements();
23943
23944 assert((EltVT == MVT::i8 || EltVT == MVT::i16) &&(((EltVT == MVT::i8 || EltVT == MVT::i16) && "Unsupported element type"
) ? static_cast<void> (0) : __assert_fail ("(EltVT == MVT::i8 || EltVT == MVT::i16) && \"Unsupported element type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 23945, __PRETTY_FUNCTION__))
23945 "Unsupported element type")(((EltVT == MVT::i8 || EltVT == MVT::i16) && "Unsupported element type"
) ? static_cast<void> (0) : __assert_fail ("(EltVT == MVT::i8 || EltVT == MVT::i16) && \"Unsupported element type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 23945, __PRETTY_FUNCTION__))
;
23946
23947 // Split vector, it's Lo and Hi parts will be handled in next iteration.
23948 if (NumElems > 16 ||
23949 (NumElems == 16 && !Subtarget.canExtendTo512DQ()))
23950 return LowerVectorIntUnary(Op, DAG);
23951
23952 MVT NewVT = MVT::getVectorVT(MVT::i32, NumElems);
23953 assert((NewVT.is256BitVector() || NewVT.is512BitVector()) &&(((NewVT.is256BitVector() || NewVT.is512BitVector()) &&
"Unsupported value type for operation") ? static_cast<void
> (0) : __assert_fail ("(NewVT.is256BitVector() || NewVT.is512BitVector()) && \"Unsupported value type for operation\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 23954, __PRETTY_FUNCTION__))
23954 "Unsupported value type for operation")(((NewVT.is256BitVector() || NewVT.is512BitVector()) &&
"Unsupported value type for operation") ? static_cast<void
> (0) : __assert_fail ("(NewVT.is256BitVector() || NewVT.is512BitVector()) && \"Unsupported value type for operation\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 23954, __PRETTY_FUNCTION__))
;
23955
23956 // Use native supported vector instruction vplzcntd.
23957 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, NewVT, Op.getOperand(0));
23958 SDValue CtlzNode = DAG.getNode(ISD::CTLZ, dl, NewVT, Op);
23959 SDValue TruncNode = DAG.getNode(ISD::TRUNCATE, dl, VT, CtlzNode);
23960 SDValue Delta = DAG.getConstant(32 - EltVT.getSizeInBits(), dl, VT);
23961
23962 return DAG.getNode(ISD::SUB, dl, VT, TruncNode, Delta);
23963}
23964
23965// Lower CTLZ using a PSHUFB lookup table implementation.
23966static SDValue LowerVectorCTLZInRegLUT(SDValue Op, const SDLoc &DL,
23967 const X86Subtarget &Subtarget,
23968 SelectionDAG &DAG) {
23969 MVT VT = Op.getSimpleValueType();
23970 int NumElts = VT.getVectorNumElements();
23971 int NumBytes = NumElts * (VT.getScalarSizeInBits() / 8);
23972 MVT CurrVT = MVT::getVectorVT(MVT::i8, NumBytes);
23973
23974 // Per-nibble leading zero PSHUFB lookup table.
23975 const int LUT[16] = {/* 0 */ 4, /* 1 */ 3, /* 2 */ 2, /* 3 */ 2,
23976 /* 4 */ 1, /* 5 */ 1, /* 6 */ 1, /* 7 */ 1,
23977 /* 8 */ 0, /* 9 */ 0, /* a */ 0, /* b */ 0,
23978 /* c */ 0, /* d */ 0, /* e */ 0, /* f */ 0};
23979
23980 SmallVector<SDValue, 64> LUTVec;
23981 for (int i = 0; i < NumBytes; ++i)
23982 LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
23983 SDValue InRegLUT = DAG.getBuildVector(CurrVT, DL, LUTVec);
23984
23985 // Begin by bitcasting the input to byte vector, then split those bytes
23986 // into lo/hi nibbles and use the PSHUFB LUT to perform CLTZ on each of them.
23987 // If the hi input nibble is zero then we add both results together, otherwise
23988 // we just take the hi result (by masking the lo result to zero before the
23989 // add).
23990 SDValue Op0 = DAG.getBitcast(CurrVT, Op.getOperand(0));
23991 SDValue Zero = DAG.getConstant(0, DL, CurrVT);
23992
23993 SDValue NibbleShift = DAG.getConstant(0x4, DL, CurrVT);
23994 SDValue Lo = Op0;
23995 SDValue Hi = DAG.getNode(ISD::SRL, DL, CurrVT, Op0, NibbleShift);
23996 SDValue HiZ;
23997 if (CurrVT.is512BitVector()) {
23998 MVT MaskVT = MVT::getVectorVT(MVT::i1, CurrVT.getVectorNumElements());
23999 HiZ = DAG.getSetCC(DL, MaskVT, Hi, Zero, ISD::SETEQ);
24000 HiZ = DAG.getNode(ISD::SIGN_EXTEND, DL, CurrVT, HiZ);
24001 } else {
24002 HiZ = DAG.getSetCC(DL, CurrVT, Hi, Zero, ISD::SETEQ);
24003 }
24004
24005 Lo = DAG.getNode(X86ISD::PSHUFB, DL, CurrVT, InRegLUT, Lo);
24006 Hi = DAG.getNode(X86ISD::PSHUFB, DL, CurrVT, InRegLUT, Hi);
24007 Lo = DAG.getNode(ISD::AND, DL, CurrVT, Lo, HiZ);
24008 SDValue Res = DAG.getNode(ISD::ADD, DL, CurrVT, Lo, Hi);
24009
24010 // Merge result back from vXi8 back to VT, working on the lo/hi halves
24011 // of the current vector width in the same way we did for the nibbles.
24012 // If the upper half of the input element is zero then add the halves'
24013 // leading zero counts together, otherwise just use the upper half's.
24014 // Double the width of the result until we are at target width.
24015 while (CurrVT != VT) {
24016 int CurrScalarSizeInBits = CurrVT.getScalarSizeInBits();
24017 int CurrNumElts = CurrVT.getVectorNumElements();
24018 MVT NextSVT = MVT::getIntegerVT(CurrScalarSizeInBits * 2);
24019 MVT NextVT = MVT::getVectorVT(NextSVT, CurrNumElts / 2);
24020 SDValue Shift = DAG.getConstant(CurrScalarSizeInBits, DL, NextVT);
24021
24022 // Check if the upper half of the input element is zero.
24023 if (CurrVT.is512BitVector()) {
24024 MVT MaskVT = MVT::getVectorVT(MVT::i1, CurrVT.getVectorNumElements());
24025 HiZ = DAG.getSetCC(DL, MaskVT, DAG.getBitcast(CurrVT, Op0),
24026 DAG.getBitcast(CurrVT, Zero), ISD::SETEQ);
24027 HiZ = DAG.getNode(ISD::SIGN_EXTEND, DL, CurrVT, HiZ);
24028 } else {
24029 HiZ = DAG.getSetCC(DL, CurrVT, DAG.getBitcast(CurrVT, Op0),
24030 DAG.getBitcast(CurrVT, Zero), ISD::SETEQ);
24031 }
24032 HiZ = DAG.getBitcast(NextVT, HiZ);
24033
24034 // Move the upper/lower halves to the lower bits as we'll be extending to
24035 // NextVT. Mask the lower result to zero if HiZ is true and add the results
24036 // together.
24037 SDValue ResNext = Res = DAG.getBitcast(NextVT, Res);
24038 SDValue R0 = DAG.getNode(ISD::SRL, DL, NextVT, ResNext, Shift);
24039 SDValue R1 = DAG.getNode(ISD::SRL, DL, NextVT, HiZ, Shift);
24040 R1 = DAG.getNode(ISD::AND, DL, NextVT, ResNext, R1);
24041 Res = DAG.getNode(ISD::ADD, DL, NextVT, R0, R1);
24042 CurrVT = NextVT;
24043 }
24044
24045 return Res;
24046}
24047
24048static SDValue LowerVectorCTLZ(SDValue Op, const SDLoc &DL,
24049 const X86Subtarget &Subtarget,
24050 SelectionDAG &DAG) {
24051 MVT VT = Op.getSimpleValueType();
24052
24053 if (Subtarget.hasCDI() &&
24054 // vXi8 vectors need to be promoted to 512-bits for vXi32.
24055 (Subtarget.canExtendTo512DQ() || VT.getVectorElementType() != MVT::i8))
24056 return LowerVectorCTLZ_AVX512CDI(Op, DAG, Subtarget);
24057
24058 // Decompose 256-bit ops into smaller 128-bit ops.
24059 if (VT.is256BitVector() && !Subtarget.hasInt256())
24060 return Lower256IntUnary(Op, DAG);
24061
24062 // Decompose 512-bit ops into smaller 256-bit ops.
24063 if (VT.is512BitVector() && !Subtarget.hasBWI())
24064 return Lower512IntUnary(Op, DAG);
24065
24066 assert(Subtarget.hasSSSE3() && "Expected SSSE3 support for PSHUFB")((Subtarget.hasSSSE3() && "Expected SSSE3 support for PSHUFB"
) ? static_cast<void> (0) : __assert_fail ("Subtarget.hasSSSE3() && \"Expected SSSE3 support for PSHUFB\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 24066, __PRETTY_FUNCTION__))
;
24067 return LowerVectorCTLZInRegLUT(Op, DL, Subtarget, DAG);
24068}
24069
24070static SDValue LowerCTLZ(SDValue Op, const X86Subtarget &Subtarget,
24071 SelectionDAG &DAG) {
24072 MVT VT = Op.getSimpleValueType();
24073 MVT OpVT = VT;
24074 unsigned NumBits = VT.getSizeInBits();
24075 SDLoc dl(Op);
24076 unsigned Opc = Op.getOpcode();
24077
24078 if (VT.isVector())
24079 return LowerVectorCTLZ(Op, dl, Subtarget, DAG);
24080
24081 Op = Op.getOperand(0);
24082 if (VT == MVT::i8) {
24083 // Zero extend to i32 since there is not an i8 bsr.
24084 OpVT = MVT::i32;
24085 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
24086 }
24087
24088 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
24089 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
24090 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
24091
24092 if (Opc == ISD::CTLZ) {
24093 // If src is zero (i.e. bsr sets ZF), returns NumBits.
24094 SDValue Ops[] = {
24095 Op,
24096 DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
24097 DAG.getConstant(X86::COND_E, dl, MVT::i8),
24098 Op.getValue(1)
24099 };
24100 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
24101 }
24102
24103 // Finally xor with NumBits-1.
24104 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
24105 DAG.getConstant(NumBits - 1, dl, OpVT));
24106
24107 if (VT == MVT::i8)
24108 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
24109 return Op;
24110}
24111
24112static SDValue LowerCTTZ(SDValue Op, const X86Subtarget &Subtarget,
24113 SelectionDAG &DAG) {
24114 MVT VT = Op.getSimpleValueType();
24115 unsigned NumBits = VT.getScalarSizeInBits();
24116 SDValue N0 = Op.getOperand(0);
24117 SDLoc dl(Op);
24118
24119 assert(!VT.isVector() && Op.getOpcode() == ISD::CTTZ &&((!VT.isVector() && Op.getOpcode() == ISD::CTTZ &&
"Only scalar CTTZ requires custom lowering") ? static_cast<
void> (0) : __assert_fail ("!VT.isVector() && Op.getOpcode() == ISD::CTTZ && \"Only scalar CTTZ requires custom lowering\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 24120, __PRETTY_FUNCTION__))
24120 "Only scalar CTTZ requires custom lowering")((!VT.isVector() && Op.getOpcode() == ISD::CTTZ &&
"Only scalar CTTZ requires custom lowering") ? static_cast<
void> (0) : __assert_fail ("!VT.isVector() && Op.getOpcode() == ISD::CTTZ && \"Only scalar CTTZ requires custom lowering\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 24120, __PRETTY_FUNCTION__))
;
24121
24122 // Issue a bsf (scan bits forward) which also sets EFLAGS.
24123 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
24124 Op = DAG.getNode(X86ISD::BSF, dl, VTs, N0);
24125
24126 // If src is zero (i.e. bsf sets ZF), returns NumBits.
24127 SDValue Ops[] = {
24128 Op,
24129 DAG.getConstant(NumBits, dl, VT),
24130 DAG.getConstant(X86::COND_E, dl, MVT::i8),
24131 Op.getValue(1)
24132 };
24133 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
24134}
24135
24136/// Break a 256-bit integer operation into two new 128-bit ones and then
24137/// concatenate the result back.
24138static SDValue split256IntArith(SDValue Op, SelectionDAG &DAG) {
24139 MVT VT = Op.getSimpleValueType();
24140
24141 assert(VT.is256BitVector() && VT.isInteger() &&((VT.is256BitVector() && VT.isInteger() && "Unsupported value type for operation"
) ? static_cast<void> (0) : __assert_fail ("VT.is256BitVector() && VT.isInteger() && \"Unsupported value type for operation\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 24142, __PRETTY_FUNCTION__))
24142 "Unsupported value type for operation")((VT.is256BitVector() && VT.isInteger() && "Unsupported value type for operation"
) ? static_cast<void> (0) : __assert_fail ("VT.is256BitVector() && VT.isInteger() && \"Unsupported value type for operation\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 24142, __PRETTY_FUNCTION__))
;
24143
24144 unsigned NumElems = VT.getVectorNumElements();
24145 SDLoc dl(Op);
24146
24147 // Extract the LHS vectors
24148 SDValue LHS = Op.getOperand(0);
24149 SDValue LHS1 = extract128BitVector(LHS, 0, DAG, dl);
24150 SDValue LHS2 = extract128BitVector(LHS, NumElems / 2, DAG, dl);
24151
24152 // Extract the RHS vectors
24153 SDValue RHS = Op.getOperand(1);
24154 SDValue RHS1 = extract128BitVector(RHS, 0, DAG, dl);
24155 SDValue RHS2 = extract128BitVector(RHS, NumElems / 2, DAG, dl);
24156
24157 MVT EltVT = VT.getVectorElementType();
24158 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
24159
24160 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
24161 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
24162 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
24163}
24164
24165/// Break a 512-bit integer operation into two new 256-bit ones and then
24166/// concatenate the result back.
24167static SDValue split512IntArith(SDValue Op, SelectionDAG &DAG) {
24168 MVT VT = Op.getSimpleValueType();
24169
24170 assert(VT.is512BitVector() && VT.isInteger() &&((VT.is512BitVector() && VT.isInteger() && "Unsupported value type for operation"
) ? static_cast<void> (0) : __assert_fail ("VT.is512BitVector() && VT.isInteger() && \"Unsupported value type for operation\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 24171, __PRETTY_FUNCTION__))
24171 "Unsupported value type for operation")((VT.is512BitVector() && VT.isInteger() && "Unsupported value type for operation"
) ? static_cast<void> (0) : __assert_fail ("VT.is512BitVector() && VT.isInteger() && \"Unsupported value type for operation\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 24171, __PRETTY_FUNCTION__))
;
24172
24173 unsigned NumElems = VT.getVectorNumElements();
24174 SDLoc dl(Op);
24175
24176 // Extract the LHS vectors
24177 SDValue LHS = Op.getOperand(0);
24178 SDValue LHS1 = extract256BitVector(LHS, 0, DAG, dl);
24179 SDValue LHS2 = extract256BitVector(LHS, NumElems / 2, DAG, dl);
24180
24181 // Extract the RHS vectors
24182 SDValue RHS = Op.getOperand(1);
24183 SDValue RHS1 = extract256BitVector(RHS, 0, DAG, dl);
24184 SDValue RHS2 = extract256BitVector(RHS, NumElems / 2, DAG, dl);
24185
24186 MVT EltVT = VT.getVectorElementType();
24187 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
24188
24189 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
24190 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
24191 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
24192}
24193
24194static SDValue lowerAddSub(SDValue Op, SelectionDAG &DAG,
24195 const X86Subtarget &Subtarget) {
24196 MVT VT = Op.getSimpleValueType();
24197 if (VT == MVT::i16 || VT == MVT::i32)
24198 return lowerAddSubToHorizontalOp(Op, DAG, Subtarget);
24199
24200 if (VT.getScalarType() == MVT::i1)
24201 return DAG.getNode(ISD::XOR, SDLoc(Op), VT,
24202 Op.getOperand(0), Op.getOperand(1));
24203
24204 assert(Op.getSimpleValueType().is256BitVector() &&((Op.getSimpleValueType().is256BitVector() && Op.getSimpleValueType
().isInteger() && "Only handle AVX 256-bit vector integer operation"
) ? static_cast<void> (0) : __assert_fail ("Op.getSimpleValueType().is256BitVector() && Op.getSimpleValueType().isInteger() && \"Only handle AVX 256-bit vector integer operation\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 24206, __PRETTY_FUNCTION__))
24205 Op.getSimpleValueType().isInteger() &&((Op.getSimpleValueType().is256BitVector() && Op.getSimpleValueType
().isInteger() && "Only handle AVX 256-bit vector integer operation"
) ? static_cast<void> (0) : __assert_fail ("Op.getSimpleValueType().is256BitVector() && Op.getSimpleValueType().isInteger() && \"Only handle AVX 256-bit vector integer operation\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 24206, __PRETTY_FUNCTION__))
24206 "Only handle AVX 256-bit vector integer operation")((Op.getSimpleValueType().is256BitVector() && Op.getSimpleValueType
().isInteger() && "Only handle AVX 256-bit vector integer operation"
) ? static_cast<void> (0) : __assert_fail ("Op.getSimpleValueType().is256BitVector() && Op.getSimpleValueType().isInteger() && \"Only handle AVX 256-bit vector integer operation\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 24206, __PRETTY_FUNCTION__))
;
24207 return split256IntArith(Op, DAG);
24208}
24209
24210static SDValue LowerADDSAT_SUBSAT(SDValue Op, SelectionDAG &DAG,
24211 const X86Subtarget &Subtarget) {
24212 MVT VT = Op.getSimpleValueType();
24213 SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
24214 unsigned Opcode = Op.getOpcode();
24215 if (VT.getScalarType() == MVT::i1) {
24216 SDLoc dl(Op);
24217 switch (Opcode) {
24218 default: llvm_unreachable("Expected saturated arithmetic opcode")::llvm::llvm_unreachable_internal("Expected saturated arithmetic opcode"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 24218)
;
24219 case ISD::UADDSAT:
24220 case ISD::SADDSAT:
24221 // *addsat i1 X, Y --> X | Y
24222 return DAG.getNode(ISD::OR, dl, VT, X, Y);
24223 case ISD::USUBSAT:
24224 case ISD::SSUBSAT:
24225 // *subsat i1 X, Y --> X & ~Y
24226 return DAG.getNode(ISD::AND, dl, VT, X, DAG.getNOT(dl, Y, VT));
24227 }
24228 }
24229
24230 if (VT.is128BitVector()) {
24231 // Avoid the generic expansion with min/max if we don't have pminu*/pmaxu*.
24232 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24233 EVT SetCCResultType = TLI.getSetCCResultType(DAG.getDataLayout(),
24234 *DAG.getContext(), VT);
24235 SDLoc DL(Op);
24236 if (Opcode == ISD::UADDSAT && !TLI.isOperationLegal(ISD::UMIN, VT)) {
24237 // uaddsat X, Y --> (X >u (X + Y)) ? -1 : X + Y
24238 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, X, Y);
24239 SDValue Cmp = DAG.getSetCC(DL, SetCCResultType, X, Add, ISD::SETUGT);
24240 return DAG.getSelect(DL, VT, Cmp, DAG.getAllOnesConstant(DL, VT), Add);
24241 }
24242 if (Opcode == ISD::USUBSAT && !TLI.isOperationLegal(ISD::UMAX, VT)) {
24243 // usubsat X, Y --> (X >u Y) ? X - Y : 0
24244 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, X, Y);
24245 SDValue Cmp = DAG.getSetCC(DL, SetCCResultType, X, Y, ISD::SETUGT);
24246 return DAG.getSelect(DL, VT, Cmp, Sub, DAG.getConstant(0, DL, VT));
24247 }
24248 // Use default expansion.
24249 return SDValue();
24250 }
24251
24252 assert(Op.getSimpleValueType().is256BitVector() &&((Op.getSimpleValueType().is256BitVector() && Op.getSimpleValueType
().isInteger() && "Only handle AVX 256-bit vector integer operation"
) ? static_cast<void> (0) : __assert_fail ("Op.getSimpleValueType().is256BitVector() && Op.getSimpleValueType().isInteger() && \"Only handle AVX 256-bit vector integer operation\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 24254, __PRETTY_FUNCTION__))
24253 Op.getSimpleValueType().isInteger() &&((Op.getSimpleValueType().is256BitVector() && Op.getSimpleValueType
().isInteger() && "Only handle AVX 256-bit vector integer operation"
) ? static_cast<void> (0) : __assert_fail ("Op.getSimpleValueType().is256BitVector() && Op.getSimpleValueType().isInteger() && \"Only handle AVX 256-bit vector integer operation\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 24254, __PRETTY_FUNCTION__))
24254 "Only handle AVX 256-bit vector integer operation")((Op.getSimpleValueType().is256BitVector() && Op.getSimpleValueType
().isInteger() && "Only handle AVX 256-bit vector integer operation"
) ? static_cast<void> (0) : __assert_fail ("Op.getSimpleValueType().is256BitVector() && Op.getSimpleValueType().isInteger() && \"Only handle AVX 256-bit vector integer operation\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 24254, __PRETTY_FUNCTION__))
;
24255 return split256IntArith(Op, DAG);
24256}
24257
24258static SDValue LowerABS(SDValue Op, const X86Subtarget &Subtarget,
24259 SelectionDAG &DAG) {
24260 MVT VT = Op.getSimpleValueType();
24261 if (VT == MVT::i16 || VT == MVT::i32 || VT == MVT::i64) {
24262 // Since X86 does not have CMOV for 8-bit integer, we don't convert
24263 // 8-bit integer abs to NEG and CMOV.
24264 SDLoc DL(Op);
24265 SDValue N0 = Op.getOperand(0);
24266 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
24267 DAG.getConstant(0, DL, VT), N0);
24268 SDValue Ops[] = {N0, Neg, DAG.getConstant(X86::COND_GE, DL, MVT::i8),
24269 SDValue(Neg.getNode(), 1)};
24270 return DAG.getNode(X86ISD::CMOV, DL, VT, Ops);
24271 }
24272
24273 // ABS(vXi64 X) --> VPBLENDVPD(X, 0-X, X).
24274 if ((VT == MVT::v2i64 || VT == MVT::v4i64) && Subtarget.hasSSE41()) {
24275 SDLoc DL(Op);
24276 SDValue Src = Op.getOperand(0);
24277 SDValue Sub =
24278 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src);
24279 return DAG.getNode(X86ISD::BLENDV, DL, VT, Src, Sub, Src);
24280 }
24281
24282 if (VT.is256BitVector() && !Subtarget.hasInt256()) {
24283 assert(VT.isInteger() &&((VT.isInteger() && "Only handle AVX 256-bit vector integer operation"
) ? static_cast<void> (0) : __assert_fail ("VT.isInteger() && \"Only handle AVX 256-bit vector integer operation\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 24284, __PRETTY_FUNCTION__))
24284 "Only handle AVX 256-bit vector integer operation")((VT.isInteger() && "Only handle AVX 256-bit vector integer operation"
) ? static_cast<void> (0) : __assert_fail ("VT.isInteger() && \"Only handle AVX 256-bit vector integer operation\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 24284, __PRETTY_FUNCTION__))
;
24285 return Lower256IntUnary(Op, DAG);
24286 }
24287
24288 // Default to expand.
24289 return SDValue();
24290}
24291
24292static SDValue LowerMINMAX(SDValue Op, SelectionDAG &DAG) {
24293 MVT VT = Op.getSimpleValueType();
24294
24295 // For AVX1 cases, split to use legal ops (everything but v4i64).
24296 if (VT.getScalarType() != MVT::i64 && VT.is256BitVector())
24297 return split256IntArith(Op, DAG);
24298
24299 SDLoc DL(Op);
24300 unsigned Opcode = Op.getOpcode();
24301 SDValue N0 = Op.getOperand(0);
24302 SDValue N1 = Op.getOperand(1);
24303
24304 // For pre-SSE41, we can perform UMIN/UMAX v8i16 by flipping the signbit,
24305 // using the SMIN/SMAX instructions and flipping the signbit back.
24306 if (VT == MVT::v8i16) {
24307 assert((Opcode == ISD::UMIN || Opcode == ISD::UMAX) &&(((Opcode == ISD::UMIN || Opcode == ISD::UMAX) && "Unexpected MIN/MAX opcode"
) ? static_cast<void> (0) : __assert_fail ("(Opcode == ISD::UMIN || Opcode == ISD::UMAX) && \"Unexpected MIN/MAX opcode\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 24308, __PRETTY_FUNCTION__))
24308 "Unexpected MIN/MAX opcode")(((Opcode == ISD::UMIN || Opcode == ISD::UMAX) && "Unexpected MIN/MAX opcode"
) ? static_cast<void> (0) : __assert_fail ("(Opcode == ISD::UMIN || Opcode == ISD::UMAX) && \"Unexpected MIN/MAX opcode\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 24308, __PRETTY_FUNCTION__))
;
24309 SDValue Sign = DAG.getConstant(APInt::getSignedMinValue(16), DL, VT);
24310 N0 = DAG.getNode(ISD::XOR, DL, VT, N0, Sign);
24311 N1 = DAG.getNode(ISD::XOR, DL, VT, N1, Sign);
24312 Opcode = (Opcode == ISD::UMIN ? ISD::SMIN : ISD::SMAX);
24313 SDValue Result = DAG.getNode(Opcode, DL, VT, N0, N1);
24314 return DAG.getNode(ISD::XOR, DL, VT, Result, Sign);
24315 }
24316
24317 // Else, expand to a compare/select.
24318 ISD::CondCode CC;
24319 switch (Opcode) {
24320 case ISD::SMIN: CC = ISD::CondCode::SETLT; break;
24321 case ISD::SMAX: CC = ISD::CondCode::SETGT; break;
24322 case ISD::UMIN: CC = ISD::CondCode::SETULT; break;
24323 case ISD::UMAX: CC = ISD::CondCode::SETUGT; break;
24324 default: llvm_unreachable("Unknown MINMAX opcode")::llvm::llvm_unreachable_internal("Unknown MINMAX opcode", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 24324)
;
24325 }
24326
24327 SDValue Cond = DAG.getSetCC(DL, VT, N0, N1, CC);
24328 return DAG.getSelect(DL, VT, Cond, N0, N1);
24329}
24330
24331static SDValue LowerMUL(SDValue Op, const X86Subtarget &Subtarget,
24332 SelectionDAG &DAG) {
24333 SDLoc dl(Op);
24334 MVT VT = Op.getSimpleValueType();
24335
24336 if (VT.getScalarType() == MVT::i1)
24337 return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
24338
24339 // Decompose 256-bit ops into 128-bit ops.
24340 if (VT.is256BitVector() && !Subtarget.hasInt256())
24341 return split256IntArith(Op, DAG);
24342
24343 SDValue A = Op.getOperand(0);
24344 SDValue B = Op.getOperand(1);
24345
24346 // Lower v16i8/v32i8/v64i8 mul as sign-extension to v8i16/v16i16/v32i16
24347 // vector pairs, multiply and truncate.
24348 if (VT == MVT::v16i8 || VT == MVT::v32i8 || VT == MVT::v64i8) {
24349 unsigned NumElts = VT.getVectorNumElements();
24350
24351 if ((VT == MVT::v16i8 && Subtarget.hasInt256()) ||
24352 (VT == MVT::v32i8 && Subtarget.canExtendTo512BW())) {
24353 MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
24354 return DAG.getNode(
24355 ISD::TRUNCATE, dl, VT,
24356 DAG.getNode(ISD::MUL, dl, ExVT,
24357 DAG.getNode(ISD::ANY_EXTEND, dl, ExVT, A),
24358 DAG.getNode(ISD::ANY_EXTEND, dl, ExVT, B)));
24359 }
24360
24361 MVT ExVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
24362
24363 // Extract the lo/hi parts to any extend to i16.
24364 // We're going to mask off the low byte of each result element of the
24365 // pmullw, so it doesn't matter what's in the high byte of each 16-bit
24366 // element.
24367 SDValue Undef = DAG.getUNDEF(VT);
24368 SDValue ALo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, A, Undef));
24369 SDValue AHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, A, Undef));
24370
24371 SDValue BLo, BHi;
24372 if (ISD::isBuildVectorOfConstantSDNodes(B.getNode())) {
24373 // If the LHS is a constant, manually unpackl/unpackh.
24374 SmallVector<SDValue, 16> LoOps, HiOps;
24375 for (unsigned i = 0; i != NumElts; i += 16) {
24376 for (unsigned j = 0; j != 8; ++j) {
24377 LoOps.push_back(DAG.getAnyExtOrTrunc(B.getOperand(i + j), dl,
24378 MVT::i16));
24379 HiOps.push_back(DAG.getAnyExtOrTrunc(B.getOperand(i + j + 8), dl,
24380 MVT::i16));
24381 }
24382 }
24383
24384 BLo = DAG.getBuildVector(ExVT, dl, LoOps);
24385 BHi = DAG.getBuildVector(ExVT, dl, HiOps);
24386 } else {
24387 BLo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, B, Undef));
24388 BHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, B, Undef));
24389 }
24390
24391 // Multiply, mask the lower 8bits of the lo/hi results and pack.
24392 SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
24393 SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
24394 RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
24395 RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
24396 return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
24397 }
24398
24399 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
24400 if (VT == MVT::v4i32) {
24401 assert(Subtarget.hasSSE2() && !Subtarget.hasSSE41() &&((Subtarget.hasSSE2() && !Subtarget.hasSSE41() &&
"Should not custom lower when pmulld is available!") ? static_cast
<void> (0) : __assert_fail ("Subtarget.hasSSE2() && !Subtarget.hasSSE41() && \"Should not custom lower when pmulld is available!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 24402, __PRETTY_FUNCTION__))
24402 "Should not custom lower when pmulld is available!")((Subtarget.hasSSE2() && !Subtarget.hasSSE41() &&
"Should not custom lower when pmulld is available!") ? static_cast
<void> (0) : __assert_fail ("Subtarget.hasSSE2() && !Subtarget.hasSSE41() && \"Should not custom lower when pmulld is available!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 24402, __PRETTY_FUNCTION__))
;
24403
24404 // Extract the odd parts.
24405 static const int UnpackMask[] = { 1, -1, 3, -1 };
24406 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
24407 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
24408
24409 // Multiply the even parts.
24410 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64,
24411 DAG.getBitcast(MVT::v2i64, A),
24412 DAG.getBitcast(MVT::v2i64, B));
24413 // Now multiply odd parts.
24414 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64,
24415 DAG.getBitcast(MVT::v2i64, Aodds),
24416 DAG.getBitcast(MVT::v2i64, Bodds));
24417
24418 Evens = DAG.getBitcast(VT, Evens);
24419 Odds = DAG.getBitcast(VT, Odds);
24420
24421 // Merge the two vectors back together with a shuffle. This expands into 2
24422 // shuffles.
24423 static const int ShufMask[] = { 0, 4, 2, 6 };
24424 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
24425 }
24426
24427 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&(((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
"Only know how to lower V2I64/V4I64/V8I64 multiply") ? static_cast
<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 24428, __PRETTY_FUNCTION__))
24428 "Only know how to lower V2I64/V4I64/V8I64 multiply")(((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
"Only know how to lower V2I64/V4I64/V8I64 multiply") ? static_cast
<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 24428, __PRETTY_FUNCTION__))
;
24429 assert(!Subtarget.hasDQI() && "DQI should use MULLQ")((!Subtarget.hasDQI() && "DQI should use MULLQ") ? static_cast
<void> (0) : __assert_fail ("!Subtarget.hasDQI() && \"DQI should use MULLQ\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 24429, __PRETTY_FUNCTION__))
;
24430
24431 // Ahi = psrlqi(a, 32);
24432 // Bhi = psrlqi(b, 32);
24433 //
24434 // AloBlo = pmuludq(a, b);
24435 // AloBhi = pmuludq(a, Bhi);
24436 // AhiBlo = pmuludq(Ahi, b);
24437 //
24438 // Hi = psllqi(AloBhi + AhiBlo, 32);
24439 // return AloBlo + Hi;
24440 KnownBits AKnown = DAG.computeKnownBits(A);
24441 KnownBits BKnown = DAG.computeKnownBits(B);
24442
24443 APInt LowerBitsMask = APInt::getLowBitsSet(64, 32);
24444 bool ALoIsZero = LowerBitsMask.isSubsetOf(AKnown.Zero);
24445 bool BLoIsZero = LowerBitsMask.isSubsetOf(BKnown.Zero);
24446
24447 APInt UpperBitsMask = APInt::getHighBitsSet(64, 32);
24448 bool AHiIsZero = UpperBitsMask.isSubsetOf(AKnown.Zero);
24449 bool BHiIsZero = UpperBitsMask.isSubsetOf(BKnown.Zero);
24450
24451 SDValue Zero = DAG.getConstant(0, dl, VT);
24452
24453 // Only multiply lo/hi halves that aren't known to be zero.
24454 SDValue AloBlo = Zero;
24455 if (!ALoIsZero && !BLoIsZero)
24456 AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
24457
24458 SDValue AloBhi = Zero;
24459 if (!ALoIsZero && !BHiIsZero) {
24460 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
24461 AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
24462 }
24463
24464 SDValue AhiBlo = Zero;
24465 if (!AHiIsZero && !BLoIsZero) {
24466 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
24467 AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
24468 }
24469
24470 SDValue Hi = DAG.getNode(ISD::ADD, dl, VT, AloBhi, AhiBlo);
24471 Hi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Hi, 32, DAG);
24472
24473 return DAG.getNode(ISD::ADD, dl, VT, AloBlo, Hi);
24474}
24475
24476static SDValue LowerMULH(SDValue Op, const X86Subtarget &Subtarget,
24477 SelectionDAG &DAG) {
24478 SDLoc dl(Op);
24479 MVT VT = Op.getSimpleValueType();
24480 bool IsSigned = Op->getOpcode() == ISD::MULHS;
24481 unsigned NumElts = VT.getVectorNumElements();
24482 SDValue A = Op.getOperand(0);
24483 SDValue B = Op.getOperand(1);
24484
24485 // Decompose 256-bit ops into 128-bit ops.
24486 if (VT.is256BitVector() && !Subtarget.hasInt256())
24487 return split256IntArith(Op, DAG);
24488
24489 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32) {
24490 assert((VT == MVT::v4i32 && Subtarget.hasSSE2()) ||(((VT == MVT::v4i32 && Subtarget.hasSSE2()) || (VT ==
MVT::v8i32 && Subtarget.hasInt256()) || (VT == MVT::
v16i32 && Subtarget.hasAVX512())) ? static_cast<void
> (0) : __assert_fail ("(VT == MVT::v4i32 && Subtarget.hasSSE2()) || (VT == MVT::v8i32 && Subtarget.hasInt256()) || (VT == MVT::v16i32 && Subtarget.hasAVX512())"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 24492, __PRETTY_FUNCTION__))
24491 (VT == MVT::v8i32 && Subtarget.hasInt256()) ||(((VT == MVT::v4i32 && Subtarget.hasSSE2()) || (VT ==
MVT::v8i32 && Subtarget.hasInt256()) || (VT == MVT::
v16i32 && Subtarget.hasAVX512())) ? static_cast<void
> (0) : __assert_fail ("(VT == MVT::v4i32 && Subtarget.hasSSE2()) || (VT == MVT::v8i32 && Subtarget.hasInt256()) || (VT == MVT::v16i32 && Subtarget.hasAVX512())"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 24492, __PRETTY_FUNCTION__))
24492 (VT == MVT::v16i32 && Subtarget.hasAVX512()))(((VT == MVT::v4i32 && Subtarget.hasSSE2()) || (VT ==
MVT::v8i32 && Subtarget.hasInt256()) || (VT == MVT::
v16i32 && Subtarget.hasAVX512())) ? static_cast<void
> (0) : __assert_fail ("(VT == MVT::v4i32 && Subtarget.hasSSE2()) || (VT == MVT::v8i32 && Subtarget.hasInt256()) || (VT == MVT::v16i32 && Subtarget.hasAVX512())"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 24492, __PRETTY_FUNCTION__))
;
24493
24494 // PMULxD operations multiply each even value (starting at 0) of LHS with
24495 // the related value of RHS and produce a widen result.
24496 // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
24497 // => <2 x i64> <ae|cg>
24498 //
24499 // In other word, to have all the results, we need to perform two PMULxD:
24500 // 1. one with the even values.
24501 // 2. one with the odd values.
24502 // To achieve #2, with need to place the odd values at an even position.
24503 //
24504 // Place the odd value at an even position (basically, shift all values 1
24505 // step to the left):
24506 const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1,
24507 9, -1, 11, -1, 13, -1, 15, -1};
24508 // <a|b|c|d> => <b|undef|d|undef>
24509 SDValue Odd0 = DAG.getVectorShuffle(VT, dl, A, A,
24510 makeArrayRef(&Mask[0], NumElts));
24511 // <e|f|g|h> => <f|undef|h|undef>
24512 SDValue Odd1 = DAG.getVectorShuffle(VT, dl, B, B,
24513 makeArrayRef(&Mask[0], NumElts));
24514
24515 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
24516 // ints.
24517 MVT MulVT = MVT::getVectorVT(MVT::i64, NumElts / 2);
24518 unsigned Opcode =
24519 (IsSigned && Subtarget.hasSSE41()) ? X86ISD::PMULDQ : X86ISD::PMULUDQ;
24520 // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
24521 // => <2 x i64> <ae|cg>
24522 SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT,
24523 DAG.getBitcast(MulVT, A),
24524 DAG.getBitcast(MulVT, B)));
24525 // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
24526 // => <2 x i64> <bf|dh>
24527 SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT,
24528 DAG.getBitcast(MulVT, Odd0),
24529 DAG.getBitcast(MulVT, Odd1)));
24530
24531 // Shuffle it back into the right order.
24532 SmallVector<int, 16> ShufMask(NumElts);
24533 for (int i = 0; i != (int)NumElts; ++i)
24534 ShufMask[i] = (i / 2) * 2 + ((i % 2) * NumElts) + 1;
24535
24536 SDValue Res = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, ShufMask);
24537
24538 // If we have a signed multiply but no PMULDQ fix up the result of an
24539 // unsigned multiply.
24540 if (IsSigned && !Subtarget.hasSSE41()) {
24541 SDValue Zero = DAG.getConstant(0, dl, VT);
24542 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
24543 DAG.getSetCC(dl, VT, Zero, A, ISD::SETGT), B);
24544 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
24545 DAG.getSetCC(dl, VT, Zero, B, ISD::SETGT), A);
24546
24547 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
24548 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Fixup);
24549 }
24550
24551 return Res;
24552 }
24553
24554 // Only i8 vectors should need custom lowering after this.
24555 assert((VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget.hasInt256()) ||(((VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget
.hasInt256()) || (VT == MVT::v64i8 && Subtarget.hasBWI
())) && "Unsupported vector type") ? static_cast<void
> (0) : __assert_fail ("(VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget.hasInt256()) || (VT == MVT::v64i8 && Subtarget.hasBWI())) && \"Unsupported vector type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 24557, __PRETTY_FUNCTION__))
24556 (VT == MVT::v64i8 && Subtarget.hasBWI())) &&(((VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget
.hasInt256()) || (VT == MVT::v64i8 && Subtarget.hasBWI
())) && "Unsupported vector type") ? static_cast<void
> (0) : __assert_fail ("(VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget.hasInt256()) || (VT == MVT::v64i8 && Subtarget.hasBWI())) && \"Unsupported vector type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 24557, __PRETTY_FUNCTION__))
24557 "Unsupported vector type")(((VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget
.hasInt256()) || (VT == MVT::v64i8 && Subtarget.hasBWI
())) && "Unsupported vector type") ? static_cast<void
> (0) : __assert_fail ("(VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget.hasInt256()) || (VT == MVT::v64i8 && Subtarget.hasBWI())) && \"Unsupported vector type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 24557, __PRETTY_FUNCTION__))
;
24558
24559 // Lower v16i8/v32i8 as extension to v8i16/v16i16 vector pairs, multiply,
24560 // logical shift down the upper half and pack back to i8.
24561
24562 // With SSE41 we can use sign/zero extend, but for pre-SSE41 we unpack
24563 // and then ashr/lshr the upper bits down to the lower bits before multiply.
24564 unsigned ExAVX = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
24565
24566 if ((VT == MVT::v16i8 && Subtarget.hasInt256()) ||
24567 (VT == MVT::v32i8 && Subtarget.canExtendTo512BW())) {
24568 MVT ExVT = MVT::getVectorVT(MVT::i16, NumElts);
24569 SDValue ExA = DAG.getNode(ExAVX, dl, ExVT, A);
24570 SDValue ExB = DAG.getNode(ExAVX, dl, ExVT, B);
24571 SDValue Mul = DAG.getNode(ISD::MUL, dl, ExVT, ExA, ExB);
24572 Mul = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExVT, Mul, 8, DAG);
24573 return DAG.getNode(ISD::TRUNCATE, dl, VT, Mul);
24574 }
24575
24576 // For signed 512-bit vectors, split into 256-bit vectors to allow the
24577 // sign-extension to occur.
24578 if (VT == MVT::v64i8 && IsSigned)
24579 return split512IntArith(Op, DAG);
24580
24581 // Signed AVX2 implementation - extend xmm subvectors to ymm.
24582 if (VT == MVT::v32i8 && IsSigned) {
24583 MVT ExVT = MVT::v16i16;
24584 SDValue ALo = extract128BitVector(A, 0, DAG, dl);
24585 SDValue BLo = extract128BitVector(B, 0, DAG, dl);
24586 SDValue AHi = extract128BitVector(A, NumElts / 2, DAG, dl);
24587 SDValue BHi = extract128BitVector(B, NumElts / 2, DAG, dl);
24588 ALo = DAG.getNode(ExAVX, dl, ExVT, ALo);
24589 BLo = DAG.getNode(ExAVX, dl, ExVT, BLo);
24590 AHi = DAG.getNode(ExAVX, dl, ExVT, AHi);
24591 BHi = DAG.getNode(ExAVX, dl, ExVT, BHi);
24592 SDValue Lo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
24593 SDValue Hi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
24594 Lo = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExVT, Lo, 8, DAG);
24595 Hi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExVT, Hi, 8, DAG);
24596
24597 // Bitcast back to VT and then pack all the even elements from Lo and Hi.
24598 // Shuffle lowering should turn this into PACKUS+PERMQ
24599 Lo = DAG.getBitcast(VT, Lo);
24600 Hi = DAG.getBitcast(VT, Hi);
24601 return DAG.getVectorShuffle(VT, dl, Lo, Hi,
24602 { 0, 2, 4, 6, 8, 10, 12, 14,
24603 16, 18, 20, 22, 24, 26, 28, 30,
24604 32, 34, 36, 38, 40, 42, 44, 46,
24605 48, 50, 52, 54, 56, 58, 60, 62});
24606 }
24607
24608 // For signed v16i8 and all unsigned vXi8 we will unpack the low and high
24609 // half of each 128 bit lane to widen to a vXi16 type. Do the multiplies,
24610 // shift the results and pack the half lane results back together.
24611
24612 MVT ExVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
24613
24614 static const int PSHUFDMask[] = { 8, 9, 10, 11, 12, 13, 14, 15,
24615 -1, -1, -1, -1, -1, -1, -1, -1};
24616
24617 // Extract the lo parts and zero/sign extend to i16.
24618 // Only use SSE4.1 instructions for signed v16i8 where using unpack requires
24619 // shifts to sign extend. Using unpack for unsigned only requires an xor to
24620 // create zeros and a copy due to tied registers contraints pre-avx. But using
24621 // zero_extend_vector_inreg would require an additional pshufd for the high
24622 // part.
24623
24624 SDValue ALo, AHi;
24625 if (IsSigned && VT == MVT::v16i8 && Subtarget.hasSSE41()) {
24626 ALo = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, dl, ExVT, A);
24627
24628 AHi = DAG.getVectorShuffle(VT, dl, A, A, PSHUFDMask);
24629 AHi = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, dl, ExVT, AHi);
24630 } else if (IsSigned) {
24631 ALo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, DAG.getUNDEF(VT), A));
24632 AHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, DAG.getUNDEF(VT), A));
24633
24634 ALo = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, ALo, 8, DAG);
24635 AHi = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, AHi, 8, DAG);
24636 } else {
24637 ALo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, A,
24638 DAG.getConstant(0, dl, VT)));
24639 AHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, A,
24640 DAG.getConstant(0, dl, VT)));
24641 }
24642
24643 SDValue BLo, BHi;
24644 if (ISD::isBuildVectorOfConstantSDNodes(B.getNode())) {
24645 // If the LHS is a constant, manually unpackl/unpackh and extend.
24646 SmallVector<SDValue, 16> LoOps, HiOps;
24647 for (unsigned i = 0; i != NumElts; i += 16) {
24648 for (unsigned j = 0; j != 8; ++j) {
24649 SDValue LoOp = B.getOperand(i + j);
24650 SDValue HiOp = B.getOperand(i + j + 8);
24651
24652 if (IsSigned) {
24653 LoOp = DAG.getSExtOrTrunc(LoOp, dl, MVT::i16);
24654 HiOp = DAG.getSExtOrTrunc(HiOp, dl, MVT::i16);
24655 } else {
24656 LoOp = DAG.getZExtOrTrunc(LoOp, dl, MVT::i16);
24657 HiOp = DAG.getZExtOrTrunc(HiOp, dl, MVT::i16);
24658 }
24659
24660 LoOps.push_back(LoOp);
24661 HiOps.push_back(HiOp);
24662 }
24663 }
24664
24665 BLo = DAG.getBuildVector(ExVT, dl, LoOps);
24666 BHi = DAG.getBuildVector(ExVT, dl, HiOps);
24667 } else if (IsSigned && VT == MVT::v16i8 && Subtarget.hasSSE41()) {
24668 BLo = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, dl, ExVT, B);
24669
24670 BHi = DAG.getVectorShuffle(VT, dl, B, B, PSHUFDMask);
24671 BHi = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, dl, ExVT, BHi);
24672 } else if (IsSigned) {
24673 BLo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, DAG.getUNDEF(VT), B));
24674 BHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, DAG.getUNDEF(VT), B));
24675
24676 BLo = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, BLo, 8, DAG);
24677 BHi = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, BHi, 8, DAG);
24678 } else {
24679 BLo = DAG.getBitcast(ExVT, getUnpackl(DAG, dl, VT, B,
24680 DAG.getConstant(0, dl, VT)));
24681 BHi = DAG.getBitcast(ExVT, getUnpackh(DAG, dl, VT, B,
24682 DAG.getConstant(0, dl, VT)));
24683 }
24684
24685 // Multiply, lshr the upper 8bits to the lower 8bits of the lo/hi results and
24686 // pack back to vXi8.
24687 SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
24688 SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
24689 RLo = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExVT, RLo, 8, DAG);
24690 RHi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExVT, RHi, 8, DAG);
24691
24692 // Bitcast back to VT and then pack all the even elements from Lo and Hi.
24693 return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
24694}
24695
24696SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
24697 assert(Subtarget.isTargetWin64() && "Unexpected target")((Subtarget.isTargetWin64() && "Unexpected target") ?
static_cast<void> (0) : __assert_fail ("Subtarget.isTargetWin64() && \"Unexpected target\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 24697, __PRETTY_FUNCTION__))
;
24698 EVT VT = Op.getValueType();
24699 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&((VT.isInteger() && VT.getSizeInBits() == 128 &&
"Unexpected return type for lowering") ? static_cast<void
> (0) : __assert_fail ("VT.isInteger() && VT.getSizeInBits() == 128 && \"Unexpected return type for lowering\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 24700, __PRETTY_FUNCTION__))
24700 "Unexpected return type for lowering")((VT.isInteger() && VT.getSizeInBits() == 128 &&
"Unexpected return type for lowering") ? static_cast<void
> (0) : __assert_fail ("VT.isInteger() && VT.getSizeInBits() == 128 && \"Unexpected return type for lowering\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 24700, __PRETTY_FUNCTION__))
;
24701
24702 RTLIB::Libcall LC;
24703 bool isSigned;
24704 switch (Op->getOpcode()) {
24705 default: llvm_unreachable("Unexpected request for libcall!")::llvm::llvm_unreachable_internal("Unexpected request for libcall!"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 24705)
;
24706 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
24707 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
24708 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
24709 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
24710 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
24711 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
24712 }
24713
24714 SDLoc dl(Op);
24715 SDValue InChain = DAG.getEntryNode();
24716
24717 TargetLowering::ArgListTy Args;
24718 TargetLowering::ArgListEntry Entry;
24719 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
24720 EVT ArgVT = Op->getOperand(i).getValueType();
24721 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&((ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
"Unexpected argument type for lowering") ? static_cast<void
> (0) : __assert_fail ("ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 && \"Unexpected argument type for lowering\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 24722, __PRETTY_FUNCTION__))
24722 "Unexpected argument type for lowering")((ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
"Unexpected argument type for lowering") ? static_cast<void
> (0) : __assert_fail ("ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 && \"Unexpected argument type for lowering\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 24722, __PRETTY_FUNCTION__))
;
24723 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
24724 Entry.Node = StackPtr;
24725 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr,
24726 MachinePointerInfo(), /* Alignment = */ 16);
24727 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
24728 Entry.Ty = PointerType::get(ArgTy,0);
24729 Entry.IsSExt = false;
24730 Entry.IsZExt = false;
24731 Args.push_back(Entry);
24732 }
24733
24734 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
24735 getPointerTy(DAG.getDataLayout()));
24736
24737 TargetLowering::CallLoweringInfo CLI(DAG);
24738 CLI.setDebugLoc(dl)
24739 .setChain(InChain)
24740 .setLibCallee(
24741 getLibcallCallingConv(LC),
24742 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()), Callee,
24743 std::move(Args))
24744 .setInRegister()
24745 .setSExtResult(isSigned)
24746 .setZExtResult(!isSigned);
24747
24748 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
24749 return DAG.getBitcast(VT, CallInfo.first);
24750}
24751
24752// Return true if the required (according to Opcode) shift-imm form is natively
24753// supported by the Subtarget
24754static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget &Subtarget,
24755 unsigned Opcode) {
24756 if (VT.getScalarSizeInBits() < 16)
24757 return false;
24758
24759 if (VT.is512BitVector() && Subtarget.hasAVX512() &&
24760 (VT.getScalarSizeInBits() > 16 || Subtarget.hasBWI()))
24761 return true;
24762
24763 bool LShift = (VT.is128BitVector() && Subtarget.hasSSE2()) ||
24764 (VT.is256BitVector() && Subtarget.hasInt256());
24765
24766 bool AShift = LShift && (Subtarget.hasAVX512() ||
24767 (VT != MVT::v2i64 && VT != MVT::v4i64));
24768 return (Opcode == ISD::SRA) ? AShift : LShift;
24769}
24770
24771// The shift amount is a variable, but it is the same for all vector lanes.
24772// These instructions are defined together with shift-immediate.
24773static
24774bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget &Subtarget,
24775 unsigned Opcode) {
24776 return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
24777}
24778
24779// Return true if the required (according to Opcode) variable-shift form is
24780// natively supported by the Subtarget
24781static bool SupportedVectorVarShift(MVT VT, const X86Subtarget &Subtarget,
24782 unsigned Opcode) {
24783
24784 if (!Subtarget.hasInt256() || VT.getScalarSizeInBits() < 16)
24785 return false;
24786
24787 // vXi16 supported only on AVX-512, BWI
24788 if (VT.getScalarSizeInBits() == 16 && !Subtarget.hasBWI())
24789 return false;
24790
24791 if (Subtarget.hasAVX512())
24792 return true;
24793
24794 bool LShift = VT.is128BitVector() || VT.is256BitVector();
24795 bool AShift = LShift && VT != MVT::v2i64 && VT != MVT::v4i64;
24796 return (Opcode == ISD::SRA) ? AShift : LShift;
24797}
24798
24799static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
24800 const X86Subtarget &Subtarget) {
24801 MVT VT = Op.getSimpleValueType();
24802 SDLoc dl(Op);
24803 SDValue R = Op.getOperand(0);
24804 SDValue Amt = Op.getOperand(1);
24805 unsigned X86Opc = getTargetVShiftUniformOpcode(Op.getOpcode(), false);
24806
24807 auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
24808 assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type")(((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type"
) ? static_cast<void> (0) : __assert_fail ("(VT == MVT::v2i64 || VT == MVT::v4i64) && \"Unexpected SRA type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 24808, __PRETTY_FUNCTION__))
;
24809 MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
24810 SDValue Ex = DAG.getBitcast(ExVT, R);
24811
24812 // ashr(R, 63) === cmp_slt(R, 0)
24813 if (ShiftAmt == 63 && Subtarget.hasSSE42()) {
24814 assert((VT != MVT::v4i64 || Subtarget.hasInt256()) &&(((VT != MVT::v4i64 || Subtarget.hasInt256()) && "Unsupported PCMPGT op"
) ? static_cast<void> (0) : __assert_fail ("(VT != MVT::v4i64 || Subtarget.hasInt256()) && \"Unsupported PCMPGT op\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 24815, __PRETTY_FUNCTION__))
24815 "Unsupported PCMPGT op")(((VT != MVT::v4i64 || Subtarget.hasInt256()) && "Unsupported PCMPGT op"
) ? static_cast<void> (0) : __assert_fail ("(VT != MVT::v4i64 || Subtarget.hasInt256()) && \"Unsupported PCMPGT op\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 24815, __PRETTY_FUNCTION__))
;
24816 return DAG.getNode(X86ISD::PCMPGT, dl, VT, DAG.getConstant(0, dl, VT), R);
24817 }
24818
24819 if (ShiftAmt >= 32) {
24820 // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
24821 SDValue Upper =
24822 getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
24823 SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
24824 ShiftAmt - 32, DAG);
24825 if (VT == MVT::v2i64)
24826 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
24827 if (VT == MVT::v4i64)
24828 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
24829 {9, 1, 11, 3, 13, 5, 15, 7});
24830 } else {
24831 // SRA upper i32, SRL whole i64 and select lower i32.
24832 SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
24833 ShiftAmt, DAG);
24834 SDValue Lower =
24835 getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
24836 Lower = DAG.getBitcast(ExVT, Lower);
24837 if (VT == MVT::v2i64)
24838 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
24839 if (VT == MVT::v4i64)
24840 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
24841 {8, 1, 10, 3, 12, 5, 14, 7});
24842 }
24843 return DAG.getBitcast(VT, Ex);
24844 };
24845
24846 // Optimize shl/srl/sra with constant shift amount.
24847 APInt APIntShiftAmt;
24848 if (!isConstantSplat(Amt, APIntShiftAmt))
24849 return SDValue();
24850 uint64_t ShiftAmt = APIntShiftAmt.getZExtValue();
24851
24852 if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
24853 return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
24854
24855 // i64 SRA needs to be performed as partial shifts.
24856 if (((!Subtarget.hasXOP() && VT == MVT::v2i64) ||
24857 (Subtarget.hasInt256() && VT == MVT::v4i64)) &&
24858 Op.getOpcode() == ISD::SRA)
24859 return ArithmeticShiftRight64(ShiftAmt);
24860
24861 if (VT == MVT::v16i8 || (Subtarget.hasInt256() && VT == MVT::v32i8) ||
24862 VT == MVT::v64i8) {
24863 unsigned NumElts = VT.getVectorNumElements();
24864 MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
24865
24866 // Simple i8 add case
24867 if (Op.getOpcode() == ISD::SHL && ShiftAmt == 1)
24868 return DAG.getNode(ISD::ADD, dl, VT, R, R);
24869
24870 // ashr(R, 7) === cmp_slt(R, 0)
24871 if (Op.getOpcode() == ISD::SRA && ShiftAmt == 7) {
24872 SDValue Zeros = DAG.getConstant(0, dl, VT);
24873 if (VT.is512BitVector()) {
24874 assert(VT == MVT::v64i8 && "Unexpected element type!")((VT == MVT::v64i8 && "Unexpected element type!") ? static_cast
<void> (0) : __assert_fail ("VT == MVT::v64i8 && \"Unexpected element type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 24874, __PRETTY_FUNCTION__))
;
24875 SDValue CMP = DAG.getSetCC(dl, MVT::v64i1, Zeros, R, ISD::SETGT);
24876 return DAG.getNode(ISD::SIGN_EXTEND, dl, VT, CMP);
24877 }
24878 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
24879 }
24880
24881 // XOP can shift v16i8 directly instead of as shift v8i16 + mask.
24882 if (VT == MVT::v16i8 && Subtarget.hasXOP())
24883 return SDValue();
24884
24885 if (Op.getOpcode() == ISD::SHL) {
24886 // Make a large shift.
24887 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT, R,
24888 ShiftAmt, DAG);
24889 SHL = DAG.getBitcast(VT, SHL);
24890 // Zero out the rightmost bits.
24891 return DAG.getNode(ISD::AND, dl, VT, SHL,
24892 DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, VT));
24893 }
24894 if (Op.getOpcode() == ISD::SRL) {
24895 // Make a large shift.
24896 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT, R,
24897 ShiftAmt, DAG);
24898 SRL = DAG.getBitcast(VT, SRL);
24899 // Zero out the leftmost bits.
24900 return DAG.getNode(ISD::AND, dl, VT, SRL,
24901 DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, VT));
24902 }
24903 if (Op.getOpcode() == ISD::SRA) {
24904 // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
24905 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
24906
24907 SDValue Mask = DAG.getConstant(128 >> ShiftAmt, dl, VT);
24908 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
24909 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
24910 return Res;
24911 }
24912 llvm_unreachable("Unknown shift opcode.")::llvm::llvm_unreachable_internal("Unknown shift opcode.", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 24912)
;
24913 }
24914
24915 return SDValue();
24916}
24917
24918static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
24919 const X86Subtarget &Subtarget) {
24920 MVT VT = Op.getSimpleValueType();
24921 SDLoc dl(Op);
24922 SDValue R = Op.getOperand(0);
24923 SDValue Amt = Op.getOperand(1);
24924 unsigned Opcode = Op.getOpcode();
24925 unsigned X86OpcI = getTargetVShiftUniformOpcode(Opcode, false);
24926 unsigned X86OpcV = getTargetVShiftUniformOpcode(Opcode, true);
24927
24928 if (SDValue BaseShAmt = DAG.getSplatValue(Amt)) {
24929 if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Opcode)) {
24930 MVT EltVT = VT.getVectorElementType();
24931 assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!")((EltVT.bitsLE(MVT::i64) && "Unexpected element type!"
) ? static_cast<void> (0) : __assert_fail ("EltVT.bitsLE(MVT::i64) && \"Unexpected element type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 24931, __PRETTY_FUNCTION__))
;
24932 if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
24933 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
24934 else if (EltVT.bitsLT(MVT::i32))
24935 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
24936
24937 return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, Subtarget, DAG);
24938 }
24939
24940 // vXi8 shifts - shift as v8i16 + mask result.
24941 if (((VT == MVT::v16i8 && !Subtarget.canExtendTo512DQ()) ||
24942 (VT == MVT::v32i8 && !Subtarget.canExtendTo512BW()) ||
24943 VT == MVT::v64i8) &&
24944 !Subtarget.hasXOP()) {
24945 unsigned NumElts = VT.getVectorNumElements();
24946 MVT ExtVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
24947 if (SupportedVectorShiftWithBaseAmnt(ExtVT, Subtarget, Opcode)) {
24948 unsigned LogicalOp = (Opcode == ISD::SHL ? ISD::SHL : ISD::SRL);
24949 unsigned LogicalX86Op = getTargetVShiftUniformOpcode(LogicalOp, false);
24950 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
24951
24952 // Create the mask using vXi16 shifts. For shift-rights we need to move
24953 // the upper byte down before splatting the vXi8 mask.
24954 SDValue BitMask = DAG.getConstant(-1, dl, ExtVT);
24955 BitMask = getTargetVShiftNode(LogicalX86Op, dl, ExtVT, BitMask,
24956 BaseShAmt, Subtarget, DAG);
24957 if (Opcode != ISD::SHL)
24958 BitMask = getTargetVShiftByConstNode(LogicalX86Op, dl, ExtVT, BitMask,
24959 8, DAG);
24960 BitMask = DAG.getBitcast(VT, BitMask);
24961 BitMask = DAG.getVectorShuffle(VT, dl, BitMask, BitMask,
24962 SmallVector<int, 64>(NumElts, 0));
24963
24964 SDValue Res = getTargetVShiftNode(LogicalX86Op, dl, ExtVT,
24965 DAG.getBitcast(ExtVT, R), BaseShAmt,
24966 Subtarget, DAG);
24967 Res = DAG.getBitcast(VT, Res);
24968 Res = DAG.getNode(ISD::AND, dl, VT, Res, BitMask);
24969
24970 if (Opcode == ISD::SRA) {
24971 // ashr(R, Amt) === sub(xor(lshr(R, Amt), SignMask), SignMask)
24972 // SignMask = lshr(SignBit, Amt) - safe to do this with PSRLW.
24973 SDValue SignMask = DAG.getConstant(0x8080, dl, ExtVT);
24974 SignMask = getTargetVShiftNode(LogicalX86Op, dl, ExtVT, SignMask,
24975 BaseShAmt, Subtarget, DAG);
24976 SignMask = DAG.getBitcast(VT, SignMask);
24977 Res = DAG.getNode(ISD::XOR, dl, VT, Res, SignMask);
24978 Res = DAG.getNode(ISD::SUB, dl, VT, Res, SignMask);
24979 }
24980 return Res;
24981 }
24982 }
24983 }
24984
24985 // Check cases (mainly 32-bit) where i64 is expanded into high and low parts.
24986 if (VT == MVT::v2i64 && Amt.getOpcode() == ISD::BITCAST &&
24987 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
24988 Amt = Amt.getOperand(0);
24989 unsigned Ratio = 64 / Amt.getScalarValueSizeInBits();
24990 std::vector<SDValue> Vals(Ratio);
24991 for (unsigned i = 0; i != Ratio; ++i)
24992 Vals[i] = Amt.getOperand(i);
24993 for (unsigned i = Ratio, e = Amt.getNumOperands(); i != e; i += Ratio) {
24994 for (unsigned j = 0; j != Ratio; ++j)
24995 if (Vals[j] != Amt.getOperand(i + j))
24996 return SDValue();
24997 }
24998
24999 if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
25000 return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
25001 }
25002 return SDValue();
25003}
25004
25005// Convert a shift/rotate left amount to a multiplication scale factor.
25006static SDValue convertShiftLeftToScale(SDValue Amt, const SDLoc &dl,
25007 const X86Subtarget &Subtarget,
25008 SelectionDAG &DAG) {
25009 MVT VT = Amt.getSimpleValueType();
25010 if (!(VT == MVT::v8i16 || VT == MVT::v4i32 ||
25011 (Subtarget.hasInt256() && VT == MVT::v16i16) ||
25012 (!Subtarget.hasAVX512() && VT == MVT::v16i8)))
25013 return SDValue();
25014
25015 if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
25016 SmallVector<SDValue, 8> Elts;
25017 MVT SVT = VT.getVectorElementType();
25018 unsigned SVTBits = SVT.getSizeInBits();
25019 APInt One(SVTBits, 1);
25020 unsigned NumElems = VT.getVectorNumElements();
25021
25022 for (unsigned i = 0; i != NumElems; ++i) {
25023 SDValue Op = Amt->getOperand(i);
25024 if (Op->isUndef()) {
25025 Elts.push_back(Op);
25026 continue;
25027 }
25028
25029 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
25030 APInt C(SVTBits, ND->getAPIntValue().getZExtValue());
25031 uint64_t ShAmt = C.getZExtValue();
25032 if (ShAmt >= SVTBits) {
25033 Elts.push_back(DAG.getUNDEF(SVT));
25034 continue;
25035 }
25036 Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
25037 }
25038 return DAG.getBuildVector(VT, dl, Elts);
25039 }
25040
25041 // If the target doesn't support variable shifts, use either FP conversion
25042 // or integer multiplication to avoid shifting each element individually.
25043 if (VT == MVT::v4i32) {
25044 Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
25045 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt,
25046 DAG.getConstant(0x3f800000U, dl, VT));
25047 Amt = DAG.getBitcast(MVT::v4f32, Amt);
25048 return DAG.getNode(ISD::FP_TO_SINT, dl, VT, Amt);
25049 }
25050
25051 // AVX2 can more effectively perform this as a zext/trunc to/from v8i32.
25052 if (VT == MVT::v8i16 && !Subtarget.hasAVX2()) {
25053 SDValue Z = DAG.getConstant(0, dl, VT);
25054 SDValue Lo = DAG.getBitcast(MVT::v4i32, getUnpackl(DAG, dl, VT, Amt, Z));
25055 SDValue Hi = DAG.getBitcast(MVT::v4i32, getUnpackh(DAG, dl, VT, Amt, Z));
25056 Lo = convertShiftLeftToScale(Lo, dl, Subtarget, DAG);
25057 Hi = convertShiftLeftToScale(Hi, dl, Subtarget, DAG);
25058 if (Subtarget.hasSSE41())
25059 return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
25060
25061 return DAG.getVectorShuffle(VT, dl, DAG.getBitcast(VT, Lo),
25062 DAG.getBitcast(VT, Hi),
25063 {0, 2, 4, 6, 8, 10, 12, 14});
25064 }
25065
25066 return SDValue();
25067}
25068
25069static SDValue LowerShift(SDValue Op, const X86Subtarget &Subtarget,
25070 SelectionDAG &DAG) {
25071 MVT VT = Op.getSimpleValueType();
25072 SDLoc dl(Op);
25073 SDValue R = Op.getOperand(0);
25074 SDValue Amt = Op.getOperand(1);
25075 unsigned EltSizeInBits = VT.getScalarSizeInBits();
25076 bool ConstantAmt = ISD::isBuildVectorOfConstantSDNodes(Amt.getNode());
25077
25078 unsigned Opc = Op.getOpcode();
25079 unsigned X86OpcV = getTargetVShiftUniformOpcode(Opc, true);
25080 unsigned X86OpcI = getTargetVShiftUniformOpcode(Opc, false);
25081
25082 assert(VT.isVector() && "Custom lowering only for vector shifts!")((VT.isVector() && "Custom lowering only for vector shifts!"
) ? static_cast<void> (0) : __assert_fail ("VT.isVector() && \"Custom lowering only for vector shifts!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 25082, __PRETTY_FUNCTION__))
;
25083 assert(Subtarget.hasSSE2() && "Only custom lower when we have SSE2!")((Subtarget.hasSSE2() && "Only custom lower when we have SSE2!"
) ? static_cast<void> (0) : __assert_fail ("Subtarget.hasSSE2() && \"Only custom lower when we have SSE2!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 25083, __PRETTY_FUNCTION__))
;
25084
25085 if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
25086 return V;
25087
25088 if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
25089 return V;
25090
25091 if (SupportedVectorVarShift(VT, Subtarget, Opc))
25092 return Op;
25093
25094 // XOP has 128-bit variable logical/arithmetic shifts.
25095 // +ve/-ve Amt = shift left/right.
25096 if (Subtarget.hasXOP() && (VT == MVT::v2i64 || VT == MVT::v4i32 ||
25097 VT == MVT::v8i16 || VT == MVT::v16i8)) {
25098 if (Opc == ISD::SRL || Opc == ISD::SRA) {
25099 SDValue Zero = DAG.getConstant(0, dl, VT);
25100 Amt = DAG.getNode(ISD::SUB, dl, VT, Zero, Amt);
25101 }
25102 if (Opc == ISD::SHL || Opc == ISD::SRL)
25103 return DAG.getNode(X86ISD::VPSHL, dl, VT, R, Amt);
25104 if (Opc == ISD::SRA)
25105 return DAG.getNode(X86ISD::VPSHA, dl, VT, R, Amt);
25106 }
25107
25108 // 2i64 vector logical shifts can efficiently avoid scalarization - do the
25109 // shifts per-lane and then shuffle the partial results back together.
25110 if (VT == MVT::v2i64 && Opc != ISD::SRA) {
25111 // Splat the shift amounts so the scalar shifts above will catch it.
25112 SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
25113 SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
25114 SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
25115 SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
25116 return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
25117 }
25118
25119 // i64 vector arithmetic shift can be emulated with the transform:
25120 // M = lshr(SIGN_MASK, Amt)
25121 // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
25122 if ((VT == MVT::v2i64 || (VT == MVT::v4i64 && Subtarget.hasInt256())) &&
25123 Opc == ISD::SRA) {
25124 SDValue S = DAG.getConstant(APInt::getSignMask(64), dl, VT);
25125 SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
25126 R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
25127 R = DAG.getNode(ISD::XOR, dl, VT, R, M);
25128 R = DAG.getNode(ISD::SUB, dl, VT, R, M);
25129 return R;
25130 }
25131
25132 // If possible, lower this shift as a sequence of two shifts by
25133 // constant plus a BLENDing shuffle instead of scalarizing it.
25134 // Example:
25135 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
25136 //
25137 // Could be rewritten as:
25138 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
25139 //
25140 // The advantage is that the two shifts from the example would be
25141 // lowered as X86ISD::VSRLI nodes in parallel before blending.
25142 if (ConstantAmt && (VT == MVT::v8i16 || VT == MVT::v4i32 ||
25143 (VT == MVT::v16i16 && Subtarget.hasInt256()))) {
25144 SDValue Amt1, Amt2;
25145 unsigned NumElts = VT.getVectorNumElements();
25146 SmallVector<int, 8> ShuffleMask;
25147 for (unsigned i = 0; i != NumElts; ++i) {
25148 SDValue A = Amt->getOperand(i);
25149 if (A.isUndef()) {
25150 ShuffleMask.push_back(SM_SentinelUndef);
25151 continue;
25152 }
25153 if (!Amt1 || Amt1 == A) {
25154 ShuffleMask.push_back(i);
25155 Amt1 = A;
25156 continue;
25157 }
25158 if (!Amt2 || Amt2 == A) {
25159 ShuffleMask.push_back(i + NumElts);
25160 Amt2 = A;
25161 continue;
25162 }
25163 break;
25164 }
25165
25166 // Only perform this blend if we can perform it without loading a mask.
25167 if (ShuffleMask.size() == NumElts && Amt1 && Amt2 &&
25168 (VT != MVT::v16i16 ||
25169 is128BitLaneRepeatedShuffleMask(VT, ShuffleMask)) &&
25170 (VT == MVT::v4i32 || Subtarget.hasSSE41() || Opc != ISD::SHL ||
25171 canWidenShuffleElements(ShuffleMask))) {
25172 auto *Cst1 = dyn_cast<ConstantSDNode>(Amt1);
25173 auto *Cst2 = dyn_cast<ConstantSDNode>(Amt2);
25174 if (Cst1 && Cst2 && Cst1->getAPIntValue().ult(EltSizeInBits) &&
25175 Cst2->getAPIntValue().ult(EltSizeInBits)) {
25176 SDValue Shift1 = getTargetVShiftByConstNode(X86OpcI, dl, VT, R,
25177 Cst1->getZExtValue(), DAG);
25178 SDValue Shift2 = getTargetVShiftByConstNode(X86OpcI, dl, VT, R,
25179 Cst2->getZExtValue(), DAG);
25180 return DAG.getVectorShuffle(VT, dl, Shift1, Shift2, ShuffleMask);
25181 }
25182 }
25183 }
25184
25185 // If possible, lower this packed shift into a vector multiply instead of
25186 // expanding it into a sequence of scalar shifts.
25187 if (Opc == ISD::SHL)
25188 if (SDValue Scale = convertShiftLeftToScale(Amt, dl, Subtarget, DAG))
25189 return DAG.getNode(ISD::MUL, dl, VT, R, Scale);
25190
25191 // Constant ISD::SRL can be performed efficiently on vXi16 vectors as we
25192 // can replace with ISD::MULHU, creating scale factor from (NumEltBits - Amt).
25193 if (Opc == ISD::SRL && ConstantAmt &&
25194 (VT == MVT::v8i16 || (VT == MVT::v16i16 && Subtarget.hasInt256()))) {
25195 SDValue EltBits = DAG.getConstant(EltSizeInBits, dl, VT);
25196 SDValue RAmt = DAG.getNode(ISD::SUB, dl, VT, EltBits, Amt);
25197 if (SDValue Scale = convertShiftLeftToScale(RAmt, dl, Subtarget, DAG)) {
25198 SDValue Zero = DAG.getConstant(0, dl, VT);
25199 SDValue ZAmt = DAG.getSetCC(dl, VT, Amt, Zero, ISD::SETEQ);
25200 SDValue Res = DAG.getNode(ISD::MULHU, dl, VT, R, Scale);
25201 return DAG.getSelect(dl, VT, ZAmt, R, Res);
25202 }
25203 }
25204
25205 // Constant ISD::SRA can be performed efficiently on vXi16 vectors as we
25206 // can replace with ISD::MULHS, creating scale factor from (NumEltBits - Amt).
25207 // TODO: Special case handling for shift by 0/1, really we can afford either
25208 // of these cases in pre-SSE41/XOP/AVX512 but not both.
25209 if (Opc == ISD::SRA && ConstantAmt &&
25210 (VT == MVT::v8i16 || (VT == MVT::v16i16 && Subtarget.hasInt256())) &&
25211 ((Subtarget.hasSSE41() && !Subtarget.hasXOP() &&
25212 !Subtarget.hasAVX512()) ||
25213 DAG.isKnownNeverZero(Amt))) {
25214 SDValue EltBits = DAG.getConstant(EltSizeInBits, dl, VT);
25215 SDValue RAmt = DAG.getNode(ISD::SUB, dl, VT, EltBits, Amt);
25216 if (SDValue Scale = convertShiftLeftToScale(RAmt, dl, Subtarget, DAG)) {
25217 SDValue Amt0 =
25218 DAG.getSetCC(dl, VT, Amt, DAG.getConstant(0, dl, VT), ISD::SETEQ);
25219 SDValue Amt1 =
25220 DAG.getSetCC(dl, VT, Amt, DAG.getConstant(1, dl, VT), ISD::SETEQ);
25221 SDValue Sra1 =
25222 getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, 1, DAG);
25223 SDValue Res = DAG.getNode(ISD::MULHS, dl, VT, R, Scale);
25224 Res = DAG.getSelect(dl, VT, Amt0, R, Res);
25225 return DAG.getSelect(dl, VT, Amt1, Sra1, Res);
25226 }
25227 }
25228
25229 // v4i32 Non Uniform Shifts.
25230 // If the shift amount is constant we can shift each lane using the SSE2
25231 // immediate shifts, else we need to zero-extend each lane to the lower i64
25232 // and shift using the SSE2 variable shifts.
25233 // The separate results can then be blended together.
25234 if (VT == MVT::v4i32) {
25235 SDValue Amt0, Amt1, Amt2, Amt3;
25236 if (ConstantAmt) {
25237 Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
25238 Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
25239 Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
25240 Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
25241 } else {
25242 // The SSE2 shifts use the lower i64 as the same shift amount for
25243 // all lanes and the upper i64 is ignored. On AVX we're better off
25244 // just zero-extending, but for SSE just duplicating the top 16-bits is
25245 // cheaper and has the same effect for out of range values.
25246 if (Subtarget.hasAVX()) {
25247 SDValue Z = DAG.getConstant(0, dl, VT);
25248 Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
25249 Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
25250 Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
25251 Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
25252 } else {
25253 SDValue Amt01 = DAG.getBitcast(MVT::v8i16, Amt);
25254 SDValue Amt23 = DAG.getVectorShuffle(MVT::v8i16, dl, Amt01, Amt01,
25255 {4, 5, 6, 7, -1, -1, -1, -1});
25256 Amt0 = DAG.getVectorShuffle(MVT::v8i16, dl, Amt01, Amt01,
25257 {0, 1, 1, 1, -1, -1, -1, -1});
25258 Amt1 = DAG.getVectorShuffle(MVT::v8i16, dl, Amt01, Amt01,
25259 {2, 3, 3, 3, -1, -1, -1, -1});
25260 Amt2 = DAG.getVectorShuffle(MVT::v8i16, dl, Amt23, Amt23,
25261 {0, 1, 1, 1, -1, -1, -1, -1});
25262 Amt3 = DAG.getVectorShuffle(MVT::v8i16, dl, Amt23, Amt23,
25263 {2, 3, 3, 3, -1, -1, -1, -1});
25264 }
25265 }
25266
25267 unsigned ShOpc = ConstantAmt ? Opc : X86OpcV;
25268 SDValue R0 = DAG.getNode(ShOpc, dl, VT, R, DAG.getBitcast(VT, Amt0));
25269 SDValue R1 = DAG.getNode(ShOpc, dl, VT, R, DAG.getBitcast(VT, Amt1));
25270 SDValue R2 = DAG.getNode(ShOpc, dl, VT, R, DAG.getBitcast(VT, Amt2));
25271 SDValue R3 = DAG.getNode(ShOpc, dl, VT, R, DAG.getBitcast(VT, Amt3));
25272
25273 // Merge the shifted lane results optimally with/without PBLENDW.
25274 // TODO - ideally shuffle combining would handle this.
25275 if (Subtarget.hasSSE41()) {
25276 SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
25277 SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
25278 return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
25279 }
25280 SDValue R01 = DAG.getVectorShuffle(VT, dl, R0, R1, {0, -1, -1, 5});
25281 SDValue R23 = DAG.getVectorShuffle(VT, dl, R2, R3, {2, -1, -1, 7});
25282 return DAG.getVectorShuffle(VT, dl, R01, R23, {0, 3, 4, 7});
25283 }
25284
25285 // It's worth extending once and using the vXi16/vXi32 shifts for smaller
25286 // types, but without AVX512 the extra overheads to get from vXi8 to vXi32
25287 // make the existing SSE solution better.
25288 // NOTE: We honor prefered vector width before promoting to 512-bits.
25289 if ((Subtarget.hasInt256() && VT == MVT::v8i16) ||
25290 (Subtarget.canExtendTo512DQ() && VT == MVT::v16i16) ||
25291 (Subtarget.canExtendTo512DQ() && VT == MVT::v16i8) ||
25292 (Subtarget.canExtendTo512BW() && VT == MVT::v32i8) ||
25293 (Subtarget.hasBWI() && Subtarget.hasVLX() && VT == MVT::v16i8)) {
25294 assert((!Subtarget.hasBWI() || VT == MVT::v32i8 || VT == MVT::v16i8) &&(((!Subtarget.hasBWI() || VT == MVT::v32i8 || VT == MVT::v16i8
) && "Unexpected vector type") ? static_cast<void>
(0) : __assert_fail ("(!Subtarget.hasBWI() || VT == MVT::v32i8 || VT == MVT::v16i8) && \"Unexpected vector type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 25295, __PRETTY_FUNCTION__))
25295 "Unexpected vector type")(((!Subtarget.hasBWI() || VT == MVT::v32i8 || VT == MVT::v16i8
) && "Unexpected vector type") ? static_cast<void>
(0) : __assert_fail ("(!Subtarget.hasBWI() || VT == MVT::v32i8 || VT == MVT::v16i8) && \"Unexpected vector type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 25295, __PRETTY_FUNCTION__))
;
25296 MVT EvtSVT = Subtarget.hasBWI() ? MVT::i16 : MVT::i32;
25297 MVT ExtVT = MVT::getVectorVT(EvtSVT, VT.getVectorNumElements());
25298 unsigned ExtOpc = Opc == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
25299 R = DAG.getNode(ExtOpc, dl, ExtVT, R);
25300 Amt = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Amt);
25301 return DAG.getNode(ISD::TRUNCATE, dl, VT,
25302 DAG.getNode(Opc, dl, ExtVT, R, Amt));
25303 }
25304
25305 // Constant ISD::SRA/SRL can be performed efficiently on vXi8 vectors as we
25306 // extend to vXi16 to perform a MUL scale effectively as a MUL_LOHI.
25307 if (ConstantAmt && (Opc == ISD::SRA || Opc == ISD::SRL) &&
25308 (VT == MVT::v16i8 || VT == MVT::v64i8 ||
25309 (VT == MVT::v32i8 && Subtarget.hasInt256())) &&
25310 !Subtarget.hasXOP()) {
25311 int NumElts = VT.getVectorNumElements();
25312 SDValue Cst8 = DAG.getConstant(8, dl, MVT::i8);
25313
25314 // Extend constant shift amount to vXi16 (it doesn't matter if the type
25315 // isn't legal).
25316 MVT ExVT = MVT::getVectorVT(MVT::i16, NumElts);
25317 Amt = DAG.getZExtOrTrunc(Amt, dl, ExVT);
25318 Amt = DAG.getNode(ISD::SUB, dl, ExVT, DAG.getConstant(8, dl, ExVT), Amt);
25319 Amt = DAG.getNode(ISD::SHL, dl, ExVT, DAG.getConstant(1, dl, ExVT), Amt);
25320 assert(ISD::isBuildVectorOfConstantSDNodes(Amt.getNode()) &&((ISD::isBuildVectorOfConstantSDNodes(Amt.getNode()) &&
"Constant build vector expected") ? static_cast<void> (
0) : __assert_fail ("ISD::isBuildVectorOfConstantSDNodes(Amt.getNode()) && \"Constant build vector expected\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 25321, __PRETTY_FUNCTION__))
25321 "Constant build vector expected")((ISD::isBuildVectorOfConstantSDNodes(Amt.getNode()) &&
"Constant build vector expected") ? static_cast<void> (
0) : __assert_fail ("ISD::isBuildVectorOfConstantSDNodes(Amt.getNode()) && \"Constant build vector expected\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 25321, __PRETTY_FUNCTION__))
;
25322
25323 if (VT == MVT::v16i8 && Subtarget.hasInt256()) {
25324 R = Opc == ISD::SRA ? DAG.getSExtOrTrunc(R, dl, ExVT)
25325 : DAG.getZExtOrTrunc(R, dl, ExVT);
25326 R = DAG.getNode(ISD::MUL, dl, ExVT, R, Amt);
25327 R = DAG.getNode(X86ISD::VSRLI, dl, ExVT, R, Cst8);
25328 return DAG.getZExtOrTrunc(R, dl, VT);
25329 }
25330
25331 SmallVector<SDValue, 16> LoAmt, HiAmt;
25332 for (int i = 0; i != NumElts; i += 16) {
25333 for (int j = 0; j != 8; ++j) {
25334 LoAmt.push_back(Amt.getOperand(i + j));
25335 HiAmt.push_back(Amt.getOperand(i + j + 8));
25336 }
25337 }
25338
25339 MVT VT16 = MVT::getVectorVT(MVT::i16, NumElts / 2);
25340 SDValue LoA = DAG.getBuildVector(VT16, dl, LoAmt);
25341 SDValue HiA = DAG.getBuildVector(VT16, dl, HiAmt);
25342
25343 SDValue LoR = DAG.getBitcast(VT16, getUnpackl(DAG, dl, VT, R, R));
25344 SDValue HiR = DAG.getBitcast(VT16, getUnpackh(DAG, dl, VT, R, R));
25345 LoR = DAG.getNode(X86OpcI, dl, VT16, LoR, Cst8);
25346 HiR = DAG.getNode(X86OpcI, dl, VT16, HiR, Cst8);
25347 LoR = DAG.getNode(ISD::MUL, dl, VT16, LoR, LoA);
25348 HiR = DAG.getNode(ISD::MUL, dl, VT16, HiR, HiA);
25349 LoR = DAG.getNode(X86ISD::VSRLI, dl, VT16, LoR, Cst8);
25350 HiR = DAG.getNode(X86ISD::VSRLI, dl, VT16, HiR, Cst8);
25351 return DAG.getNode(X86ISD::PACKUS, dl, VT, LoR, HiR);
25352 }
25353
25354 if (VT == MVT::v16i8 ||
25355 (VT == MVT::v32i8 && Subtarget.hasInt256() && !Subtarget.hasXOP()) ||
25356 (VT == MVT::v64i8 && Subtarget.hasBWI())) {
25357 MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
25358
25359 auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
25360 if (VT.is512BitVector()) {
25361 // On AVX512BW targets we make use of the fact that VSELECT lowers
25362 // to a masked blend which selects bytes based just on the sign bit
25363 // extracted to a mask.
25364 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
25365 V0 = DAG.getBitcast(VT, V0);
25366 V1 = DAG.getBitcast(VT, V1);
25367 Sel = DAG.getBitcast(VT, Sel);
25368 Sel = DAG.getSetCC(dl, MaskVT, DAG.getConstant(0, dl, VT), Sel,
25369 ISD::SETGT);
25370 return DAG.getBitcast(SelVT, DAG.getSelect(dl, VT, Sel, V0, V1));
25371 } else if (Subtarget.hasSSE41()) {
25372 // On SSE41 targets we make use of the fact that VSELECT lowers
25373 // to PBLENDVB which selects bytes based just on the sign bit.
25374 V0 = DAG.getBitcast(VT, V0);
25375 V1 = DAG.getBitcast(VT, V1);
25376 Sel = DAG.getBitcast(VT, Sel);
25377 return DAG.getBitcast(SelVT, DAG.getSelect(dl, VT, Sel, V0, V1));
25378 }
25379 // On pre-SSE41 targets we test for the sign bit by comparing to
25380 // zero - a negative value will set all bits of the lanes to true
25381 // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
25382 SDValue Z = DAG.getConstant(0, dl, SelVT);
25383 SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
25384 return DAG.getSelect(dl, SelVT, C, V0, V1);
25385 };
25386
25387 // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
25388 // We can safely do this using i16 shifts as we're only interested in
25389 // the 3 lower bits of each byte.
25390 Amt = DAG.getBitcast(ExtVT, Amt);
25391 Amt = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ExtVT, Amt, 5, DAG);
25392 Amt = DAG.getBitcast(VT, Amt);
25393
25394 if (Opc == ISD::SHL || Opc == ISD::SRL) {
25395 // r = VSELECT(r, shift(r, 4), a);
25396 SDValue M = DAG.getNode(Opc, dl, VT, R, DAG.getConstant(4, dl, VT));
25397 R = SignBitSelect(VT, Amt, M, R);
25398
25399 // a += a
25400 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
25401
25402 // r = VSELECT(r, shift(r, 2), a);
25403 M = DAG.getNode(Opc, dl, VT, R, DAG.getConstant(2, dl, VT));
25404 R = SignBitSelect(VT, Amt, M, R);
25405
25406 // a += a
25407 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
25408
25409 // return VSELECT(r, shift(r, 1), a);
25410 M = DAG.getNode(Opc, dl, VT, R, DAG.getConstant(1, dl, VT));
25411 R = SignBitSelect(VT, Amt, M, R);
25412 return R;
25413 }
25414
25415 if (Opc == ISD::SRA) {
25416 // For SRA we need to unpack each byte to the higher byte of a i16 vector
25417 // so we can correctly sign extend. We don't care what happens to the
25418 // lower byte.
25419 SDValue ALo = getUnpackl(DAG, dl, VT, DAG.getUNDEF(VT), Amt);
25420 SDValue AHi = getUnpackh(DAG, dl, VT, DAG.getUNDEF(VT), Amt);
25421 SDValue RLo = getUnpackl(DAG, dl, VT, DAG.getUNDEF(VT), R);
25422 SDValue RHi = getUnpackh(DAG, dl, VT, DAG.getUNDEF(VT), R);
25423 ALo = DAG.getBitcast(ExtVT, ALo);
25424 AHi = DAG.getBitcast(ExtVT, AHi);
25425 RLo = DAG.getBitcast(ExtVT, RLo);
25426 RHi = DAG.getBitcast(ExtVT, RHi);
25427
25428 // r = VSELECT(r, shift(r, 4), a);
25429 SDValue MLo = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RLo, 4, DAG);
25430 SDValue MHi = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RHi, 4, DAG);
25431 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
25432 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
25433
25434 // a += a
25435 ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
25436 AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
25437
25438 // r = VSELECT(r, shift(r, 2), a);
25439 MLo = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RLo, 2, DAG);
25440 MHi = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RHi, 2, DAG);
25441 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
25442 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
25443
25444 // a += a
25445 ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
25446 AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
25447
25448 // r = VSELECT(r, shift(r, 1), a);
25449 MLo = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RLo, 1, DAG);
25450 MHi = getTargetVShiftByConstNode(X86OpcI, dl, ExtVT, RHi, 1, DAG);
25451 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
25452 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
25453
25454 // Logical shift the result back to the lower byte, leaving a zero upper
25455 // byte meaning that we can safely pack with PACKUSWB.
25456 RLo = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExtVT, RLo, 8, DAG);
25457 RHi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExtVT, RHi, 8, DAG);
25458 return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
25459 }
25460 }
25461
25462 if (Subtarget.hasInt256() && !Subtarget.hasXOP() && VT == MVT::v16i16) {
25463 MVT ExtVT = MVT::v8i32;
25464 SDValue Z = DAG.getConstant(0, dl, VT);
25465 SDValue ALo = getUnpackl(DAG, dl, VT, Amt, Z);
25466 SDValue AHi = getUnpackh(DAG, dl, VT, Amt, Z);
25467 SDValue RLo = getUnpackl(DAG, dl, VT, Z, R);
25468 SDValue RHi = getUnpackh(DAG, dl, VT, Z, R);
25469 ALo = DAG.getBitcast(ExtVT, ALo);
25470 AHi = DAG.getBitcast(ExtVT, AHi);
25471 RLo = DAG.getBitcast(ExtVT, RLo);
25472 RHi = DAG.getBitcast(ExtVT, RHi);
25473 SDValue Lo = DAG.getNode(Opc, dl, ExtVT, RLo, ALo);
25474 SDValue Hi = DAG.getNode(Opc, dl, ExtVT, RHi, AHi);
25475 Lo = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExtVT, Lo, 16, DAG);
25476 Hi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ExtVT, Hi, 16, DAG);
25477 return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
25478 }
25479
25480 if (VT == MVT::v8i16) {
25481 // If we have a constant shift amount, the non-SSE41 path is best as
25482 // avoiding bitcasts make it easier to constant fold and reduce to PBLENDW.
25483 bool UseSSE41 = Subtarget.hasSSE41() &&
25484 !ISD::isBuildVectorOfConstantSDNodes(Amt.getNode());
25485
25486 auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
25487 // On SSE41 targets we make use of the fact that VSELECT lowers
25488 // to PBLENDVB which selects bytes based just on the sign bit.
25489 if (UseSSE41) {
25490 MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
25491 V0 = DAG.getBitcast(ExtVT, V0);
25492 V1 = DAG.getBitcast(ExtVT, V1);
25493 Sel = DAG.getBitcast(ExtVT, Sel);
25494 return DAG.getBitcast(VT, DAG.getSelect(dl, ExtVT, Sel, V0, V1));
25495 }
25496 // On pre-SSE41 targets we splat the sign bit - a negative value will
25497 // set all bits of the lanes to true and VSELECT uses that in
25498 // its OR(AND(V0,C),AND(V1,~C)) lowering.
25499 SDValue C =
25500 getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Sel, 15, DAG);
25501 return DAG.getSelect(dl, VT, C, V0, V1);
25502 };
25503
25504 // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
25505 if (UseSSE41) {
25506 // On SSE41 targets we need to replicate the shift mask in both
25507 // bytes for PBLENDVB.
25508 Amt = DAG.getNode(
25509 ISD::OR, dl, VT,
25510 getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Amt, 4, DAG),
25511 getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Amt, 12, DAG));
25512 } else {
25513 Amt = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Amt, 12, DAG);
25514 }
25515
25516 // r = VSELECT(r, shift(r, 8), a);
25517 SDValue M = getTargetVShiftByConstNode(X86OpcI, dl, VT, R, 8, DAG);
25518 R = SignBitSelect(Amt, M, R);
25519
25520 // a += a
25521 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
25522
25523 // r = VSELECT(r, shift(r, 4), a);
25524 M = getTargetVShiftByConstNode(X86OpcI, dl, VT, R, 4, DAG);
25525 R = SignBitSelect(Amt, M, R);
25526
25527 // a += a
25528 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
25529
25530 // r = VSELECT(r, shift(r, 2), a);
25531 M = getTargetVShiftByConstNode(X86OpcI, dl, VT, R, 2, DAG);
25532 R = SignBitSelect(Amt, M, R);
25533
25534 // a += a
25535 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
25536
25537 // return VSELECT(r, shift(r, 1), a);
25538 M = getTargetVShiftByConstNode(X86OpcI, dl, VT, R, 1, DAG);
25539 R = SignBitSelect(Amt, M, R);
25540 return R;
25541 }
25542
25543 // Decompose 256-bit shifts into 128-bit shifts.
25544 if (VT.is256BitVector())
25545 return split256IntArith(Op, DAG);
25546
25547 return SDValue();
25548}
25549
25550static SDValue LowerRotate(SDValue Op, const X86Subtarget &Subtarget,
25551 SelectionDAG &DAG) {
25552 MVT VT = Op.getSimpleValueType();
25553 assert(VT.isVector() && "Custom lowering only for vector rotates!")((VT.isVector() && "Custom lowering only for vector rotates!"
) ? static_cast<void> (0) : __assert_fail ("VT.isVector() && \"Custom lowering only for vector rotates!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 25553, __PRETTY_FUNCTION__))
;
25554
25555 SDLoc DL(Op);
25556 SDValue R = Op.getOperand(0);
25557 SDValue Amt = Op.getOperand(1);
25558 unsigned Opcode = Op.getOpcode();
25559 unsigned EltSizeInBits = VT.getScalarSizeInBits();
25560 int NumElts = VT.getVectorNumElements();
25561
25562 // Check for constant splat rotation amount.
25563 APInt UndefElts;
25564 SmallVector<APInt, 32> EltBits;
25565 int CstSplatIndex = -1;
25566 if (getTargetConstantBitsFromNode(Amt, EltSizeInBits, UndefElts, EltBits))
25567 for (int i = 0; i != NumElts; ++i)
25568 if (!UndefElts[i]) {
25569 if (CstSplatIndex < 0 || EltBits[i] == EltBits[CstSplatIndex]) {
25570 CstSplatIndex = i;
25571 continue;
25572 }
25573 CstSplatIndex = -1;
25574 break;
25575 }
25576
25577 // AVX512 implicitly uses modulo rotation amounts.
25578 if (Subtarget.hasAVX512() && 32 <= EltSizeInBits) {
25579 // Attempt to rotate by immediate.
25580 if (0 <= CstSplatIndex) {
25581 unsigned Op = (Opcode == ISD::ROTL ? X86ISD::VROTLI : X86ISD::VROTRI);
25582 uint64_t RotateAmt = EltBits[CstSplatIndex].urem(EltSizeInBits);
25583 return DAG.getNode(Op, DL, VT, R,
25584 DAG.getConstant(RotateAmt, DL, MVT::i8));
25585 }
25586
25587 // Else, fall-back on VPROLV/VPRORV.
25588 return Op;
25589 }
25590
25591 assert((Opcode == ISD::ROTL) && "Only ROTL supported")(((Opcode == ISD::ROTL) && "Only ROTL supported") ? static_cast
<void> (0) : __assert_fail ("(Opcode == ISD::ROTL) && \"Only ROTL supported\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 25591, __PRETTY_FUNCTION__))
;
25592
25593 // XOP has 128-bit vector variable + immediate rotates.
25594 // +ve/-ve Amt = rotate left/right - just need to handle ISD::ROTL.
25595 // XOP implicitly uses modulo rotation amounts.
25596 if (Subtarget.hasXOP()) {
25597 if (VT.is256BitVector())
25598 return split256IntArith(Op, DAG);
25599 assert(VT.is128BitVector() && "Only rotate 128-bit vectors!")((VT.is128BitVector() && "Only rotate 128-bit vectors!"
) ? static_cast<void> (0) : __assert_fail ("VT.is128BitVector() && \"Only rotate 128-bit vectors!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 25599, __PRETTY_FUNCTION__))
;
25600
25601 // Attempt to rotate by immediate.
25602 if (0 <= CstSplatIndex) {
25603 uint64_t RotateAmt = EltBits[CstSplatIndex].urem(EltSizeInBits);
25604 return DAG.getNode(X86ISD::VROTLI, DL, VT, R,
25605 DAG.getConstant(RotateAmt, DL, MVT::i8));
25606 }
25607
25608 // Use general rotate by variable (per-element).
25609 return Op;
25610 }
25611
25612 // Split 256-bit integers on pre-AVX2 targets.
25613 if (VT.is256BitVector() && !Subtarget.hasAVX2())
25614 return split256IntArith(Op, DAG);
25615
25616 assert((VT == MVT::v4i32 || VT == MVT::v8i16 || VT == MVT::v16i8 ||(((VT == MVT::v4i32 || VT == MVT::v8i16 || VT == MVT::v16i8 ||
((VT == MVT::v8i32 || VT == MVT::v16i16 || VT == MVT::v32i8)
&& Subtarget.hasAVX2())) && "Only vXi32/vXi16/vXi8 vector rotates supported"
) ? static_cast<void> (0) : __assert_fail ("(VT == MVT::v4i32 || VT == MVT::v8i16 || VT == MVT::v16i8 || ((VT == MVT::v8i32 || VT == MVT::v16i16 || VT == MVT::v32i8) && Subtarget.hasAVX2())) && \"Only vXi32/vXi16/vXi8 vector rotates supported\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 25619, __PRETTY_FUNCTION__))
25617 ((VT == MVT::v8i32 || VT == MVT::v16i16 || VT == MVT::v32i8) &&(((VT == MVT::v4i32 || VT == MVT::v8i16 || VT == MVT::v16i8 ||
((VT == MVT::v8i32 || VT == MVT::v16i16 || VT == MVT::v32i8)
&& Subtarget.hasAVX2())) && "Only vXi32/vXi16/vXi8 vector rotates supported"
) ? static_cast<void> (0) : __assert_fail ("(VT == MVT::v4i32 || VT == MVT::v8i16 || VT == MVT::v16i8 || ((VT == MVT::v8i32 || VT == MVT::v16i16 || VT == MVT::v32i8) && Subtarget.hasAVX2())) && \"Only vXi32/vXi16/vXi8 vector rotates supported\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 25619, __PRETTY_FUNCTION__))
25618 Subtarget.hasAVX2())) &&(((VT == MVT::v4i32 || VT == MVT::v8i16 || VT == MVT::v16i8 ||
((VT == MVT::v8i32 || VT == MVT::v16i16 || VT == MVT::v32i8)
&& Subtarget.hasAVX2())) && "Only vXi32/vXi16/vXi8 vector rotates supported"
) ? static_cast<void> (0) : __assert_fail ("(VT == MVT::v4i32 || VT == MVT::v8i16 || VT == MVT::v16i8 || ((VT == MVT::v8i32 || VT == MVT::v16i16 || VT == MVT::v32i8) && Subtarget.hasAVX2())) && \"Only vXi32/vXi16/vXi8 vector rotates supported\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 25619, __PRETTY_FUNCTION__))
25619 "Only vXi32/vXi16/vXi8 vector rotates supported")(((VT == MVT::v4i32 || VT == MVT::v8i16 || VT == MVT::v16i8 ||
((VT == MVT::v8i32 || VT == MVT::v16i16 || VT == MVT::v32i8)
&& Subtarget.hasAVX2())) && "Only vXi32/vXi16/vXi8 vector rotates supported"
) ? static_cast<void> (0) : __assert_fail ("(VT == MVT::v4i32 || VT == MVT::v8i16 || VT == MVT::v16i8 || ((VT == MVT::v8i32 || VT == MVT::v16i16 || VT == MVT::v32i8) && Subtarget.hasAVX2())) && \"Only vXi32/vXi16/vXi8 vector rotates supported\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 25619, __PRETTY_FUNCTION__))
;
25620
25621 // Rotate by an uniform constant - expand back to shifts.
25622 if (0 <= CstSplatIndex)
25623 return SDValue();
25624
25625 bool IsSplatAmt = DAG.isSplatValue(Amt);
25626
25627 // v16i8/v32i8: Split rotation into rot4/rot2/rot1 stages and select by
25628 // the amount bit.
25629 if (EltSizeInBits == 8 && !IsSplatAmt) {
25630 if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode()))
25631 return SDValue();
25632
25633 // We don't need ModuloAmt here as we just peek at individual bits.
25634 MVT ExtVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
25635
25636 auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
25637 if (Subtarget.hasSSE41()) {
25638 // On SSE41 targets we make use of the fact that VSELECT lowers
25639 // to PBLENDVB which selects bytes based just on the sign bit.
25640 V0 = DAG.getBitcast(VT, V0);
25641 V1 = DAG.getBitcast(VT, V1);
25642 Sel = DAG.getBitcast(VT, Sel);
25643 return DAG.getBitcast(SelVT, DAG.getSelect(DL, VT, Sel, V0, V1));
25644 }
25645 // On pre-SSE41 targets we test for the sign bit by comparing to
25646 // zero - a negative value will set all bits of the lanes to true
25647 // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
25648 SDValue Z = DAG.getConstant(0, DL, SelVT);
25649 SDValue C = DAG.getNode(X86ISD::PCMPGT, DL, SelVT, Z, Sel);
25650 return DAG.getSelect(DL, SelVT, C, V0, V1);
25651 };
25652
25653 // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
25654 // We can safely do this using i16 shifts as we're only interested in
25655 // the 3 lower bits of each byte.
25656 Amt = DAG.getBitcast(ExtVT, Amt);
25657 Amt = DAG.getNode(ISD::SHL, DL, ExtVT, Amt, DAG.getConstant(5, DL, ExtVT));
25658 Amt = DAG.getBitcast(VT, Amt);
25659
25660 // r = VSELECT(r, rot(r, 4), a);
25661 SDValue M;
25662 M = DAG.getNode(
25663 ISD::OR, DL, VT,
25664 DAG.getNode(ISD::SHL, DL, VT, R, DAG.getConstant(4, DL, VT)),
25665 DAG.getNode(ISD::SRL, DL, VT, R, DAG.getConstant(4, DL, VT)));
25666 R = SignBitSelect(VT, Amt, M, R);
25667
25668 // a += a
25669 Amt = DAG.getNode(ISD::ADD, DL, VT, Amt, Amt);
25670
25671 // r = VSELECT(r, rot(r, 2), a);
25672 M = DAG.getNode(
25673 ISD::OR, DL, VT,
25674 DAG.getNode(ISD::SHL, DL, VT, R, DAG.getConstant(2, DL, VT)),
25675 DAG.getNode(ISD::SRL, DL, VT, R, DAG.getConstant(6, DL, VT)));
25676 R = SignBitSelect(VT, Amt, M, R);
25677
25678 // a += a
25679 Amt = DAG.getNode(ISD::ADD, DL, VT, Amt, Amt);
25680
25681 // return VSELECT(r, rot(r, 1), a);
25682 M = DAG.getNode(
25683 ISD::OR, DL, VT,
25684 DAG.getNode(ISD::SHL, DL, VT, R, DAG.getConstant(1, DL, VT)),
25685 DAG.getNode(ISD::SRL, DL, VT, R, DAG.getConstant(7, DL, VT)));
25686 return SignBitSelect(VT, Amt, M, R);
25687 }
25688
25689 // ISD::ROT* uses modulo rotate amounts.
25690 Amt = DAG.getNode(ISD::AND, DL, VT, Amt,
25691 DAG.getConstant(EltSizeInBits - 1, DL, VT));
25692
25693 bool ConstantAmt = ISD::isBuildVectorOfConstantSDNodes(Amt.getNode());
25694 bool LegalVarShifts = SupportedVectorVarShift(VT, Subtarget, ISD::SHL) &&
25695 SupportedVectorVarShift(VT, Subtarget, ISD::SRL);
25696
25697 // Fallback for splats + all supported variable shifts.
25698 // Fallback for non-constants AVX2 vXi16 as well.
25699 if (IsSplatAmt || LegalVarShifts || (Subtarget.hasAVX2() && !ConstantAmt)) {
25700 SDValue AmtR = DAG.getConstant(EltSizeInBits, DL, VT);
25701 AmtR = DAG.getNode(ISD::SUB, DL, VT, AmtR, Amt);
25702 SDValue SHL = DAG.getNode(ISD::SHL, DL, VT, R, Amt);
25703 SDValue SRL = DAG.getNode(ISD::SRL, DL, VT, R, AmtR);
25704 return DAG.getNode(ISD::OR, DL, VT, SHL, SRL);
25705 }
25706
25707 // As with shifts, convert the rotation amount to a multiplication factor.
25708 SDValue Scale = convertShiftLeftToScale(Amt, DL, Subtarget, DAG);
25709 assert(Scale && "Failed to convert ROTL amount to scale")((Scale && "Failed to convert ROTL amount to scale") ?
static_cast<void> (0) : __assert_fail ("Scale && \"Failed to convert ROTL amount to scale\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 25709, __PRETTY_FUNCTION__))
;
25710
25711 // v8i16/v16i16: perform unsigned multiply hi/lo and OR the results.
25712 if (EltSizeInBits == 16) {
25713 SDValue Lo = DAG.getNode(ISD::MUL, DL, VT, R, Scale);
25714 SDValue Hi = DAG.getNode(ISD::MULHU, DL, VT, R, Scale);
25715 return DAG.getNode(ISD::OR, DL, VT, Lo, Hi);
25716 }
25717
25718 // v4i32: make use of the PMULUDQ instruction to multiply 2 lanes of v4i32
25719 // to v2i64 results at a time. The upper 32-bits contain the wrapped bits
25720 // that can then be OR'd with the lower 32-bits.
25721 assert(VT == MVT::v4i32 && "Only v4i32 vector rotate expected")((VT == MVT::v4i32 && "Only v4i32 vector rotate expected"
) ? static_cast<void> (0) : __assert_fail ("VT == MVT::v4i32 && \"Only v4i32 vector rotate expected\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 25721, __PRETTY_FUNCTION__))
;
25722 static const int OddMask[] = {1, -1, 3, -1};
25723 SDValue R13 = DAG.getVectorShuffle(VT, DL, R, R, OddMask);
25724 SDValue Scale13 = DAG.getVectorShuffle(VT, DL, Scale, Scale, OddMask);
25725
25726 SDValue Res02 = DAG.getNode(X86ISD::PMULUDQ, DL, MVT::v2i64,
25727 DAG.getBitcast(MVT::v2i64, R),
25728 DAG.getBitcast(MVT::v2i64, Scale));
25729 SDValue Res13 = DAG.getNode(X86ISD::PMULUDQ, DL, MVT::v2i64,
25730 DAG.getBitcast(MVT::v2i64, R13),
25731 DAG.getBitcast(MVT::v2i64, Scale13));
25732 Res02 = DAG.getBitcast(VT, Res02);
25733 Res13 = DAG.getBitcast(VT, Res13);
25734
25735 return DAG.getNode(ISD::OR, DL, VT,
25736 DAG.getVectorShuffle(VT, DL, Res02, Res13, {0, 4, 2, 6}),
25737 DAG.getVectorShuffle(VT, DL, Res02, Res13, {1, 5, 3, 7}));
25738}
25739
25740/// Returns true if the operand type is exactly twice the native width, and
25741/// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
25742/// Used to know whether to use cmpxchg8/16b when expanding atomic operations
25743/// (otherwise we leave them alone to become __sync_fetch_and_... calls).
25744bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
25745 unsigned OpWidth = MemType->getPrimitiveSizeInBits();
25746
25747 if (OpWidth == 64)
25748 return Subtarget.hasCmpxchg8b() && !Subtarget.is64Bit();
25749 if (OpWidth == 128)
25750 return Subtarget.hasCmpxchg16b();
25751
25752 return false;
25753}
25754
25755// TODO: In 32-bit mode, use MOVLPS when SSE1 is available?
25756// TODO: In 32-bit mode, use FISTP when X87 is available?
25757bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
25758 Type *MemType = SI->getValueOperand()->getType();
25759
25760 bool NoImplicitFloatOps =
25761 SI->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat);
25762 if (MemType->getPrimitiveSizeInBits() == 64 && !Subtarget.is64Bit() &&
25763 !Subtarget.useSoftFloat() && !NoImplicitFloatOps && Subtarget.hasSSE2())
25764 return false;
25765
25766 return needsCmpXchgNb(MemType);
25767}
25768
25769// Note: this turns large loads into lock cmpxchg8b/16b.
25770// TODO: In 32-bit mode, use MOVLPS when SSE1 is available?
25771TargetLowering::AtomicExpansionKind
25772X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
25773 Type *MemType = LI->getType();
25774
25775 // If this a 64 bit atomic load on a 32-bit target and SSE2 is enabled, we
25776 // can use movq to do the load. If we have X87 we can load into an 80-bit
25777 // X87 register and store it to a stack temporary.
25778 bool NoImplicitFloatOps =
25779 LI->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat);
25780 if (MemType->getPrimitiveSizeInBits() == 64 && !Subtarget.is64Bit() &&
25781 !Subtarget.useSoftFloat() && !NoImplicitFloatOps &&
25782 (Subtarget.hasSSE2() || Subtarget.hasX87()))
25783 return AtomicExpansionKind::None;
25784
25785 return needsCmpXchgNb(MemType) ? AtomicExpansionKind::CmpXChg
25786 : AtomicExpansionKind::None;
25787}
25788
25789TargetLowering::AtomicExpansionKind
25790X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
25791 unsigned NativeWidth = Subtarget.is64Bit() ? 64 : 32;
25792 Type *MemType = AI->getType();
25793
25794 // If the operand is too big, we must see if cmpxchg8/16b is available
25795 // and default to library calls otherwise.
25796 if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
25797 return needsCmpXchgNb(MemType) ? AtomicExpansionKind::CmpXChg
25798 : AtomicExpansionKind::None;
25799 }
25800
25801 AtomicRMWInst::BinOp Op = AI->getOperation();
25802 switch (Op) {
25803 default:
25804 llvm_unreachable("Unknown atomic operation")::llvm::llvm_unreachable_internal("Unknown atomic operation",
"/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 25804)
;
25805 case AtomicRMWInst::Xchg:
25806 case AtomicRMWInst::Add:
25807 case AtomicRMWInst::Sub:
25808 // It's better to use xadd, xsub or xchg for these in all cases.
25809 return AtomicExpansionKind::None;
25810 case AtomicRMWInst::Or:
25811 case AtomicRMWInst::And:
25812 case AtomicRMWInst::Xor:
25813 // If the atomicrmw's result isn't actually used, we can just add a "lock"
25814 // prefix to a normal instruction for these operations.
25815 return !AI->use_empty() ? AtomicExpansionKind::CmpXChg
25816 : AtomicExpansionKind::None;
25817 case AtomicRMWInst::Nand:
25818 case AtomicRMWInst::Max:
25819 case AtomicRMWInst::Min:
25820 case AtomicRMWInst::UMax:
25821 case AtomicRMWInst::UMin:
25822 case AtomicRMWInst::FAdd:
25823 case AtomicRMWInst::FSub:
25824 // These always require a non-trivial set of data operations on x86. We must
25825 // use a cmpxchg loop.
25826 return AtomicExpansionKind::CmpXChg;
25827 }
25828}
25829
25830LoadInst *
25831X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
25832 unsigned NativeWidth = Subtarget.is64Bit() ? 64 : 32;
25833 Type *MemType = AI->getType();
25834 // Accesses larger than the native width are turned into cmpxchg/libcalls, so
25835 // there is no benefit in turning such RMWs into loads, and it is actually
25836 // harmful as it introduces a mfence.
25837 if (MemType->getPrimitiveSizeInBits() > NativeWidth)
25838 return nullptr;
25839
25840 // If this is a canonical idempotent atomicrmw w/no uses, we have a better
25841 // lowering available in lowerAtomicArith.
25842 // TODO: push more cases through this path.
25843 if (auto *C = dyn_cast<ConstantInt>(AI->getValOperand()))
25844 if (AI->getOperation() == AtomicRMWInst::Or && C->isZero() &&
25845 AI->use_empty())
25846 return nullptr;
25847
25848 auto Builder = IRBuilder<>(AI);
25849 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
25850 auto SSID = AI->getSyncScopeID();
25851 // We must restrict the ordering to avoid generating loads with Release or
25852 // ReleaseAcquire orderings.
25853 auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
25854
25855 // Before the load we need a fence. Here is an example lifted from
25856 // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
25857 // is required:
25858 // Thread 0:
25859 // x.store(1, relaxed);
25860 // r1 = y.fetch_add(0, release);
25861 // Thread 1:
25862 // y.fetch_add(42, acquire);
25863 // r2 = x.load(relaxed);
25864 // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
25865 // lowered to just a load without a fence. A mfence flushes the store buffer,
25866 // making the optimization clearly correct.
25867 // FIXME: it is required if isReleaseOrStronger(Order) but it is not clear
25868 // otherwise, we might be able to be more aggressive on relaxed idempotent
25869 // rmw. In practice, they do not look useful, so we don't try to be
25870 // especially clever.
25871 if (SSID == SyncScope::SingleThread)
25872 // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
25873 // the IR level, so we must wrap it in an intrinsic.
25874 return nullptr;
25875
25876 if (!Subtarget.hasMFence())
25877 // FIXME: it might make sense to use a locked operation here but on a
25878 // different cache-line to prevent cache-line bouncing. In practice it
25879 // is probably a small win, and x86 processors without mfence are rare
25880 // enough that we do not bother.
25881 return nullptr;
25882
25883 Function *MFence =
25884 llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
25885 Builder.CreateCall(MFence, {});
25886
25887 // Finally we can emit the atomic load.
25888 LoadInst *Loaded =
25889 Builder.CreateAlignedLoad(AI->getType(), AI->getPointerOperand(),
25890 AI->getType()->getPrimitiveSizeInBits());
25891 Loaded->setAtomic(Order, SSID);
25892 AI->replaceAllUsesWith(Loaded);
25893 AI->eraseFromParent();
25894 return Loaded;
25895}
25896
25897/// Emit a locked operation on a stack location which does not change any
25898/// memory location, but does involve a lock prefix. Location is chosen to be
25899/// a) very likely accessed only by a single thread to minimize cache traffic,
25900/// and b) definitely dereferenceable. Returns the new Chain result.
25901static SDValue emitLockedStackOp(SelectionDAG &DAG,
25902 const X86Subtarget &Subtarget,
25903 SDValue Chain, SDLoc DL) {
25904 // Implementation notes:
25905 // 1) LOCK prefix creates a full read/write reordering barrier for memory
25906 // operations issued by the current processor. As such, the location
25907 // referenced is not relevant for the ordering properties of the instruction.
25908 // See: Intel® 64 and IA-32 ArchitecturesSoftware Developer’s Manual,
25909 // 8.2.3.9 Loads and Stores Are Not Reordered with Locked Instructions
25910 // 2) Using an immediate operand appears to be the best encoding choice
25911 // here since it doesn't require an extra register.
25912 // 3) OR appears to be very slightly faster than ADD. (Though, the difference
25913 // is small enough it might just be measurement noise.)
25914 // 4) When choosing offsets, there are several contributing factors:
25915 // a) If there's no redzone, we default to TOS. (We could allocate a cache
25916 // line aligned stack object to improve this case.)
25917 // b) To minimize our chances of introducing a false dependence, we prefer
25918 // to offset the stack usage from TOS slightly.
25919 // c) To minimize concerns about cross thread stack usage - in particular,
25920 // the idiomatic MyThreadPool.run([&StackVars]() {...}) pattern which
25921 // captures state in the TOS frame and accesses it from many threads -
25922 // we want to use an offset such that the offset is in a distinct cache
25923 // line from the TOS frame.
25924 //
25925 // For a general discussion of the tradeoffs and benchmark results, see:
25926 // https://shipilev.net/blog/2014/on-the-fence-with-dependencies/
25927
25928 auto &MF = DAG.getMachineFunction();
25929 auto &TFL = *Subtarget.getFrameLowering();
25930 const unsigned SPOffset = TFL.has128ByteRedZone(MF) ? -64 : 0;
25931
25932 if (Subtarget.is64Bit()) {
25933 SDValue Zero = DAG.getTargetConstant(0, DL, MVT::i32);
25934 SDValue Ops[] = {
25935 DAG.getRegister(X86::RSP, MVT::i64), // Base
25936 DAG.getTargetConstant(1, DL, MVT::i8), // Scale
25937 DAG.getRegister(0, MVT::i64), // Index
25938 DAG.getTargetConstant(SPOffset, DL, MVT::i32), // Disp
25939 DAG.getRegister(0, MVT::i16), // Segment.
25940 Zero,
25941 Chain};
25942 SDNode *Res = DAG.getMachineNode(X86::OR32mi8Locked, DL, MVT::i32,
25943 MVT::Other, Ops);
25944 return SDValue(Res, 1);
25945 }
25946
25947 SDValue Zero = DAG.getTargetConstant(0, DL, MVT::i32);
25948 SDValue Ops[] = {
25949 DAG.getRegister(X86::ESP, MVT::i32), // Base
25950 DAG.getTargetConstant(1, DL, MVT::i8), // Scale
25951 DAG.getRegister(0, MVT::i32), // Index
25952 DAG.getTargetConstant(SPOffset, DL, MVT::i32), // Disp
25953 DAG.getRegister(0, MVT::i16), // Segment.
25954 Zero,
25955 Chain
25956 };
25957 SDNode *Res = DAG.getMachineNode(X86::OR32mi8Locked, DL, MVT::i32,
25958 MVT::Other, Ops);
25959 return SDValue(Res, 1);
25960}
25961
25962static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget &Subtarget,
25963 SelectionDAG &DAG) {
25964 SDLoc dl(Op);
25965 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
25966 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
25967 SyncScope::ID FenceSSID = static_cast<SyncScope::ID>(
25968 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
25969
25970 // The only fence that needs an instruction is a sequentially-consistent
25971 // cross-thread fence.
25972 if (FenceOrdering == AtomicOrdering::SequentiallyConsistent &&
25973 FenceSSID == SyncScope::System) {
25974 if (Subtarget.hasMFence())
25975 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
25976
25977 SDValue Chain = Op.getOperand(0);
25978 return emitLockedStackOp(DAG, Subtarget, Chain, dl);
25979 }
25980
25981 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
25982 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
25983}
25984
25985static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget &Subtarget,
25986 SelectionDAG &DAG) {
25987 MVT T = Op.getSimpleValueType();
25988 SDLoc DL(Op);
25989 unsigned Reg = 0;
25990 unsigned size = 0;
25991 switch(T.SimpleTy) {
25992 default: llvm_unreachable("Invalid value type!")::llvm::llvm_unreachable_internal("Invalid value type!", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 25992)
;
25993 case MVT::i8: Reg = X86::AL; size = 1; break;
25994 case MVT::i16: Reg = X86::AX; size = 2; break;
25995 case MVT::i32: Reg = X86::EAX; size = 4; break;
25996 case MVT::i64:
25997 assert(Subtarget.is64Bit() && "Node not type legal!")((Subtarget.is64Bit() && "Node not type legal!") ? static_cast
<void> (0) : __assert_fail ("Subtarget.is64Bit() && \"Node not type legal!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 25997, __PRETTY_FUNCTION__))
;
25998 Reg = X86::RAX; size = 8;
25999 break;
26000 }
26001 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
26002 Op.getOperand(2), SDValue());
26003 SDValue Ops[] = { cpIn.getValue(0),
26004 Op.getOperand(1),
26005 Op.getOperand(3),
26006 DAG.getTargetConstant(size, DL, MVT::i8),
26007 cpIn.getValue(1) };
26008 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
26009 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
26010 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
26011 Ops, T, MMO);
26012
26013 SDValue cpOut =
26014 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
26015 SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
26016 MVT::i32, cpOut.getValue(2));
26017 SDValue Success = getSETCC(X86::COND_E, EFLAGS, DL, DAG);
26018
26019 return DAG.getNode(ISD::MERGE_VALUES, DL, Op->getVTList(),
26020 cpOut, Success, EFLAGS.getValue(1));
26021}
26022
26023// Create MOVMSKB, taking into account whether we need to split for AVX1.
26024static SDValue getPMOVMSKB(const SDLoc &DL, SDValue V, SelectionDAG &DAG,
26025 const X86Subtarget &Subtarget) {
26026 MVT InVT = V.getSimpleValueType();
26027
26028 if (InVT == MVT::v32i8 && !Subtarget.hasInt256()) {
26029 SDValue Lo, Hi;
26030 std::tie(Lo, Hi) = DAG.SplitVector(V, DL);
26031 Lo = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Lo);
26032 Hi = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Hi);
26033 Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
26034 DAG.getConstant(16, DL, MVT::i8));
26035 return DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi);
26036 }
26037
26038 return DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, V);
26039}
26040
26041static SDValue LowerBITCAST(SDValue Op, const X86Subtarget &Subtarget,
26042 SelectionDAG &DAG) {
26043 SDValue Src = Op.getOperand(0);
26044 MVT SrcVT = Src.getSimpleValueType();
26045 MVT DstVT = Op.getSimpleValueType();
26046
26047 // Legalize (v64i1 (bitcast i64 (X))) by splitting the i64, bitcasting each
26048 // half to v32i1 and concatenating the result.
26049 if (SrcVT == MVT::i64 && DstVT == MVT::v64i1) {
26050 assert(!Subtarget.is64Bit() && "Expected 32-bit mode")((!Subtarget.is64Bit() && "Expected 32-bit mode") ? static_cast
<void> (0) : __assert_fail ("!Subtarget.is64Bit() && \"Expected 32-bit mode\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26050, __PRETTY_FUNCTION__))
;
26051 assert(Subtarget.hasBWI() && "Expected BWI target")((Subtarget.hasBWI() && "Expected BWI target") ? static_cast
<void> (0) : __assert_fail ("Subtarget.hasBWI() && \"Expected BWI target\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26051, __PRETTY_FUNCTION__))
;
26052 SDLoc dl(Op);
26053 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Src,
26054 DAG.getIntPtrConstant(0, dl));
26055 Lo = DAG.getBitcast(MVT::v32i1, Lo);
26056 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Src,
26057 DAG.getIntPtrConstant(1, dl));
26058 Hi = DAG.getBitcast(MVT::v32i1, Hi);
26059 return DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, Lo, Hi);
26060 }
26061
26062 // Custom splitting for BWI types when AVX512F is available but BWI isn't.
26063 if ((SrcVT == MVT::v32i16 || SrcVT == MVT::v64i8) && DstVT.isVector() &&
26064 DAG.getTargetLoweringInfo().isTypeLegal(DstVT)) {
26065 SDLoc dl(Op);
26066 SDValue Lo, Hi;
26067 std::tie(Lo, Hi) = DAG.SplitVector(Op.getOperand(0), dl);
26068 EVT CastVT = MVT::getVectorVT(DstVT.getVectorElementType(),
26069 DstVT.getVectorNumElements() / 2);
26070 Lo = DAG.getBitcast(CastVT, Lo);
26071 Hi = DAG.getBitcast(CastVT, Hi);
26072 return DAG.getNode(ISD::CONCAT_VECTORS, dl, DstVT, Lo, Hi);
26073 }
26074
26075 // Use MOVMSK for vector to scalar conversion to prevent scalarization.
26076 if ((SrcVT == MVT::v16i1 || SrcVT == MVT::v32i1) && DstVT.isScalarInteger()) {
26077 assert(!Subtarget.hasAVX512() && "Should use K-registers with AVX512")((!Subtarget.hasAVX512() && "Should use K-registers with AVX512"
) ? static_cast<void> (0) : __assert_fail ("!Subtarget.hasAVX512() && \"Should use K-registers with AVX512\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26077, __PRETTY_FUNCTION__))
;
26078 MVT SExtVT = SrcVT == MVT::v16i1 ? MVT::v16i8 : MVT::v32i8;
26079 SDLoc DL(Op);
26080 SDValue V = DAG.getSExtOrTrunc(Src, DL, SExtVT);
26081 V = getPMOVMSKB(DL, V, DAG, Subtarget);
26082 return DAG.getZExtOrTrunc(V, DL, DstVT);
26083 }
26084
26085 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8 ||
26086 SrcVT == MVT::i64) {
26087 assert(Subtarget.hasSSE2() && "Requires at least SSE2!")((Subtarget.hasSSE2() && "Requires at least SSE2!") ?
static_cast<void> (0) : __assert_fail ("Subtarget.hasSSE2() && \"Requires at least SSE2!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26087, __PRETTY_FUNCTION__))
;
26088 if (DstVT != MVT::f64 && DstVT != MVT::i64 &&
26089 !(DstVT == MVT::x86mmx && SrcVT.isVector()))
26090 // This conversion needs to be expanded.
26091 return SDValue();
26092
26093 SDLoc dl(Op);
26094 if (SrcVT.isVector()) {
26095 // Widen the vector in input in the case of MVT::v2i32.
26096 // Example: from MVT::v2i32 to MVT::v4i32.
26097 MVT NewVT = MVT::getVectorVT(SrcVT.getVectorElementType(),
26098 SrcVT.getVectorNumElements() * 2);
26099 Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewVT, Src,
26100 DAG.getUNDEF(SrcVT));
26101 } else {
26102 assert(SrcVT == MVT::i64 && !Subtarget.is64Bit() &&((SrcVT == MVT::i64 && !Subtarget.is64Bit() &&
"Unexpected source type in LowerBITCAST") ? static_cast<void
> (0) : __assert_fail ("SrcVT == MVT::i64 && !Subtarget.is64Bit() && \"Unexpected source type in LowerBITCAST\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26103, __PRETTY_FUNCTION__))
26103 "Unexpected source type in LowerBITCAST")((SrcVT == MVT::i64 && !Subtarget.is64Bit() &&
"Unexpected source type in LowerBITCAST") ? static_cast<void
> (0) : __assert_fail ("SrcVT == MVT::i64 && !Subtarget.is64Bit() && \"Unexpected source type in LowerBITCAST\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26103, __PRETTY_FUNCTION__))
;
26104 Src = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Src);
26105 }
26106
26107 MVT V2X64VT = DstVT == MVT::f64 ? MVT::v2f64 : MVT::v2i64;
26108 Src = DAG.getNode(ISD::BITCAST, dl, V2X64VT, Src);
26109
26110 if (DstVT == MVT::x86mmx)
26111 return DAG.getNode(X86ISD::MOVDQ2Q, dl, DstVT, Src);
26112
26113 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, DstVT, Src,
26114 DAG.getIntPtrConstant(0, dl));
26115 }
26116
26117 assert(Subtarget.is64Bit() && !Subtarget.hasSSE2() &&((Subtarget.is64Bit() && !Subtarget.hasSSE2() &&
Subtarget.hasMMX() && "Unexpected custom BITCAST") ?
static_cast<void> (0) : __assert_fail ("Subtarget.is64Bit() && !Subtarget.hasSSE2() && Subtarget.hasMMX() && \"Unexpected custom BITCAST\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26118, __PRETTY_FUNCTION__))
26118 Subtarget.hasMMX() && "Unexpected custom BITCAST")((Subtarget.is64Bit() && !Subtarget.hasSSE2() &&
Subtarget.hasMMX() && "Unexpected custom BITCAST") ?
static_cast<void> (0) : __assert_fail ("Subtarget.is64Bit() && !Subtarget.hasSSE2() && Subtarget.hasMMX() && \"Unexpected custom BITCAST\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26118, __PRETTY_FUNCTION__))
;
26119 assert((DstVT == MVT::i64 ||(((DstVT == MVT::i64 || (DstVT.isVector() && DstVT.getSizeInBits
()==64)) && "Unexpected custom BITCAST") ? static_cast
<void> (0) : __assert_fail ("(DstVT == MVT::i64 || (DstVT.isVector() && DstVT.getSizeInBits()==64)) && \"Unexpected custom BITCAST\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26121, __PRETTY_FUNCTION__))
26120 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&(((DstVT == MVT::i64 || (DstVT.isVector() && DstVT.getSizeInBits
()==64)) && "Unexpected custom BITCAST") ? static_cast
<void> (0) : __assert_fail ("(DstVT == MVT::i64 || (DstVT.isVector() && DstVT.getSizeInBits()==64)) && \"Unexpected custom BITCAST\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26121, __PRETTY_FUNCTION__))
26121 "Unexpected custom BITCAST")(((DstVT == MVT::i64 || (DstVT.isVector() && DstVT.getSizeInBits
()==64)) && "Unexpected custom BITCAST") ? static_cast
<void> (0) : __assert_fail ("(DstVT == MVT::i64 || (DstVT.isVector() && DstVT.getSizeInBits()==64)) && \"Unexpected custom BITCAST\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26121, __PRETTY_FUNCTION__))
;
26122 // i64 <=> MMX conversions are Legal.
26123 if (SrcVT==MVT::i64 && DstVT.isVector())
26124 return Op;
26125 if (DstVT==MVT::i64 && SrcVT.isVector())
26126 return Op;
26127 // MMX <=> MMX conversions are Legal.
26128 if (SrcVT.isVector() && DstVT.isVector())
26129 return Op;
26130 // All other conversions need to be expanded.
26131 return SDValue();
26132}
26133
26134/// Compute the horizontal sum of bytes in V for the elements of VT.
26135///
26136/// Requires V to be a byte vector and VT to be an integer vector type with
26137/// wider elements than V's type. The width of the elements of VT determines
26138/// how many bytes of V are summed horizontally to produce each element of the
26139/// result.
26140static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
26141 const X86Subtarget &Subtarget,
26142 SelectionDAG &DAG) {
26143 SDLoc DL(V);
26144 MVT ByteVecVT = V.getSimpleValueType();
26145 MVT EltVT = VT.getVectorElementType();
26146 assert(ByteVecVT.getVectorElementType() == MVT::i8 &&((ByteVecVT.getVectorElementType() == MVT::i8 && "Expected value to have byte element type."
) ? static_cast<void> (0) : __assert_fail ("ByteVecVT.getVectorElementType() == MVT::i8 && \"Expected value to have byte element type.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26147, __PRETTY_FUNCTION__))
26147 "Expected value to have byte element type.")((ByteVecVT.getVectorElementType() == MVT::i8 && "Expected value to have byte element type."
) ? static_cast<void> (0) : __assert_fail ("ByteVecVT.getVectorElementType() == MVT::i8 && \"Expected value to have byte element type.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26147, __PRETTY_FUNCTION__))
;
26148 assert(EltVT != MVT::i8 &&((EltVT != MVT::i8 && "Horizontal byte sum only makes sense for wider elements!"
) ? static_cast<void> (0) : __assert_fail ("EltVT != MVT::i8 && \"Horizontal byte sum only makes sense for wider elements!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26149, __PRETTY_FUNCTION__))
26149 "Horizontal byte sum only makes sense for wider elements!")((EltVT != MVT::i8 && "Horizontal byte sum only makes sense for wider elements!"
) ? static_cast<void> (0) : __assert_fail ("EltVT != MVT::i8 && \"Horizontal byte sum only makes sense for wider elements!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26149, __PRETTY_FUNCTION__))
;
26150 unsigned VecSize = VT.getSizeInBits();
26151 assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!")((ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!"
) ? static_cast<void> (0) : __assert_fail ("ByteVecVT.getSizeInBits() == VecSize && \"Cannot change vector size!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26151, __PRETTY_FUNCTION__))
;
26152
26153 // PSADBW instruction horizontally add all bytes and leave the result in i64
26154 // chunks, thus directly computes the pop count for v2i64 and v4i64.
26155 if (EltVT == MVT::i64) {
26156 SDValue Zeros = DAG.getConstant(0, DL, ByteVecVT);
26157 MVT SadVecVT = MVT::getVectorVT(MVT::i64, VecSize / 64);
26158 V = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT, V, Zeros);
26159 return DAG.getBitcast(VT, V);
26160 }
26161
26162 if (EltVT == MVT::i32) {
26163 // We unpack the low half and high half into i32s interleaved with zeros so
26164 // that we can use PSADBW to horizontally sum them. The most useful part of
26165 // this is that it lines up the results of two PSADBW instructions to be
26166 // two v2i64 vectors which concatenated are the 4 population counts. We can
26167 // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
26168 SDValue Zeros = DAG.getConstant(0, DL, VT);
26169 SDValue V32 = DAG.getBitcast(VT, V);
26170 SDValue Low = getUnpackl(DAG, DL, VT, V32, Zeros);
26171 SDValue High = getUnpackh(DAG, DL, VT, V32, Zeros);
26172
26173 // Do the horizontal sums into two v2i64s.
26174 Zeros = DAG.getConstant(0, DL, ByteVecVT);
26175 MVT SadVecVT = MVT::getVectorVT(MVT::i64, VecSize / 64);
26176 Low = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT,
26177 DAG.getBitcast(ByteVecVT, Low), Zeros);
26178 High = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT,
26179 DAG.getBitcast(ByteVecVT, High), Zeros);
26180
26181 // Merge them together.
26182 MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
26183 V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
26184 DAG.getBitcast(ShortVecVT, Low),
26185 DAG.getBitcast(ShortVecVT, High));
26186
26187 return DAG.getBitcast(VT, V);
26188 }
26189
26190 // The only element type left is i16.
26191 assert(EltVT == MVT::i16 && "Unknown how to handle type")((EltVT == MVT::i16 && "Unknown how to handle type") ?
static_cast<void> (0) : __assert_fail ("EltVT == MVT::i16 && \"Unknown how to handle type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26191, __PRETTY_FUNCTION__))
;
26192
26193 // To obtain pop count for each i16 element starting from the pop count for
26194 // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
26195 // right by 8. It is important to shift as i16s as i8 vector shift isn't
26196 // directly supported.
26197 SDValue ShifterV = DAG.getConstant(8, DL, VT);
26198 SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), ShifterV);
26199 V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
26200 DAG.getBitcast(ByteVecVT, V));
26201 return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), ShifterV);
26202}
26203
26204static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, const SDLoc &DL,
26205 const X86Subtarget &Subtarget,
26206 SelectionDAG &DAG) {
26207 MVT VT = Op.getSimpleValueType();
26208 MVT EltVT = VT.getVectorElementType();
26209 int NumElts = VT.getVectorNumElements();
26210 (void)EltVT;
26211 assert(EltVT == MVT::i8 && "Only vXi8 vector CTPOP lowering supported.")((EltVT == MVT::i8 && "Only vXi8 vector CTPOP lowering supported."
) ? static_cast<void> (0) : __assert_fail ("EltVT == MVT::i8 && \"Only vXi8 vector CTPOP lowering supported.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26211, __PRETTY_FUNCTION__))
;
26212
26213 // Implement a lookup table in register by using an algorithm based on:
26214 // http://wm.ite.pl/articles/sse-popcount.html
26215 //
26216 // The general idea is that every lower byte nibble in the input vector is an
26217 // index into a in-register pre-computed pop count table. We then split up the
26218 // input vector in two new ones: (1) a vector with only the shifted-right
26219 // higher nibbles for each byte and (2) a vector with the lower nibbles (and
26220 // masked out higher ones) for each byte. PSHUFB is used separately with both
26221 // to index the in-register table. Next, both are added and the result is a
26222 // i8 vector where each element contains the pop count for input byte.
26223 const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
26224 /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
26225 /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
26226 /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
26227
26228 SmallVector<SDValue, 64> LUTVec;
26229 for (int i = 0; i < NumElts; ++i)
26230 LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
26231 SDValue InRegLUT = DAG.getBuildVector(VT, DL, LUTVec);
26232 SDValue M0F = DAG.getConstant(0x0F, DL, VT);
26233
26234 // High nibbles
26235 SDValue FourV = DAG.getConstant(4, DL, VT);
26236 SDValue HiNibbles = DAG.getNode(ISD::SRL, DL, VT, Op, FourV);
26237
26238 // Low nibbles
26239 SDValue LoNibbles = DAG.getNode(ISD::AND, DL, VT, Op, M0F);
26240
26241 // The input vector is used as the shuffle mask that index elements into the
26242 // LUT. After counting low and high nibbles, add the vector to obtain the
26243 // final pop count per i8 element.
26244 SDValue HiPopCnt = DAG.getNode(X86ISD::PSHUFB, DL, VT, InRegLUT, HiNibbles);
26245 SDValue LoPopCnt = DAG.getNode(X86ISD::PSHUFB, DL, VT, InRegLUT, LoNibbles);
26246 return DAG.getNode(ISD::ADD, DL, VT, HiPopCnt, LoPopCnt);
26247}
26248
26249// Please ensure that any codegen change from LowerVectorCTPOP is reflected in
26250// updated cost models in X86TTIImpl::getIntrinsicInstrCost.
26251static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget &Subtarget,
26252 SelectionDAG &DAG) {
26253 MVT VT = Op.getSimpleValueType();
26254 assert((VT.is512BitVector() || VT.is256BitVector() || VT.is128BitVector()) &&(((VT.is512BitVector() || VT.is256BitVector() || VT.is128BitVector
()) && "Unknown CTPOP type to handle") ? static_cast<
void> (0) : __assert_fail ("(VT.is512BitVector() || VT.is256BitVector() || VT.is128BitVector()) && \"Unknown CTPOP type to handle\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26255, __PRETTY_FUNCTION__))
26255 "Unknown CTPOP type to handle")(((VT.is512BitVector() || VT.is256BitVector() || VT.is128BitVector
()) && "Unknown CTPOP type to handle") ? static_cast<
void> (0) : __assert_fail ("(VT.is512BitVector() || VT.is256BitVector() || VT.is128BitVector()) && \"Unknown CTPOP type to handle\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26255, __PRETTY_FUNCTION__))
;
26256 SDLoc DL(Op.getNode());
26257 SDValue Op0 = Op.getOperand(0);
26258
26259 // TRUNC(CTPOP(ZEXT(X))) to make use of vXi32/vXi64 VPOPCNT instructions.
26260 if (Subtarget.hasVPOPCNTDQ()) {
26261 unsigned NumElems = VT.getVectorNumElements();
26262 assert((VT.getVectorElementType() == MVT::i8 ||(((VT.getVectorElementType() == MVT::i8 || VT.getVectorElementType
() == MVT::i16) && "Unexpected type") ? static_cast<
void> (0) : __assert_fail ("(VT.getVectorElementType() == MVT::i8 || VT.getVectorElementType() == MVT::i16) && \"Unexpected type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26263, __PRETTY_FUNCTION__))
26263 VT.getVectorElementType() == MVT::i16) && "Unexpected type")(((VT.getVectorElementType() == MVT::i8 || VT.getVectorElementType
() == MVT::i16) && "Unexpected type") ? static_cast<
void> (0) : __assert_fail ("(VT.getVectorElementType() == MVT::i8 || VT.getVectorElementType() == MVT::i16) && \"Unexpected type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26263, __PRETTY_FUNCTION__))
;
26264 if (NumElems < 16 || (NumElems == 16 && Subtarget.canExtendTo512DQ())) {
26265 MVT NewVT = MVT::getVectorVT(MVT::i32, NumElems);
26266 Op = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, Op0);
26267 Op = DAG.getNode(ISD::CTPOP, DL, NewVT, Op);
26268 return DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
26269 }
26270 }
26271
26272 // Decompose 256-bit ops into smaller 128-bit ops.
26273 if (VT.is256BitVector() && !Subtarget.hasInt256())
26274 return Lower256IntUnary(Op, DAG);
26275
26276 // Decompose 512-bit ops into smaller 256-bit ops.
26277 if (VT.is512BitVector() && !Subtarget.hasBWI())
26278 return Lower512IntUnary(Op, DAG);
26279
26280 // For element types greater than i8, do vXi8 pop counts and a bytesum.
26281 if (VT.getScalarType() != MVT::i8) {
26282 MVT ByteVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
26283 SDValue ByteOp = DAG.getBitcast(ByteVT, Op0);
26284 SDValue PopCnt8 = DAG.getNode(ISD::CTPOP, DL, ByteVT, ByteOp);
26285 return LowerHorizontalByteSum(PopCnt8, VT, Subtarget, DAG);
26286 }
26287
26288 // We can't use the fast LUT approach, so fall back on LegalizeDAG.
26289 if (!Subtarget.hasSSSE3())
26290 return SDValue();
26291
26292 return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
26293}
26294
26295static SDValue LowerCTPOP(SDValue Op, const X86Subtarget &Subtarget,
26296 SelectionDAG &DAG) {
26297 assert(Op.getSimpleValueType().isVector() &&((Op.getSimpleValueType().isVector() && "We only do custom lowering for vector population count."
) ? static_cast<void> (0) : __assert_fail ("Op.getSimpleValueType().isVector() && \"We only do custom lowering for vector population count.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26298, __PRETTY_FUNCTION__))
26298 "We only do custom lowering for vector population count.")((Op.getSimpleValueType().isVector() && "We only do custom lowering for vector population count."
) ? static_cast<void> (0) : __assert_fail ("Op.getSimpleValueType().isVector() && \"We only do custom lowering for vector population count.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26298, __PRETTY_FUNCTION__))
;
26299 return LowerVectorCTPOP(Op, Subtarget, DAG);
26300}
26301
26302static SDValue LowerBITREVERSE_XOP(SDValue Op, SelectionDAG &DAG) {
26303 MVT VT = Op.getSimpleValueType();
26304 SDValue In = Op.getOperand(0);
26305 SDLoc DL(Op);
26306
26307 // For scalars, its still beneficial to transfer to/from the SIMD unit to
26308 // perform the BITREVERSE.
26309 if (!VT.isVector()) {
26310 MVT VecVT = MVT::getVectorVT(VT, 128 / VT.getSizeInBits());
26311 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, In);
26312 Res = DAG.getNode(ISD::BITREVERSE, DL, VecVT, Res);
26313 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Res,
26314 DAG.getIntPtrConstant(0, DL));
26315 }
26316
26317 int NumElts = VT.getVectorNumElements();
26318 int ScalarSizeInBytes = VT.getScalarSizeInBits() / 8;
26319
26320 // Decompose 256-bit ops into smaller 128-bit ops.
26321 if (VT.is256BitVector())
26322 return Lower256IntUnary(Op, DAG);
26323
26324 assert(VT.is128BitVector() &&((VT.is128BitVector() && "Only 128-bit vector bitreverse lowering supported."
) ? static_cast<void> (0) : __assert_fail ("VT.is128BitVector() && \"Only 128-bit vector bitreverse lowering supported.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26325, __PRETTY_FUNCTION__))
26325 "Only 128-bit vector bitreverse lowering supported.")((VT.is128BitVector() && "Only 128-bit vector bitreverse lowering supported."
) ? static_cast<void> (0) : __assert_fail ("VT.is128BitVector() && \"Only 128-bit vector bitreverse lowering supported.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26325, __PRETTY_FUNCTION__))
;
26326
26327 // VPPERM reverses the bits of a byte with the permute Op (2 << 5), and we
26328 // perform the BSWAP in the shuffle.
26329 // Its best to shuffle using the second operand as this will implicitly allow
26330 // memory folding for multiple vectors.
26331 SmallVector<SDValue, 16> MaskElts;
26332 for (int i = 0; i != NumElts; ++i) {
26333 for (int j = ScalarSizeInBytes - 1; j >= 0; --j) {
26334 int SourceByte = 16 + (i * ScalarSizeInBytes) + j;
26335 int PermuteByte = SourceByte | (2 << 5);
26336 MaskElts.push_back(DAG.getConstant(PermuteByte, DL, MVT::i8));
26337 }
26338 }
26339
26340 SDValue Mask = DAG.getBuildVector(MVT::v16i8, DL, MaskElts);
26341 SDValue Res = DAG.getBitcast(MVT::v16i8, In);
26342 Res = DAG.getNode(X86ISD::VPPERM, DL, MVT::v16i8, DAG.getUNDEF(MVT::v16i8),
26343 Res, Mask);
26344 return DAG.getBitcast(VT, Res);
26345}
26346
26347static SDValue LowerBITREVERSE(SDValue Op, const X86Subtarget &Subtarget,
26348 SelectionDAG &DAG) {
26349 MVT VT = Op.getSimpleValueType();
26350
26351 if (Subtarget.hasXOP() && !VT.is512BitVector())
26352 return LowerBITREVERSE_XOP(Op, DAG);
26353
26354 assert(Subtarget.hasSSSE3() && "SSSE3 required for BITREVERSE")((Subtarget.hasSSSE3() && "SSSE3 required for BITREVERSE"
) ? static_cast<void> (0) : __assert_fail ("Subtarget.hasSSSE3() && \"SSSE3 required for BITREVERSE\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26354, __PRETTY_FUNCTION__))
;
26355
26356 SDValue In = Op.getOperand(0);
26357 SDLoc DL(Op);
26358
26359 unsigned NumElts = VT.getVectorNumElements();
26360 assert(VT.getScalarType() == MVT::i8 &&((VT.getScalarType() == MVT::i8 && "Only byte vector BITREVERSE supported"
) ? static_cast<void> (0) : __assert_fail ("VT.getScalarType() == MVT::i8 && \"Only byte vector BITREVERSE supported\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26361, __PRETTY_FUNCTION__))
26361 "Only byte vector BITREVERSE supported")((VT.getScalarType() == MVT::i8 && "Only byte vector BITREVERSE supported"
) ? static_cast<void> (0) : __assert_fail ("VT.getScalarType() == MVT::i8 && \"Only byte vector BITREVERSE supported\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26361, __PRETTY_FUNCTION__))
;
26362
26363 // Decompose 256-bit ops into smaller 128-bit ops on pre-AVX2.
26364 if (VT.is256BitVector() && !Subtarget.hasInt256())
26365 return Lower256IntUnary(Op, DAG);
26366
26367 // Perform BITREVERSE using PSHUFB lookups. Each byte is split into
26368 // two nibbles and a PSHUFB lookup to find the bitreverse of each
26369 // 0-15 value (moved to the other nibble).
26370 SDValue NibbleMask = DAG.getConstant(0xF, DL, VT);
26371 SDValue Lo = DAG.getNode(ISD::AND, DL, VT, In, NibbleMask);
26372 SDValue Hi = DAG.getNode(ISD::SRL, DL, VT, In, DAG.getConstant(4, DL, VT));
26373
26374 const int LoLUT[16] = {
26375 /* 0 */ 0x00, /* 1 */ 0x80, /* 2 */ 0x40, /* 3 */ 0xC0,
26376 /* 4 */ 0x20, /* 5 */ 0xA0, /* 6 */ 0x60, /* 7 */ 0xE0,
26377 /* 8 */ 0x10, /* 9 */ 0x90, /* a */ 0x50, /* b */ 0xD0,
26378 /* c */ 0x30, /* d */ 0xB0, /* e */ 0x70, /* f */ 0xF0};
26379 const int HiLUT[16] = {
26380 /* 0 */ 0x00, /* 1 */ 0x08, /* 2 */ 0x04, /* 3 */ 0x0C,
26381 /* 4 */ 0x02, /* 5 */ 0x0A, /* 6 */ 0x06, /* 7 */ 0x0E,
26382 /* 8 */ 0x01, /* 9 */ 0x09, /* a */ 0x05, /* b */ 0x0D,
26383 /* c */ 0x03, /* d */ 0x0B, /* e */ 0x07, /* f */ 0x0F};
26384
26385 SmallVector<SDValue, 16> LoMaskElts, HiMaskElts;
26386 for (unsigned i = 0; i < NumElts; ++i) {
26387 LoMaskElts.push_back(DAG.getConstant(LoLUT[i % 16], DL, MVT::i8));
26388 HiMaskElts.push_back(DAG.getConstant(HiLUT[i % 16], DL, MVT::i8));
26389 }
26390
26391 SDValue LoMask = DAG.getBuildVector(VT, DL, LoMaskElts);
26392 SDValue HiMask = DAG.getBuildVector(VT, DL, HiMaskElts);
26393 Lo = DAG.getNode(X86ISD::PSHUFB, DL, VT, LoMask, Lo);
26394 Hi = DAG.getNode(X86ISD::PSHUFB, DL, VT, HiMask, Hi);
26395 return DAG.getNode(ISD::OR, DL, VT, Lo, Hi);
26396}
26397
26398static SDValue lowerAtomicArithWithLOCK(SDValue N, SelectionDAG &DAG,
26399 const X86Subtarget &Subtarget) {
26400 unsigned NewOpc = 0;
26401 switch (N->getOpcode()) {
26402 case ISD::ATOMIC_LOAD_ADD:
26403 NewOpc = X86ISD::LADD;
26404 break;
26405 case ISD::ATOMIC_LOAD_SUB:
26406 NewOpc = X86ISD::LSUB;
26407 break;
26408 case ISD::ATOMIC_LOAD_OR:
26409 NewOpc = X86ISD::LOR;
26410 break;
26411 case ISD::ATOMIC_LOAD_XOR:
26412 NewOpc = X86ISD::LXOR;
26413 break;
26414 case ISD::ATOMIC_LOAD_AND:
26415 NewOpc = X86ISD::LAND;
26416 break;
26417 default:
26418 llvm_unreachable("Unknown ATOMIC_LOAD_ opcode")::llvm::llvm_unreachable_internal("Unknown ATOMIC_LOAD_ opcode"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26418)
;
26419 }
26420
26421 MachineMemOperand *MMO = cast<MemSDNode>(N)->getMemOperand();
26422
26423 return DAG.getMemIntrinsicNode(
26424 NewOpc, SDLoc(N), DAG.getVTList(MVT::i32, MVT::Other),
26425 {N->getOperand(0), N->getOperand(1), N->getOperand(2)},
26426 /*MemVT=*/N->getSimpleValueType(0), MMO);
26427}
26428
26429/// Lower atomic_load_ops into LOCK-prefixed operations.
26430static SDValue lowerAtomicArith(SDValue N, SelectionDAG &DAG,
26431 const X86Subtarget &Subtarget) {
26432 AtomicSDNode *AN = cast<AtomicSDNode>(N.getNode());
26433 SDValue Chain = N->getOperand(0);
26434 SDValue LHS = N->getOperand(1);
26435 SDValue RHS = N->getOperand(2);
26436 unsigned Opc = N->getOpcode();
26437 MVT VT = N->getSimpleValueType(0);
26438 SDLoc DL(N);
26439
26440 // We can lower atomic_load_add into LXADD. However, any other atomicrmw op
26441 // can only be lowered when the result is unused. They should have already
26442 // been transformed into a cmpxchg loop in AtomicExpand.
26443 if (N->hasAnyUseOfValue(0)) {
26444 // Handle (atomic_load_sub p, v) as (atomic_load_add p, -v), to be able to
26445 // select LXADD if LOCK_SUB can't be selected.
26446 if (Opc == ISD::ATOMIC_LOAD_SUB) {
26447 RHS = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), RHS);
26448 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, DL, VT, Chain, LHS,
26449 RHS, AN->getMemOperand());
26450 }
26451 assert(Opc == ISD::ATOMIC_LOAD_ADD &&((Opc == ISD::ATOMIC_LOAD_ADD && "Used AtomicRMW ops other than Add should have been expanded!"
) ? static_cast<void> (0) : __assert_fail ("Opc == ISD::ATOMIC_LOAD_ADD && \"Used AtomicRMW ops other than Add should have been expanded!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26452, __PRETTY_FUNCTION__))
26452 "Used AtomicRMW ops other than Add should have been expanded!")((Opc == ISD::ATOMIC_LOAD_ADD && "Used AtomicRMW ops other than Add should have been expanded!"
) ? static_cast<void> (0) : __assert_fail ("Opc == ISD::ATOMIC_LOAD_ADD && \"Used AtomicRMW ops other than Add should have been expanded!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26452, __PRETTY_FUNCTION__))
;
26453 return N;
26454 }
26455
26456 // Specialized lowering for the canonical form of an idemptotent atomicrmw.
26457 // The core idea here is that since the memory location isn't actually
26458 // changing, all we need is a lowering for the *ordering* impacts of the
26459 // atomicrmw. As such, we can chose a different operation and memory
26460 // location to minimize impact on other code.
26461 if (Opc == ISD::ATOMIC_LOAD_OR && isNullConstant(RHS)) {
26462 // On X86, the only ordering which actually requires an instruction is
26463 // seq_cst which isn't SingleThread, everything just needs to be preserved
26464 // during codegen and then dropped. Note that we expect (but don't assume),
26465 // that orderings other than seq_cst and acq_rel have been canonicalized to
26466 // a store or load.
26467 if (AN->getOrdering() == AtomicOrdering::SequentiallyConsistent &&
26468 AN->getSyncScopeID() == SyncScope::System) {
26469 // Prefer a locked operation against a stack location to minimize cache
26470 // traffic. This assumes that stack locations are very likely to be
26471 // accessed only by the owning thread.
26472 SDValue NewChain = emitLockedStackOp(DAG, Subtarget, Chain, DL);
26473 assert(!N->hasAnyUseOfValue(0))((!N->hasAnyUseOfValue(0)) ? static_cast<void> (0) :
__assert_fail ("!N->hasAnyUseOfValue(0)", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26473, __PRETTY_FUNCTION__))
;
26474 // NOTE: The getUNDEF is needed to give something for the unused result 0.
26475 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(),
26476 DAG.getUNDEF(VT), NewChain);
26477 }
26478 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
26479 SDValue NewChain = DAG.getNode(X86ISD::MEMBARRIER, DL, MVT::Other, Chain);
26480 assert(!N->hasAnyUseOfValue(0))((!N->hasAnyUseOfValue(0)) ? static_cast<void> (0) :
__assert_fail ("!N->hasAnyUseOfValue(0)", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26480, __PRETTY_FUNCTION__))
;
26481 // NOTE: The getUNDEF is needed to give something for the unused result 0.
26482 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(),
26483 DAG.getUNDEF(VT), NewChain);
26484 }
26485
26486 SDValue LockOp = lowerAtomicArithWithLOCK(N, DAG, Subtarget);
26487 // RAUW the chain, but don't worry about the result, as it's unused.
26488 assert(!N->hasAnyUseOfValue(0))((!N->hasAnyUseOfValue(0)) ? static_cast<void> (0) :
__assert_fail ("!N->hasAnyUseOfValue(0)", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26488, __PRETTY_FUNCTION__))
;
26489 // NOTE: The getUNDEF is needed to give something for the unused result 0.
26490 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(),
26491 DAG.getUNDEF(VT), LockOp.getValue(1));
26492}
26493
26494static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG,
26495 const X86Subtarget &Subtarget) {
26496 auto *Node = cast<AtomicSDNode>(Op.getNode());
26497 SDLoc dl(Node);
26498 EVT VT = Node->getMemoryVT();
26499
26500 bool IsSeqCst = Node->getOrdering() == AtomicOrdering::SequentiallyConsistent;
26501 bool IsTypeLegal = DAG.getTargetLoweringInfo().isTypeLegal(VT);
26502
26503 // If this store is not sequentially consistent and the type is legal
26504 // we can just keep it.
26505 if (!IsSeqCst && IsTypeLegal)
26506 return Op;
26507
26508 if (VT == MVT::i64 && !IsTypeLegal) {
26509 // For illegal i64 atomic_stores, we can try to use MOVQ if SSE2 is enabled.
26510 // FIXME: Use movlps with SSE1.
26511 // FIXME: Use fist with X87.
26512 bool NoImplicitFloatOps =
26513 DAG.getMachineFunction().getFunction().hasFnAttribute(
26514 Attribute::NoImplicitFloat);
26515 if (!Subtarget.useSoftFloat() && !NoImplicitFloatOps &&
26516 Subtarget.hasSSE2()) {
26517 SDValue SclToVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
26518 Node->getOperand(2));
26519 SDVTList Tys = DAG.getVTList(MVT::Other);
26520 SDValue Ops[] = { Node->getChain(), SclToVec, Node->getBasePtr() };
26521 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::VEXTRACT_STORE, dl, Tys,
26522 Ops, MVT::i64,
26523 Node->getMemOperand());
26524
26525 // If this is a sequentially consistent store, also emit an appropriate
26526 // barrier.
26527 if (IsSeqCst)
26528 Chain = emitLockedStackOp(DAG, Subtarget, Chain, dl);
26529
26530 return Chain;
26531 }
26532 }
26533
26534 // Convert seq_cst store -> xchg
26535 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
26536 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
26537 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
26538 Node->getMemoryVT(),
26539 Node->getOperand(0),
26540 Node->getOperand(1), Node->getOperand(2),
26541 Node->getMemOperand());
26542 return Swap.getValue(1);
26543}
26544
26545static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) {
26546 SDNode *N = Op.getNode();
26547 MVT VT = N->getSimpleValueType(0);
26548
26549 // Let legalize expand this if it isn't a legal type yet.
26550 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
26551 return SDValue();
26552
26553 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
26554 SDLoc DL(N);
26555
26556 // Set the carry flag.
26557 SDValue Carry = Op.getOperand(2);
26558 EVT CarryVT = Carry.getValueType();
26559 APInt NegOne = APInt::getAllOnesValue(CarryVT.getScalarSizeInBits());
26560 Carry = DAG.getNode(X86ISD::ADD, DL, DAG.getVTList(CarryVT, MVT::i32),
26561 Carry, DAG.getConstant(NegOne, DL, CarryVT));
26562
26563 unsigned Opc = Op.getOpcode() == ISD::ADDCARRY ? X86ISD::ADC : X86ISD::SBB;
26564 SDValue Sum = DAG.getNode(Opc, DL, VTs, Op.getOperand(0),
26565 Op.getOperand(1), Carry.getValue(1));
26566
26567 SDValue SetCC = getSETCC(X86::COND_B, Sum.getValue(1), DL, DAG);
26568 if (N->getValueType(1) == MVT::i1)
26569 SetCC = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, SetCC);
26570
26571 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
26572}
26573
26574static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget &Subtarget,
26575 SelectionDAG &DAG) {
26576 assert(Subtarget.isTargetDarwin() && Subtarget.is64Bit())((Subtarget.isTargetDarwin() && Subtarget.is64Bit()) ?
static_cast<void> (0) : __assert_fail ("Subtarget.isTargetDarwin() && Subtarget.is64Bit()"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26576, __PRETTY_FUNCTION__))
;
26577
26578 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
26579 // which returns the values as { float, float } (in XMM0) or
26580 // { double, double } (which is returned in XMM0, XMM1).
26581 SDLoc dl(Op);
26582 SDValue Arg = Op.getOperand(0);
26583 EVT ArgVT = Arg.getValueType();
26584 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
26585
26586 TargetLowering::ArgListTy Args;
26587 TargetLowering::ArgListEntry Entry;
26588
26589 Entry.Node = Arg;
26590 Entry.Ty = ArgTy;
26591 Entry.IsSExt = false;
26592 Entry.IsZExt = false;
26593 Args.push_back(Entry);
26594
26595 bool isF64 = ArgVT == MVT::f64;
26596 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
26597 // the small struct {f32, f32} is returned in (eax, edx). For f64,
26598 // the results are returned via SRet in memory.
26599 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26600 RTLIB::Libcall LC = isF64 ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32;
26601 const char *LibcallName = TLI.getLibcallName(LC);
26602 SDValue Callee =
26603 DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
26604
26605 Type *RetTy = isF64 ? (Type *)StructType::get(ArgTy, ArgTy)
26606 : (Type *)VectorType::get(ArgTy, 4);
26607
26608 TargetLowering::CallLoweringInfo CLI(DAG);
26609 CLI.setDebugLoc(dl)
26610 .setChain(DAG.getEntryNode())
26611 .setLibCallee(CallingConv::C, RetTy, Callee, std::move(Args));
26612
26613 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
26614
26615 if (isF64)
26616 // Returned in xmm0 and xmm1.
26617 return CallResult.first;
26618
26619 // Returned in bits 0:31 and 32:64 xmm0.
26620 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
26621 CallResult.first, DAG.getIntPtrConstant(0, dl));
26622 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
26623 CallResult.first, DAG.getIntPtrConstant(1, dl));
26624 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
26625 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
26626}
26627
26628/// Widen a vector input to a vector of NVT. The
26629/// input vector must have the same element type as NVT.
26630static SDValue ExtendToType(SDValue InOp, MVT NVT, SelectionDAG &DAG,
26631 bool FillWithZeroes = false) {
26632 // Check if InOp already has the right width.
26633 MVT InVT = InOp.getSimpleValueType();
26634 if (InVT == NVT)
26635 return InOp;
26636
26637 if (InOp.isUndef())
26638 return DAG.getUNDEF(NVT);
26639
26640 assert(InVT.getVectorElementType() == NVT.getVectorElementType() &&((InVT.getVectorElementType() == NVT.getVectorElementType() &&
"input and widen element type must match") ? static_cast<
void> (0) : __assert_fail ("InVT.getVectorElementType() == NVT.getVectorElementType() && \"input and widen element type must match\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26641, __PRETTY_FUNCTION__))
26641 "input and widen element type must match")((InVT.getVectorElementType() == NVT.getVectorElementType() &&
"input and widen element type must match") ? static_cast<
void> (0) : __assert_fail ("InVT.getVectorElementType() == NVT.getVectorElementType() && \"input and widen element type must match\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26641, __PRETTY_FUNCTION__))
;
26642
26643 unsigned InNumElts = InVT.getVectorNumElements();
26644 unsigned WidenNumElts = NVT.getVectorNumElements();
26645 assert(WidenNumElts > InNumElts && WidenNumElts % InNumElts == 0 &&((WidenNumElts > InNumElts && WidenNumElts % InNumElts
== 0 && "Unexpected request for vector widening") ? static_cast
<void> (0) : __assert_fail ("WidenNumElts > InNumElts && WidenNumElts % InNumElts == 0 && \"Unexpected request for vector widening\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26646, __PRETTY_FUNCTION__))
26646 "Unexpected request for vector widening")((WidenNumElts > InNumElts && WidenNumElts % InNumElts
== 0 && "Unexpected request for vector widening") ? static_cast
<void> (0) : __assert_fail ("WidenNumElts > InNumElts && WidenNumElts % InNumElts == 0 && \"Unexpected request for vector widening\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26646, __PRETTY_FUNCTION__))
;
26647
26648 SDLoc dl(InOp);
26649 if (InOp.getOpcode() == ISD::CONCAT_VECTORS &&
26650 InOp.getNumOperands() == 2) {
26651 SDValue N1 = InOp.getOperand(1);
26652 if ((ISD::isBuildVectorAllZeros(N1.getNode()) && FillWithZeroes) ||
26653 N1.isUndef()) {
26654 InOp = InOp.getOperand(0);
26655 InVT = InOp.getSimpleValueType();
26656 InNumElts = InVT.getVectorNumElements();
26657 }
26658 }
26659 if (ISD::isBuildVectorOfConstantSDNodes(InOp.getNode()) ||
26660 ISD::isBuildVectorOfConstantFPSDNodes(InOp.getNode())) {
26661 SmallVector<SDValue, 16> Ops;
26662 for (unsigned i = 0; i < InNumElts; ++i)
26663 Ops.push_back(InOp.getOperand(i));
26664
26665 EVT EltVT = InOp.getOperand(0).getValueType();
26666
26667 SDValue FillVal = FillWithZeroes ? DAG.getConstant(0, dl, EltVT) :
26668 DAG.getUNDEF(EltVT);
26669 for (unsigned i = 0; i < WidenNumElts - InNumElts; ++i)
26670 Ops.push_back(FillVal);
26671 return DAG.getBuildVector(NVT, dl, Ops);
26672 }
26673 SDValue FillVal = FillWithZeroes ? DAG.getConstant(0, dl, NVT) :
26674 DAG.getUNDEF(NVT);
26675 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, NVT, FillVal,
26676 InOp, DAG.getIntPtrConstant(0, dl));
26677}
26678
26679static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget &Subtarget,
26680 SelectionDAG &DAG) {
26681 assert(Subtarget.hasAVX512() &&((Subtarget.hasAVX512() && "MGATHER/MSCATTER are supported on AVX-512 arch only"
) ? static_cast<void> (0) : __assert_fail ("Subtarget.hasAVX512() && \"MGATHER/MSCATTER are supported on AVX-512 arch only\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26682, __PRETTY_FUNCTION__))
26682 "MGATHER/MSCATTER are supported on AVX-512 arch only")((Subtarget.hasAVX512() && "MGATHER/MSCATTER are supported on AVX-512 arch only"
) ? static_cast<void> (0) : __assert_fail ("Subtarget.hasAVX512() && \"MGATHER/MSCATTER are supported on AVX-512 arch only\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26682, __PRETTY_FUNCTION__))
;
26683
26684 MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
26685 SDValue Src = N->getValue();
26686 MVT VT = Src.getSimpleValueType();
26687 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op")((VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op"
) ? static_cast<void> (0) : __assert_fail ("VT.getScalarSizeInBits() >= 32 && \"Unsupported scatter op\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26687, __PRETTY_FUNCTION__))
;
26688 SDLoc dl(Op);
26689
26690 SDValue Scale = N->getScale();
26691 SDValue Index = N->getIndex();
26692 SDValue Mask = N->getMask();
26693 SDValue Chain = N->getChain();
26694 SDValue BasePtr = N->getBasePtr();
26695
26696 if (VT == MVT::v2f32) {
26697 assert(Mask.getValueType() == MVT::v2i1 && "Unexpected mask type")((Mask.getValueType() == MVT::v2i1 && "Unexpected mask type"
) ? static_cast<void> (0) : __assert_fail ("Mask.getValueType() == MVT::v2i1 && \"Unexpected mask type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26697, __PRETTY_FUNCTION__))
;
26698 // If the index is v2i64 and we have VLX we can use xmm for data and index.
26699 if (Index.getValueType() == MVT::v2i64 && Subtarget.hasVLX()) {
26700 Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32, Src,
26701 DAG.getUNDEF(MVT::v2f32));
26702 SDVTList VTs = DAG.getVTList(MVT::v2i1, MVT::Other);
26703 SDValue Ops[] = {Chain, Src, Mask, BasePtr, Index, Scale};
26704 SDValue NewScatter = DAG.getTargetMemSDNode<X86MaskedScatterSDNode>(
26705 VTs, Ops, dl, N->getMemoryVT(), N->getMemOperand());
26706 return SDValue(NewScatter.getNode(), 1);
26707 }
26708 return SDValue();
26709 }
26710
26711 if (VT == MVT::v2i32) {
26712 assert(Mask.getValueType() == MVT::v2i1 && "Unexpected mask type")((Mask.getValueType() == MVT::v2i1 && "Unexpected mask type"
) ? static_cast<void> (0) : __assert_fail ("Mask.getValueType() == MVT::v2i1 && \"Unexpected mask type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26712, __PRETTY_FUNCTION__))
;
26713 Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
26714 DAG.getUNDEF(MVT::v2i32));
26715 // If the index is v2i64 and we have VLX we can use xmm for data and index.
26716 if (Index.getValueType() == MVT::v2i64 && Subtarget.hasVLX()) {
26717 SDVTList VTs = DAG.getVTList(MVT::v2i1, MVT::Other);
26718 SDValue Ops[] = {Chain, Src, Mask, BasePtr, Index, Scale};
26719 SDValue NewScatter = DAG.getTargetMemSDNode<X86MaskedScatterSDNode>(
26720 VTs, Ops, dl, N->getMemoryVT(), N->getMemOperand());
26721 return SDValue(NewScatter.getNode(), 1);
26722 }
26723 // Custom widen all the operands to avoid promotion.
26724 EVT NewIndexVT = EVT::getVectorVT(
26725 *DAG.getContext(), Index.getValueType().getVectorElementType(), 4);
26726 Index = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewIndexVT, Index,
26727 DAG.getUNDEF(Index.getValueType()));
26728 Mask = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i1, Mask,
26729 DAG.getConstant(0, dl, MVT::v2i1));
26730 SDValue Ops[] = {Chain, Src, Mask, BasePtr, Index, Scale};
26731 return DAG.getMaskedScatter(DAG.getVTList(MVT::Other), N->getMemoryVT(), dl,
26732 Ops, N->getMemOperand());
26733 }
26734
26735 MVT IndexVT = Index.getSimpleValueType();
26736 MVT MaskVT = Mask.getSimpleValueType();
26737
26738 // If the index is v2i32, we're being called by type legalization and we
26739 // should just let the default handling take care of it.
26740 if (IndexVT == MVT::v2i32)
26741 return SDValue();
26742
26743 // If we don't have VLX and neither the passthru or index is 512-bits, we
26744 // need to widen until one is.
26745 if (!Subtarget.hasVLX() && !VT.is512BitVector() &&
26746 !Index.getSimpleValueType().is512BitVector()) {
26747 // Determine how much we need to widen by to get a 512-bit type.
26748 unsigned Factor = std::min(512/VT.getSizeInBits(),
26749 512/IndexVT.getSizeInBits());
26750 unsigned NumElts = VT.getVectorNumElements() * Factor;
26751
26752 VT = MVT::getVectorVT(VT.getVectorElementType(), NumElts);
26753 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), NumElts);
26754 MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
26755
26756 Src = ExtendToType(Src, VT, DAG);
26757 Index = ExtendToType(Index, IndexVT, DAG);
26758 Mask = ExtendToType(Mask, MaskVT, DAG, true);
26759 }
26760
26761 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
26762 SDValue Ops[] = {Chain, Src, Mask, BasePtr, Index, Scale};
26763 SDValue NewScatter = DAG.getTargetMemSDNode<X86MaskedScatterSDNode>(
26764 VTs, Ops, dl, N->getMemoryVT(), N->getMemOperand());
26765 return SDValue(NewScatter.getNode(), 1);
26766}
26767
26768static SDValue LowerMLOAD(SDValue Op, const X86Subtarget &Subtarget,
26769 SelectionDAG &DAG) {
26770
26771 MaskedLoadSDNode *N = cast<MaskedLoadSDNode>(Op.getNode());
26772 MVT VT = Op.getSimpleValueType();
26773 MVT ScalarVT = VT.getScalarType();
26774 SDValue Mask = N->getMask();
26775 SDLoc dl(Op);
26776
26777 assert((!N->isExpandingLoad() || Subtarget.hasAVX512()) &&(((!N->isExpandingLoad() || Subtarget.hasAVX512()) &&
"Expanding masked load is supported on AVX-512 target only!"
) ? static_cast<void> (0) : __assert_fail ("(!N->isExpandingLoad() || Subtarget.hasAVX512()) && \"Expanding masked load is supported on AVX-512 target only!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26778, __PRETTY_FUNCTION__))
26778 "Expanding masked load is supported on AVX-512 target only!")(((!N->isExpandingLoad() || Subtarget.hasAVX512()) &&
"Expanding masked load is supported on AVX-512 target only!"
) ? static_cast<void> (0) : __assert_fail ("(!N->isExpandingLoad() || Subtarget.hasAVX512()) && \"Expanding masked load is supported on AVX-512 target only!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26778, __PRETTY_FUNCTION__))
;
26779
26780 assert((!N->isExpandingLoad() || ScalarVT.getSizeInBits() >= 32) &&(((!N->isExpandingLoad() || ScalarVT.getSizeInBits() >=
32) && "Expanding masked load is supported for 32 and 64-bit types only!"
) ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26781, __PRETTY_FUNCTION__))
26781 "Expanding masked load is supported for 32 and 64-bit types only!")(((!N->isExpandingLoad() || ScalarVT.getSizeInBits() >=
32) && "Expanding masked load is supported for 32 and 64-bit types only!"
) ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26781, __PRETTY_FUNCTION__))
;
26782
26783 assert(Subtarget.hasAVX512() && !Subtarget.hasVLX() && !VT.is512BitVector() &&((Subtarget.hasAVX512() && !Subtarget.hasVLX() &&
!VT.is512BitVector() && "Cannot lower masked load op."
) ? static_cast<void> (0) : __assert_fail ("Subtarget.hasAVX512() && !Subtarget.hasVLX() && !VT.is512BitVector() && \"Cannot lower masked load op.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26784, __PRETTY_FUNCTION__))
26784 "Cannot lower masked load op.")((Subtarget.hasAVX512() && !Subtarget.hasVLX() &&
!VT.is512BitVector() && "Cannot lower masked load op."
) ? static_cast<void> (0) : __assert_fail ("Subtarget.hasAVX512() && !Subtarget.hasVLX() && !VT.is512BitVector() && \"Cannot lower masked load op.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26784, __PRETTY_FUNCTION__))
;
26785
26786 assert((ScalarVT.getSizeInBits() >= 32 ||(((ScalarVT.getSizeInBits() >= 32 || (Subtarget.hasBWI() &&
(ScalarVT == MVT::i8 || ScalarVT == MVT::i16))) && "Unsupported masked load op."
) ? static_cast<void> (0) : __assert_fail ("(ScalarVT.getSizeInBits() >= 32 || (Subtarget.hasBWI() && (ScalarVT == MVT::i8 || ScalarVT == MVT::i16))) && \"Unsupported masked load op.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26789, __PRETTY_FUNCTION__))
26787 (Subtarget.hasBWI() &&(((ScalarVT.getSizeInBits() >= 32 || (Subtarget.hasBWI() &&
(ScalarVT == MVT::i8 || ScalarVT == MVT::i16))) && "Unsupported masked load op."
) ? static_cast<void> (0) : __assert_fail ("(ScalarVT.getSizeInBits() >= 32 || (Subtarget.hasBWI() && (ScalarVT == MVT::i8 || ScalarVT == MVT::i16))) && \"Unsupported masked load op.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26789, __PRETTY_FUNCTION__))
26788 (ScalarVT == MVT::i8 || ScalarVT == MVT::i16))) &&(((ScalarVT.getSizeInBits() >= 32 || (Subtarget.hasBWI() &&
(ScalarVT == MVT::i8 || ScalarVT == MVT::i16))) && "Unsupported masked load op."
) ? static_cast<void> (0) : __assert_fail ("(ScalarVT.getSizeInBits() >= 32 || (Subtarget.hasBWI() && (ScalarVT == MVT::i8 || ScalarVT == MVT::i16))) && \"Unsupported masked load op.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26789, __PRETTY_FUNCTION__))
26789 "Unsupported masked load op.")(((ScalarVT.getSizeInBits() >= 32 || (Subtarget.hasBWI() &&
(ScalarVT == MVT::i8 || ScalarVT == MVT::i16))) && "Unsupported masked load op."
) ? static_cast<void> (0) : __assert_fail ("(ScalarVT.getSizeInBits() >= 32 || (Subtarget.hasBWI() && (ScalarVT == MVT::i8 || ScalarVT == MVT::i16))) && \"Unsupported masked load op.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26789, __PRETTY_FUNCTION__))
;
26790
26791 // This operation is legal for targets with VLX, but without
26792 // VLX the vector should be widened to 512 bit
26793 unsigned NumEltsInWideVec = 512 / VT.getScalarSizeInBits();
26794 MVT WideDataVT = MVT::getVectorVT(ScalarVT, NumEltsInWideVec);
26795 SDValue PassThru = ExtendToType(N->getPassThru(), WideDataVT, DAG);
26796
26797 // Mask element has to be i1.
26798 assert(Mask.getSimpleValueType().getScalarType() == MVT::i1 &&((Mask.getSimpleValueType().getScalarType() == MVT::i1 &&
"Unexpected mask type") ? static_cast<void> (0) : __assert_fail
("Mask.getSimpleValueType().getScalarType() == MVT::i1 && \"Unexpected mask type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26799, __PRETTY_FUNCTION__))
26799 "Unexpected mask type")((Mask.getSimpleValueType().getScalarType() == MVT::i1 &&
"Unexpected mask type") ? static_cast<void> (0) : __assert_fail
("Mask.getSimpleValueType().getScalarType() == MVT::i1 && \"Unexpected mask type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26799, __PRETTY_FUNCTION__))
;
26800
26801 MVT WideMaskVT = MVT::getVectorVT(MVT::i1, NumEltsInWideVec);
26802
26803 Mask = ExtendToType(Mask, WideMaskVT, DAG, true);
26804 SDValue NewLoad = DAG.getMaskedLoad(WideDataVT, dl, N->getChain(),
26805 N->getBasePtr(), Mask, PassThru,
26806 N->getMemoryVT(), N->getMemOperand(),
26807 N->getExtensionType(),
26808 N->isExpandingLoad());
26809
26810 SDValue Exract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
26811 NewLoad.getValue(0),
26812 DAG.getIntPtrConstant(0, dl));
26813 SDValue RetOps[] = {Exract, NewLoad.getValue(1)};
26814 return DAG.getMergeValues(RetOps, dl);
26815}
26816
26817static SDValue LowerMSTORE(SDValue Op, const X86Subtarget &Subtarget,
26818 SelectionDAG &DAG) {
26819 MaskedStoreSDNode *N = cast<MaskedStoreSDNode>(Op.getNode());
26820 SDValue DataToStore = N->getValue();
26821 MVT VT = DataToStore.getSimpleValueType();
26822 MVT ScalarVT = VT.getScalarType();
26823 SDValue Mask = N->getMask();
26824 SDLoc dl(Op);
26825
26826 assert((!N->isCompressingStore() || Subtarget.hasAVX512()) &&(((!N->isCompressingStore() || Subtarget.hasAVX512()) &&
"Expanding masked load is supported on AVX-512 target only!"
) ? static_cast<void> (0) : __assert_fail ("(!N->isCompressingStore() || Subtarget.hasAVX512()) && \"Expanding masked load is supported on AVX-512 target only!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26827, __PRETTY_FUNCTION__))
26827 "Expanding masked load is supported on AVX-512 target only!")(((!N->isCompressingStore() || Subtarget.hasAVX512()) &&
"Expanding masked load is supported on AVX-512 target only!"
) ? static_cast<void> (0) : __assert_fail ("(!N->isCompressingStore() || Subtarget.hasAVX512()) && \"Expanding masked load is supported on AVX-512 target only!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26827, __PRETTY_FUNCTION__))
;
26828
26829 assert((!N->isCompressingStore() || ScalarVT.getSizeInBits() >= 32) &&(((!N->isCompressingStore() || ScalarVT.getSizeInBits() >=
32) && "Expanding masked load is supported for 32 and 64-bit types only!"
) ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26830, __PRETTY_FUNCTION__))
26830 "Expanding masked load is supported for 32 and 64-bit types only!")(((!N->isCompressingStore() || ScalarVT.getSizeInBits() >=
32) && "Expanding masked load is supported for 32 and 64-bit types only!"
) ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26830, __PRETTY_FUNCTION__))
;
26831
26832 assert(Subtarget.hasAVX512() && !Subtarget.hasVLX() && !VT.is512BitVector() &&((Subtarget.hasAVX512() && !Subtarget.hasVLX() &&
!VT.is512BitVector() && "Cannot lower masked store op."
) ? static_cast<void> (0) : __assert_fail ("Subtarget.hasAVX512() && !Subtarget.hasVLX() && !VT.is512BitVector() && \"Cannot lower masked store op.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26833, __PRETTY_FUNCTION__))
26833 "Cannot lower masked store op.")((Subtarget.hasAVX512() && !Subtarget.hasVLX() &&
!VT.is512BitVector() && "Cannot lower masked store op."
) ? static_cast<void> (0) : __assert_fail ("Subtarget.hasAVX512() && !Subtarget.hasVLX() && !VT.is512BitVector() && \"Cannot lower masked store op.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26833, __PRETTY_FUNCTION__))
;
26834
26835 assert((ScalarVT.getSizeInBits() >= 32 ||(((ScalarVT.getSizeInBits() >= 32 || (Subtarget.hasBWI() &&
(ScalarVT == MVT::i8 || ScalarVT == MVT::i16))) && "Unsupported masked store op."
) ? static_cast<void> (0) : __assert_fail ("(ScalarVT.getSizeInBits() >= 32 || (Subtarget.hasBWI() && (ScalarVT == MVT::i8 || ScalarVT == MVT::i16))) && \"Unsupported masked store op.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26838, __PRETTY_FUNCTION__))
26836 (Subtarget.hasBWI() &&(((ScalarVT.getSizeInBits() >= 32 || (Subtarget.hasBWI() &&
(ScalarVT == MVT::i8 || ScalarVT == MVT::i16))) && "Unsupported masked store op."
) ? static_cast<void> (0) : __assert_fail ("(ScalarVT.getSizeInBits() >= 32 || (Subtarget.hasBWI() && (ScalarVT == MVT::i8 || ScalarVT == MVT::i16))) && \"Unsupported masked store op.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26838, __PRETTY_FUNCTION__))
26837 (ScalarVT == MVT::i8 || ScalarVT == MVT::i16))) &&(((ScalarVT.getSizeInBits() >= 32 || (Subtarget.hasBWI() &&
(ScalarVT == MVT::i8 || ScalarVT == MVT::i16))) && "Unsupported masked store op."
) ? static_cast<void> (0) : __assert_fail ("(ScalarVT.getSizeInBits() >= 32 || (Subtarget.hasBWI() && (ScalarVT == MVT::i8 || ScalarVT == MVT::i16))) && \"Unsupported masked store op.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26838, __PRETTY_FUNCTION__))
26838 "Unsupported masked store op.")(((ScalarVT.getSizeInBits() >= 32 || (Subtarget.hasBWI() &&
(ScalarVT == MVT::i8 || ScalarVT == MVT::i16))) && "Unsupported masked store op."
) ? static_cast<void> (0) : __assert_fail ("(ScalarVT.getSizeInBits() >= 32 || (Subtarget.hasBWI() && (ScalarVT == MVT::i8 || ScalarVT == MVT::i16))) && \"Unsupported masked store op.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26838, __PRETTY_FUNCTION__))
;
26839
26840 // This operation is legal for targets with VLX, but without
26841 // VLX the vector should be widened to 512 bit
26842 unsigned NumEltsInWideVec = 512/VT.getScalarSizeInBits();
26843 MVT WideDataVT = MVT::getVectorVT(ScalarVT, NumEltsInWideVec);
26844
26845 // Mask element has to be i1.
26846 assert(Mask.getSimpleValueType().getScalarType() == MVT::i1 &&((Mask.getSimpleValueType().getScalarType() == MVT::i1 &&
"Unexpected mask type") ? static_cast<void> (0) : __assert_fail
("Mask.getSimpleValueType().getScalarType() == MVT::i1 && \"Unexpected mask type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26847, __PRETTY_FUNCTION__))
26847 "Unexpected mask type")((Mask.getSimpleValueType().getScalarType() == MVT::i1 &&
"Unexpected mask type") ? static_cast<void> (0) : __assert_fail
("Mask.getSimpleValueType().getScalarType() == MVT::i1 && \"Unexpected mask type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26847, __PRETTY_FUNCTION__))
;
26848
26849 MVT WideMaskVT = MVT::getVectorVT(MVT::i1, NumEltsInWideVec);
26850
26851 DataToStore = ExtendToType(DataToStore, WideDataVT, DAG);
26852 Mask = ExtendToType(Mask, WideMaskVT, DAG, true);
26853 return DAG.getMaskedStore(N->getChain(), dl, DataToStore, N->getBasePtr(),
26854 Mask, N->getMemoryVT(), N->getMemOperand(),
26855 N->isTruncatingStore(), N->isCompressingStore());
26856}
26857
26858static SDValue LowerMGATHER(SDValue Op, const X86Subtarget &Subtarget,
26859 SelectionDAG &DAG) {
26860 assert(Subtarget.hasAVX2() &&((Subtarget.hasAVX2() && "MGATHER/MSCATTER are supported on AVX-512/AVX-2 arch only"
) ? static_cast<void> (0) : __assert_fail ("Subtarget.hasAVX2() && \"MGATHER/MSCATTER are supported on AVX-512/AVX-2 arch only\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26861, __PRETTY_FUNCTION__))
26861 "MGATHER/MSCATTER are supported on AVX-512/AVX-2 arch only")((Subtarget.hasAVX2() && "MGATHER/MSCATTER are supported on AVX-512/AVX-2 arch only"
) ? static_cast<void> (0) : __assert_fail ("Subtarget.hasAVX2() && \"MGATHER/MSCATTER are supported on AVX-512/AVX-2 arch only\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26861, __PRETTY_FUNCTION__))
;
26862
26863 MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
26864 SDLoc dl(Op);
26865 MVT VT = Op.getSimpleValueType();
26866 SDValue Index = N->getIndex();
26867 SDValue Mask = N->getMask();
26868 SDValue PassThru = N->getPassThru();
26869 MVT IndexVT = Index.getSimpleValueType();
26870 MVT MaskVT = Mask.getSimpleValueType();
26871
26872 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op")((VT.getScalarSizeInBits() >= 32 && "Unsupported gather op"
) ? static_cast<void> (0) : __assert_fail ("VT.getScalarSizeInBits() >= 32 && \"Unsupported gather op\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26872, __PRETTY_FUNCTION__))
;
26873
26874 // If the index is v2i32, we're being called by type legalization.
26875 if (IndexVT == MVT::v2i32)
26876 return SDValue();
26877
26878 // If we don't have VLX and neither the passthru or index is 512-bits, we
26879 // need to widen until one is.
26880 MVT OrigVT = VT;
26881 if (Subtarget.hasAVX512() && !Subtarget.hasVLX() && !VT.is512BitVector() &&
26882 !IndexVT.is512BitVector()) {
26883 // Determine how much we need to widen by to get a 512-bit type.
26884 unsigned Factor = std::min(512/VT.getSizeInBits(),
26885 512/IndexVT.getSizeInBits());
26886
26887 unsigned NumElts = VT.getVectorNumElements() * Factor;
26888
26889 VT = MVT::getVectorVT(VT.getVectorElementType(), NumElts);
26890 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), NumElts);
26891 MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
26892
26893 PassThru = ExtendToType(PassThru, VT, DAG);
26894 Index = ExtendToType(Index, IndexVT, DAG);
26895 Mask = ExtendToType(Mask, MaskVT, DAG, true);
26896 }
26897
26898 SDValue Ops[] = { N->getChain(), PassThru, Mask, N->getBasePtr(), Index,
26899 N->getScale() };
26900 SDValue NewGather = DAG.getTargetMemSDNode<X86MaskedGatherSDNode>(
26901 DAG.getVTList(VT, MaskVT, MVT::Other), Ops, dl, N->getMemoryVT(),
26902 N->getMemOperand());
26903 SDValue Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OrigVT,
26904 NewGather, DAG.getIntPtrConstant(0, dl));
26905 return DAG.getMergeValues({Extract, NewGather.getValue(2)}, dl);
26906}
26907
26908SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
26909 SelectionDAG &DAG) const {
26910 // TODO: Eventually, the lowering of these nodes should be informed by or
26911 // deferred to the GC strategy for the function in which they appear. For
26912 // now, however, they must be lowered to something. Since they are logically
26913 // no-ops in the case of a null GC strategy (or a GC strategy which does not
26914 // require special handling for these nodes), lower them as literal NOOPs for
26915 // the time being.
26916 SmallVector<SDValue, 2> Ops;
26917
26918 Ops.push_back(Op.getOperand(0));
26919 if (Op->getGluedNode())
26920 Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
26921
26922 SDLoc OpDL(Op);
26923 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
26924 SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
26925
26926 return NOOP;
26927}
26928
26929SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
26930 SelectionDAG &DAG) const {
26931 // TODO: Eventually, the lowering of these nodes should be informed by or
26932 // deferred to the GC strategy for the function in which they appear. For
26933 // now, however, they must be lowered to something. Since they are logically
26934 // no-ops in the case of a null GC strategy (or a GC strategy which does not
26935 // require special handling for these nodes), lower them as literal NOOPs for
26936 // the time being.
26937 SmallVector<SDValue, 2> Ops;
26938
26939 Ops.push_back(Op.getOperand(0));
26940 if (Op->getGluedNode())
26941 Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
26942
26943 SDLoc OpDL(Op);
26944 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
26945 SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
26946
26947 return NOOP;
26948}
26949
26950/// Provide custom lowering hooks for some operations.
26951SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
26952 switch (Op.getOpcode()) {
26953 default: llvm_unreachable("Should not custom lower this!")::llvm::llvm_unreachable_internal("Should not custom lower this!"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 26953)
;
26954 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
26955 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
26956 return LowerCMP_SWAP(Op, Subtarget, DAG);
26957 case ISD::CTPOP: return LowerCTPOP(Op, Subtarget, DAG);
26958 case ISD::ATOMIC_LOAD_ADD:
26959 case ISD::ATOMIC_LOAD_SUB:
26960 case ISD::ATOMIC_LOAD_OR:
26961 case ISD::ATOMIC_LOAD_XOR:
26962 case ISD::ATOMIC_LOAD_AND: return lowerAtomicArith(Op, DAG, Subtarget);
26963 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op, DAG, Subtarget);
26964 case ISD::BITREVERSE: return LowerBITREVERSE(Op, Subtarget, DAG);
26965 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
26966 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
26967 case ISD::VECTOR_SHUFFLE: return lowerVectorShuffle(Op, Subtarget, DAG);
26968 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
26969 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
26970 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
26971 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
26972 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
26973 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, Subtarget,DAG);
26974 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
26975 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
26976 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
26977 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
26978 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
26979 case ISD::SHL_PARTS:
26980 case ISD::SRA_PARTS:
26981 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
26982 case ISD::FSHL:
26983 case ISD::FSHR: return LowerFunnelShift(Op, Subtarget, DAG);
26984 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
26985 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
26986 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
26987 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
26988 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
26989 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
26990 case ISD::ZERO_EXTEND_VECTOR_INREG:
26991 case ISD::SIGN_EXTEND_VECTOR_INREG:
26992 return LowerEXTEND_VECTOR_INREG(Op, Subtarget, DAG);
26993 case ISD::FP_TO_SINT:
26994 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
26995 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
26996 case ISD::LOAD: return LowerLoad(Op, Subtarget, DAG);
26997 case ISD::STORE: return LowerStore(Op, Subtarget, DAG);
26998 case ISD::FADD:
26999 case ISD::FSUB: return lowerFaddFsub(Op, DAG, Subtarget);
27000 case ISD::FABS:
27001 case ISD::FNEG: return LowerFABSorFNEG(Op, DAG);
27002 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
27003 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
27004 case ISD::SETCC: return LowerSETCC(Op, DAG);
27005 case ISD::SETCCCARRY: return LowerSETCCCARRY(Op, DAG);
27006 case ISD::SELECT: return LowerSELECT(Op, DAG);
27007 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
27008 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
27009 case ISD::VASTART: return LowerVASTART(Op, DAG);
27010 case ISD::VAARG: return LowerVAARG(Op, DAG);
27011 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
27012 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
27013 case ISD::INTRINSIC_VOID:
27014 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
27015 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
27016 case ISD::ADDROFRETURNADDR: return LowerADDROFRETURNADDR(Op, DAG);
27017 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
27018 case ISD::FRAME_TO_ARGS_OFFSET:
27019 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
27020 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
27021 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
27022 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
27023 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
27024 case ISD::EH_SJLJ_SETUP_DISPATCH:
27025 return lowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
27026 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
27027 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
27028 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
27029 case ISD::CTLZ:
27030 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ(Op, Subtarget, DAG);
27031 case ISD::CTTZ:
27032 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op, Subtarget, DAG);
27033 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
27034 case ISD::MULHS:
27035 case ISD::MULHU: return LowerMULH(Op, Subtarget, DAG);
27036 case ISD::ROTL:
27037 case ISD::ROTR: return LowerRotate(Op, Subtarget, DAG);
27038 case ISD::SRA:
27039 case ISD::SRL:
27040 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
27041 case ISD::SADDO:
27042 case ISD::UADDO:
27043 case ISD::SSUBO:
27044 case ISD::USUBO:
27045 case ISD::SMULO:
27046 case ISD::UMULO: return LowerXALUO(Op, DAG);
27047 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
27048 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
27049 case ISD::ADDCARRY:
27050 case ISD::SUBCARRY: return LowerADDSUBCARRY(Op, DAG);
27051 case ISD::ADD:
27052 case ISD::SUB: return lowerAddSub(Op, DAG, Subtarget);
27053 case ISD::UADDSAT:
27054 case ISD::SADDSAT:
27055 case ISD::USUBSAT:
27056 case ISD::SSUBSAT: return LowerADDSAT_SUBSAT(Op, DAG, Subtarget);
27057 case ISD::SMAX:
27058 case ISD::SMIN:
27059 case ISD::UMAX:
27060 case ISD::UMIN: return LowerMINMAX(Op, DAG);
27061 case ISD::ABS: return LowerABS(Op, Subtarget, DAG);
27062 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
27063 case ISD::MLOAD: return LowerMLOAD(Op, Subtarget, DAG);
27064 case ISD::MSTORE: return LowerMSTORE(Op, Subtarget, DAG);
27065 case ISD::MGATHER: return LowerMGATHER(Op, Subtarget, DAG);
27066 case ISD::MSCATTER: return LowerMSCATTER(Op, Subtarget, DAG);
27067 case ISD::GC_TRANSITION_START:
27068 return LowerGC_TRANSITION_START(Op, DAG);
27069 case ISD::GC_TRANSITION_END: return LowerGC_TRANSITION_END(Op, DAG);
27070 }
27071}
27072
27073/// Places new result values for the node in Results (their number
27074/// and types must exactly match those of the original return values of
27075/// the node), or leaves Results empty, which indicates that the node is not
27076/// to be custom lowered after all.
27077void X86TargetLowering::LowerOperationWrapper(SDNode *N,
27078 SmallVectorImpl<SDValue> &Results,
27079 SelectionDAG &DAG) const {
27080 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
27081
27082 if (!Res.getNode())
27083 return;
27084
27085 // If the original node has one result, take the return value from
27086 // LowerOperation as is. It might not be result number 0.
27087 if (N->getNumValues() == 1) {
27088 Results.push_back(Res);
27089 return;
27090 }
27091
27092 // If the original node has multiple results, then the return node should
27093 // have the same number of results.
27094 assert((N->getNumValues() == Res->getNumValues()) &&(((N->getNumValues() == Res->getNumValues()) &&
"Lowering returned the wrong number of results!") ? static_cast
<void> (0) : __assert_fail ("(N->getNumValues() == Res->getNumValues()) && \"Lowering returned the wrong number of results!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 27095, __PRETTY_FUNCTION__))
27095 "Lowering returned the wrong number of results!")(((N->getNumValues() == Res->getNumValues()) &&
"Lowering returned the wrong number of results!") ? static_cast
<void> (0) : __assert_fail ("(N->getNumValues() == Res->getNumValues()) && \"Lowering returned the wrong number of results!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 27095, __PRETTY_FUNCTION__))
;
27096
27097 // Places new result values base on N result number.
27098 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
27099 Results.push_back(Res.getValue(I));
27100}
27101
27102/// Replace a node with an illegal result type with a new node built out of
27103/// custom code.
27104void X86TargetLowering::ReplaceNodeResults(SDNode *N,
27105 SmallVectorImpl<SDValue>&Results,
27106 SelectionDAG &DAG) const {
27107 SDLoc dl(N);
27108 switch (N->getOpcode()) {
27109 default:
27110 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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 27110)
;
27111 case ISD::CTPOP: {
27112 assert(N->getValueType(0) == MVT::i64 && "Unexpected VT!")((N->getValueType(0) == MVT::i64 && "Unexpected VT!"
) ? static_cast<void> (0) : __assert_fail ("N->getValueType(0) == MVT::i64 && \"Unexpected VT!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 27112, __PRETTY_FUNCTION__))
;
27113 // Use a v2i64 if possible.
27114 bool NoImplicitFloatOps =
27115 DAG.getMachineFunction().getFunction().hasFnAttribute(
27116 Attribute::NoImplicitFloat);
27117 if (isTypeLegal(MVT::v2i64) && !NoImplicitFloatOps) {
27118 SDValue Wide =
27119 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, N->getOperand(0));
27120 Wide = DAG.getNode(ISD::CTPOP, dl, MVT::v2i64, Wide);
27121 // Bit count should fit in 32-bits, extract it as that and then zero
27122 // extend to i64. Otherwise we end up extracting bits 63:32 separately.
27123 Wide = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Wide);
27124 Wide = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, Wide,
27125 DAG.getIntPtrConstant(0, dl));
27126 Wide = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Wide);
27127 Results.push_back(Wide);
27128 }
27129 return;
27130 }
27131 case ISD::MUL: {
27132 EVT VT = N->getValueType(0);
27133 assert(VT.isVector() && "Unexpected VT")((VT.isVector() && "Unexpected VT") ? static_cast<
void> (0) : __assert_fail ("VT.isVector() && \"Unexpected VT\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 27133, __PRETTY_FUNCTION__))
;
27134 if (getTypeAction(*DAG.getContext(), VT) == TypePromoteInteger &&
27135 VT.getVectorNumElements() == 2) {
27136 // Promote to a pattern that will be turned into PMULUDQ.
27137 SDValue N0 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::v2i64,
27138 N->getOperand(0));
27139 SDValue N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::v2i64,
27140 N->getOperand(1));
27141 SDValue Mul = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, N0, N1);
27142 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, VT, Mul));
27143 } else if (getTypeAction(*DAG.getContext(), VT) == TypeWidenVector &&
27144 VT.getVectorElementType() == MVT::i8) {
27145 // Pre-promote these to vXi16 to avoid op legalization thinking all 16
27146 // elements are needed.
27147 MVT MulVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
27148 SDValue Op0 = DAG.getNode(ISD::ANY_EXTEND, dl, MulVT, N->getOperand(0));
27149 SDValue Op1 = DAG.getNode(ISD::ANY_EXTEND, dl, MulVT, N->getOperand(1));
27150 SDValue Res = DAG.getNode(ISD::MUL, dl, MulVT, Op0, Op1);
27151 Res = DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
27152 unsigned NumConcats = 16 / VT.getVectorNumElements();
27153 SmallVector<SDValue, 8> ConcatOps(NumConcats, DAG.getUNDEF(VT));
27154 ConcatOps[0] = Res;
27155 Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v16i8, ConcatOps);
27156 Results.push_back(Res);
27157 }
27158 return;
27159 }
27160 case ISD::UADDSAT:
27161 case ISD::SADDSAT:
27162 case ISD::USUBSAT:
27163 case ISD::SSUBSAT:
27164 case X86ISD::VPMADDWD:
27165 case X86ISD::AVG: {
27166 // Legalize types for ISD::UADDSAT/SADDSAT/USUBSAT/SSUBSAT and
27167 // X86ISD::AVG/VPMADDWD by widening.
27168 assert(Subtarget.hasSSE2() && "Requires at least SSE2!")((Subtarget.hasSSE2() && "Requires at least SSE2!") ?
static_cast<void> (0) : __assert_fail ("Subtarget.hasSSE2() && \"Requires at least SSE2!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 27168, __PRETTY_FUNCTION__))
;
27169
27170 EVT VT = N->getValueType(0);
27171 EVT InVT = N->getOperand(0).getValueType();
27172 assert(VT.getSizeInBits() < 128 && 128 % VT.getSizeInBits() == 0 &&((VT.getSizeInBits() < 128 && 128 % VT.getSizeInBits
() == 0 && "Expected a VT that divides into 128 bits."
) ? static_cast<void> (0) : __assert_fail ("VT.getSizeInBits() < 128 && 128 % VT.getSizeInBits() == 0 && \"Expected a VT that divides into 128 bits.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 27173, __PRETTY_FUNCTION__))
27173 "Expected a VT that divides into 128 bits.")((VT.getSizeInBits() < 128 && 128 % VT.getSizeInBits
() == 0 && "Expected a VT that divides into 128 bits."
) ? static_cast<void> (0) : __assert_fail ("VT.getSizeInBits() < 128 && 128 % VT.getSizeInBits() == 0 && \"Expected a VT that divides into 128 bits.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 27173, __PRETTY_FUNCTION__))
;
27174 unsigned NumConcat = 128 / InVT.getSizeInBits();
27175
27176 EVT InWideVT = EVT::getVectorVT(*DAG.getContext(),
27177 InVT.getVectorElementType(),
27178 NumConcat * InVT.getVectorNumElements());
27179 EVT WideVT = EVT::getVectorVT(*DAG.getContext(),
27180 VT.getVectorElementType(),
27181 NumConcat * VT.getVectorNumElements());
27182
27183 SmallVector<SDValue, 16> Ops(NumConcat, DAG.getUNDEF(InVT));
27184 Ops[0] = N->getOperand(0);
27185 SDValue InVec0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, InWideVT, Ops);
27186 Ops[0] = N->getOperand(1);
27187 SDValue InVec1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, InWideVT, Ops);
27188
27189 SDValue Res = DAG.getNode(N->getOpcode(), dl, WideVT, InVec0, InVec1);
27190 if (getTypeAction(*DAG.getContext(), VT) != TypeWidenVector)
27191 Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Res,
27192 DAG.getIntPtrConstant(0, dl));
27193 Results.push_back(Res);
27194 return;
27195 }
27196 case ISD::ABS: {
27197 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
27198 assert(N->getValueType(0) == MVT::i64 &&((N->getValueType(0) == MVT::i64 && "Unexpected type (!= i64) on ABS."
) ? static_cast<void> (0) : __assert_fail ("N->getValueType(0) == MVT::i64 && \"Unexpected type (!= i64) on ABS.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 27199, __PRETTY_FUNCTION__))
27199 "Unexpected type (!= i64) on ABS.")((N->getValueType(0) == MVT::i64 && "Unexpected type (!= i64) on ABS."
) ? static_cast<void> (0) : __assert_fail ("N->getValueType(0) == MVT::i64 && \"Unexpected type (!= i64) on ABS.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 27199, __PRETTY_FUNCTION__))
;
27200 MVT HalfT = MVT::i32;
27201 SDValue Lo, Hi, Tmp;
27202 SDVTList VTList = DAG.getVTList(HalfT, MVT::i1);
27203
27204 Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0),
27205 DAG.getConstant(0, dl, HalfT));
27206 Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0),
27207 DAG.getConstant(1, dl, HalfT));
27208 Tmp = DAG.getNode(
27209 ISD::SRA, dl, HalfT, Hi,
27210 DAG.getConstant(HalfT.getSizeInBits() - 1, dl,
27211 TLI.getShiftAmountTy(HalfT, DAG.getDataLayout())));
27212 Lo = DAG.getNode(ISD::UADDO, dl, VTList, Tmp, Lo);
27213 Hi = DAG.getNode(ISD::ADDCARRY, dl, VTList, Tmp, Hi,
27214 SDValue(Lo.getNode(), 1));
27215 Hi = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Hi);
27216 Lo = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Lo);
27217 Results.push_back(Lo);
27218 Results.push_back(Hi);
27219 return;
27220 }
27221 case ISD::SETCC: {
27222 // Widen v2i32 (setcc v2f32). This is really needed for AVX512VL when
27223 // setCC result type is v2i1 because type legalzation will end up with
27224 // a v4i1 setcc plus an extend.
27225 assert(N->getValueType(0) == MVT::v2i32 && "Unexpected type")((N->getValueType(0) == MVT::v2i32 && "Unexpected type"
) ? static_cast<void> (0) : __assert_fail ("N->getValueType(0) == MVT::v2i32 && \"Unexpected type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 27225, __PRETTY_FUNCTION__))
;
27226 if (N->getOperand(0).getValueType() != MVT::v2f32 ||
27227 getTypeAction(*DAG.getContext(), MVT::v2i32) == TypeWidenVector)
27228 return;
27229 SDValue UNDEF = DAG.getUNDEF(MVT::v2f32);
27230 SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
27231 N->getOperand(0), UNDEF);
27232 SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
27233 N->getOperand(1), UNDEF);
27234 SDValue Res = DAG.getNode(ISD::SETCC, dl, MVT::v4i32, LHS, RHS,
27235 N->getOperand(2));
27236 Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i32, Res,
27237 DAG.getIntPtrConstant(0, dl));
27238 Results.push_back(Res);
27239 return;
27240 }
27241 // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
27242 case X86ISD::FMINC:
27243 case X86ISD::FMIN:
27244 case X86ISD::FMAXC:
27245 case X86ISD::FMAX: {
27246 EVT VT = N->getValueType(0);
27247 assert(VT == MVT::v2f32 && "Unexpected type (!= v2f32) on FMIN/FMAX.")((VT == MVT::v2f32 && "Unexpected type (!= v2f32) on FMIN/FMAX."
) ? static_cast<void> (0) : __assert_fail ("VT == MVT::v2f32 && \"Unexpected type (!= v2f32) on FMIN/FMAX.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 27247, __PRETTY_FUNCTION__))
;
27248 SDValue UNDEF = DAG.getUNDEF(VT);
27249 SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
27250 N->getOperand(0), UNDEF);
27251 SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
27252 N->getOperand(1), UNDEF);
27253 Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
27254 return;
27255 }
27256 case ISD::SDIV:
27257 case ISD::UDIV:
27258 case ISD::SREM:
27259 case ISD::UREM: {
27260 EVT VT = N->getValueType(0);
27261 if (getTypeAction(*DAG.getContext(), VT) == TypeWidenVector) {
27262 // If this RHS is a constant splat vector we can widen this and let
27263 // division/remainder by constant optimize it.
27264 // TODO: Can we do something for non-splat?
27265 APInt SplatVal;
27266 if (ISD::isConstantSplatVector(N->getOperand(1).getNode(), SplatVal)) {
27267 unsigned NumConcats = 128 / VT.getSizeInBits();
27268 SmallVector<SDValue, 8> Ops0(NumConcats, DAG.getUNDEF(VT));
27269 Ops0[0] = N->getOperand(0);
27270 EVT ResVT = getTypeToTransformTo(*DAG.getContext(), VT);
27271 SDValue N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Ops0);
27272 SDValue N1 = DAG.getConstant(SplatVal, dl, ResVT);
27273 SDValue Res = DAG.getNode(N->getOpcode(), dl, ResVT, N0, N1);
27274 Results.push_back(Res);
27275 }
27276 return;
27277 }
27278
27279 if (VT == MVT::v2i32) {
27280 // Legalize v2i32 div/rem by unrolling. Otherwise we promote to the
27281 // v2i64 and unroll later. But then we create i64 scalar ops which
27282 // might be slow in 64-bit mode or require a libcall in 32-bit mode.
27283 Results.push_back(DAG.UnrollVectorOp(N));
27284 return;
27285 }
27286
27287 if (VT.isVector())
27288 return;
27289
27290 LLVM_FALLTHROUGH[[clang::fallthrough]];
27291 }
27292 case ISD::SDIVREM:
27293 case ISD::UDIVREM: {
27294 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
27295 Results.push_back(V);
27296 return;
27297 }
27298 case ISD::TRUNCATE: {
27299 MVT VT = N->getSimpleValueType(0);
27300 if (getTypeAction(*DAG.getContext(), VT) != TypeWidenVector)
27301 return;
27302
27303 // The generic legalizer will try to widen the input type to the same
27304 // number of elements as the widened result type. But this isn't always
27305 // the best thing so do some custom legalization to avoid some cases.
27306 MVT WidenVT = getTypeToTransformTo(*DAG.getContext(), VT).getSimpleVT();
27307 SDValue In = N->getOperand(0);
27308 EVT InVT = In.getValueType();
27309
27310 unsigned InBits = InVT.getSizeInBits();
27311 if (128 % InBits == 0) {
27312 // 128 bit and smaller inputs should avoid truncate all together and
27313 // just use a build_vector that will become a shuffle.
27314 // TODO: Widen and use a shuffle directly?
27315 MVT InEltVT = InVT.getSimpleVT().getVectorElementType();
27316 EVT EltVT = VT.getVectorElementType();
27317 unsigned WidenNumElts = WidenVT.getVectorNumElements();
27318 SmallVector<SDValue, 16> Ops(WidenNumElts, DAG.getUNDEF(EltVT));
27319 // Use the original element count so we don't do more scalar opts than
27320 // necessary.
27321 unsigned MinElts = VT.getVectorNumElements();
27322 for (unsigned i=0; i < MinElts; ++i) {
27323 SDValue Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, InEltVT, In,
27324 DAG.getIntPtrConstant(i, dl));
27325 Ops[i] = DAG.getNode(ISD::TRUNCATE, dl, EltVT, Val);
27326 }
27327 Results.push_back(DAG.getBuildVector(WidenVT, dl, Ops));
27328 return;
27329 }
27330 // With AVX512 there are some cases that can use a target specific
27331 // truncate node to go from 256/512 to less than 128 with zeros in the
27332 // upper elements of the 128 bit result.
27333 if (Subtarget.hasAVX512() && isTypeLegal(InVT)) {
27334 // We can use VTRUNC directly if for 256 bits with VLX or for any 512.
27335 if ((InBits == 256 && Subtarget.hasVLX()) || InBits == 512) {
27336 Results.push_back(DAG.getNode(X86ISD::VTRUNC, dl, WidenVT, In));
27337 return;
27338 }
27339 // There's one case we can widen to 512 bits and use VTRUNC.
27340 if (InVT == MVT::v4i64 && VT == MVT::v4i8 && isTypeLegal(MVT::v8i64)) {
27341 In = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i64, In,
27342 DAG.getUNDEF(MVT::v4i64));
27343 Results.push_back(DAG.getNode(X86ISD::VTRUNC, dl, WidenVT, In));
27344 return;
27345 }
27346 }
27347 return;
27348 }
27349 case ISD::SIGN_EXTEND_VECTOR_INREG: {
27350 if (ExperimentalVectorWideningLegalization)
27351 return;
27352
27353 EVT VT = N->getValueType(0);
27354 SDValue In = N->getOperand(0);
27355 EVT InVT = In.getValueType();
27356 if (!Subtarget.hasSSE41() && VT == MVT::v4i64 &&
27357 (InVT == MVT::v16i16 || InVT == MVT::v32i8)) {
27358 // Custom split this so we can extend i8/i16->i32 invec. This is better
27359 // since sign_extend_inreg i8/i16->i64 requires an extend to i32 using
27360 // sra. Then extending from i32 to i64 using pcmpgt. By custom splitting
27361 // we allow the sra from the extend to i32 to be shared by the split.
27362 EVT ExtractVT = EVT::getVectorVT(*DAG.getContext(),
27363 InVT.getVectorElementType(),
27364 InVT.getVectorNumElements() / 2);
27365 MVT ExtendVT = MVT::getVectorVT(MVT::i32,
27366 VT.getVectorNumElements());
27367 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ExtractVT,
27368 In, DAG.getIntPtrConstant(0, dl));
27369 In = DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, dl, MVT::v4i32, In);
27370
27371 // Fill a vector with sign bits for each element.
27372 SDValue Zero = DAG.getConstant(0, dl, ExtendVT);
27373 SDValue SignBits = DAG.getSetCC(dl, ExtendVT, Zero, In, ISD::SETGT);
27374
27375 EVT LoVT, HiVT;
27376 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
27377
27378 // Create an unpackl and unpackh to interleave the sign bits then bitcast
27379 // to vXi64.
27380 SDValue Lo = getUnpackl(DAG, dl, ExtendVT, In, SignBits);
27381 Lo = DAG.getNode(ISD::BITCAST, dl, LoVT, Lo);
27382 SDValue Hi = getUnpackh(DAG, dl, ExtendVT, In, SignBits);
27383 Hi = DAG.getNode(ISD::BITCAST, dl, HiVT, Hi);
27384
27385 SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
27386 Results.push_back(Res);
27387 return;
27388 }
27389 return;
27390 }
27391 case ISD::SIGN_EXTEND:
27392 case ISD::ZERO_EXTEND: {
27393 EVT VT = N->getValueType(0);
27394 SDValue In = N->getOperand(0);
27395 EVT InVT = In.getValueType();
27396 if (!Subtarget.hasSSE41() && VT == MVT::v4i64 &&
27397 (InVT == MVT::v4i16 || InVT == MVT::v4i8) &&
27398 getTypeAction(*DAG.getContext(), InVT) == TypeWidenVector) {
27399 assert(N->getOpcode() == ISD::SIGN_EXTEND && "Unexpected opcode")((N->getOpcode() == ISD::SIGN_EXTEND && "Unexpected opcode"
) ? static_cast<void> (0) : __assert_fail ("N->getOpcode() == ISD::SIGN_EXTEND && \"Unexpected opcode\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 27399, __PRETTY_FUNCTION__))
;
27400 // Custom split this so we can extend i8/i16->i32 invec. This is better
27401 // since sign_extend_inreg i8/i16->i64 requires an extend to i32 using
27402 // sra. Then extending from i32 to i64 using pcmpgt. By custom splitting
27403 // we allow the sra from the extend to i32 to be shared by the split.
27404 In = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, In);
27405
27406 // Fill a vector with sign bits for each element.
27407 SDValue Zero = DAG.getConstant(0, dl, MVT::v4i32);
27408 SDValue SignBits = DAG.getSetCC(dl, MVT::v4i32, Zero, In, ISD::SETGT);
27409
27410 // Create an unpackl and unpackh to interleave the sign bits then bitcast
27411 // to v2i64.
27412 SDValue Lo = DAG.getVectorShuffle(MVT::v4i32, dl, In, SignBits,
27413 {0, 4, 1, 5});
27414 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Lo);
27415 SDValue Hi = DAG.getVectorShuffle(MVT::v4i32, dl, In, SignBits,
27416 {2, 6, 3, 7});
27417 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Hi);
27418
27419 SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
27420 Results.push_back(Res);
27421 return;
27422 }
27423
27424 if (VT == MVT::v16i32 || VT == MVT::v8i64) {
27425 if (!InVT.is128BitVector()) {
27426 // Not a 128 bit vector, but maybe type legalization will promote
27427 // it to 128 bits.
27428 if (getTypeAction(*DAG.getContext(), InVT) != TypePromoteInteger)
27429 return;
27430 InVT = getTypeToTransformTo(*DAG.getContext(), InVT);
27431 if (!InVT.is128BitVector())
27432 return;
27433
27434 // Promote the input to 128 bits. Type legalization will turn this into
27435 // zext_inreg/sext_inreg.
27436 In = DAG.getNode(N->getOpcode(), dl, InVT, In);
27437 }
27438
27439 // Perform custom splitting instead of the two stage extend we would get
27440 // by default.
27441 EVT LoVT, HiVT;
27442 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
27443 assert(isTypeLegal(LoVT) && "Split VT not legal?")((isTypeLegal(LoVT) && "Split VT not legal?") ? static_cast
<void> (0) : __assert_fail ("isTypeLegal(LoVT) && \"Split VT not legal?\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 27443, __PRETTY_FUNCTION__))
;
27444
27445 bool IsSigned = N->getOpcode() == ISD::SIGN_EXTEND;
27446
27447 SDValue Lo = getExtendInVec(IsSigned, dl, LoVT, In, DAG);
27448
27449 // We need to shift the input over by half the number of elements.
27450 unsigned NumElts = InVT.getVectorNumElements();
27451 unsigned HalfNumElts = NumElts / 2;
27452 SmallVector<int, 16> ShufMask(NumElts, SM_SentinelUndef);
27453 for (unsigned i = 0; i != HalfNumElts; ++i)
27454 ShufMask[i] = i + HalfNumElts;
27455
27456 SDValue Hi = DAG.getVectorShuffle(InVT, dl, In, In, ShufMask);
27457 Hi = getExtendInVec(IsSigned, dl, HiVT, Hi, DAG);
27458
27459 SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
27460 Results.push_back(Res);
27461 }
27462 return;
27463 }
27464 case ISD::FP_TO_SINT:
27465 case ISD::FP_TO_UINT: {
27466 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
27467 EVT VT = N->getValueType(0);
27468 SDValue Src = N->getOperand(0);
27469 EVT SrcVT = Src.getValueType();
27470
27471 // Promote these manually to avoid over promotion to v2i64. Type
27472 // legalization will revisit the v2i32 operation for more cleanup.
27473 if ((VT == MVT::v2i8 || VT == MVT::v2i16) &&
27474 getTypeAction(*DAG.getContext(), VT) == TypePromoteInteger) {
27475 // AVX512DQ provides instructions that produce a v2i64 result.
27476 if (Subtarget.hasDQI())
27477 return;
27478
27479 SDValue Res = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v2i32, Src);
27480 Res = DAG.getNode(N->getOpcode() == ISD::FP_TO_UINT ? ISD::AssertZext
27481 : ISD::AssertSext,
27482 dl, MVT::v2i32, Res,
27483 DAG.getValueType(VT.getVectorElementType()));
27484 Res = DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
27485 Results.push_back(Res);
27486 return;
27487 }
27488
27489 if (VT.isVector() && VT.getScalarSizeInBits() < 32) {
27490 if (getTypeAction(*DAG.getContext(), VT) != TypeWidenVector)
27491 return;
27492
27493 // Try to create a 128 bit vector, but don't exceed a 32 bit element.
27494 unsigned NewEltWidth = std::min(128 / VT.getVectorNumElements(), 32U);
27495 MVT PromoteVT = MVT::getVectorVT(MVT::getIntegerVT(NewEltWidth),
27496 VT.getVectorNumElements());
27497 SDValue Res = DAG.getNode(ISD::FP_TO_SINT, dl, PromoteVT, Src);
27498
27499 // Preserve what we know about the size of the original result. Except
27500 // when the result is v2i32 since we can't widen the assert.
27501 if (PromoteVT != MVT::v2i32)
27502 Res = DAG.getNode(N->getOpcode() == ISD::FP_TO_UINT ? ISD::AssertZext
27503 : ISD::AssertSext,
27504 dl, PromoteVT, Res,
27505 DAG.getValueType(VT.getVectorElementType()));
27506
27507 // Truncate back to the original width.
27508 Res = DAG.getNode(ISD::TRUNCATE, dl, VT, Res);
27509
27510 // Now widen to 128 bits.
27511 unsigned NumConcats = 128 / VT.getSizeInBits();
27512 MVT ConcatVT = MVT::getVectorVT(VT.getSimpleVT().getVectorElementType(),
27513 VT.getVectorNumElements() * NumConcats);
27514 SmallVector<SDValue, 8> ConcatOps(NumConcats, DAG.getUNDEF(VT));
27515 ConcatOps[0] = Res;
27516 Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatVT, ConcatOps);
27517 Results.push_back(Res);
27518 return;
27519 }
27520
27521
27522 if (VT == MVT::v2i32) {
27523 assert((IsSigned || Subtarget.hasAVX512()) &&(((IsSigned || Subtarget.hasAVX512()) && "Can only handle signed conversion without AVX512"
) ? static_cast<void> (0) : __assert_fail ("(IsSigned || Subtarget.hasAVX512()) && \"Can only handle signed conversion without AVX512\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 27524, __PRETTY_FUNCTION__))
27524 "Can only handle signed conversion without AVX512")(((IsSigned || Subtarget.hasAVX512()) && "Can only handle signed conversion without AVX512"
) ? static_cast<void> (0) : __assert_fail ("(IsSigned || Subtarget.hasAVX512()) && \"Can only handle signed conversion without AVX512\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 27524, __PRETTY_FUNCTION__))
;
27525 assert(Subtarget.hasSSE2() && "Requires at least SSE2!")((Subtarget.hasSSE2() && "Requires at least SSE2!") ?
static_cast<void> (0) : __assert_fail ("Subtarget.hasSSE2() && \"Requires at least SSE2!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 27525, __PRETTY_FUNCTION__))
;
27526 bool Widenv2i32 =
27527 getTypeAction(*DAG.getContext(), MVT::v2i32) == TypeWidenVector;
27528 if (Src.getValueType() == MVT::v2f64) {
27529 unsigned Opc = IsSigned ? X86ISD::CVTTP2SI : X86ISD::CVTTP2UI;
27530 if (!IsSigned && !Subtarget.hasVLX()) {
27531 // If v2i32 is widened, we can defer to the generic legalizer.
27532 if (Widenv2i32)
27533 return;
27534 // Custom widen by doubling to a legal vector with. Isel will
27535 // further widen to v8f64.
27536 Opc = ISD::FP_TO_UINT;
27537 Src = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f64,
27538 Src, DAG.getUNDEF(MVT::v2f64));
27539 }
27540 SDValue Res = DAG.getNode(Opc, dl, MVT::v4i32, Src);
27541 if (!Widenv2i32)
27542 Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i32, Res,
27543 DAG.getIntPtrConstant(0, dl));
27544 Results.push_back(Res);
27545 return;
27546 }
27547 if (SrcVT == MVT::v2f32 &&
27548 getTypeAction(*DAG.getContext(), VT) != TypeWidenVector) {
27549 SDValue Idx = DAG.getIntPtrConstant(0, dl);
27550 SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32, Src,
27551 DAG.getUNDEF(MVT::v2f32));
27552 Res = DAG.getNode(IsSigned ? ISD::FP_TO_SINT
27553 : ISD::FP_TO_UINT, dl, MVT::v4i32, Res);
27554 Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i32, Res, Idx);
27555 Results.push_back(Res);
27556 return;
27557 }
27558
27559 // The FP_TO_INTHelper below only handles f32/f64/f80 scalar inputs,
27560 // so early out here.
27561 return;
27562 }
27563
27564 if (Subtarget.hasDQI() && VT == MVT::i64 &&
27565 (SrcVT == MVT::f32 || SrcVT == MVT::f64)) {
27566 assert(!Subtarget.is64Bit() && "i64 should be legal")((!Subtarget.is64Bit() && "i64 should be legal") ? static_cast
<void> (0) : __assert_fail ("!Subtarget.is64Bit() && \"i64 should be legal\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 27566, __PRETTY_FUNCTION__))
;
27567 unsigned NumElts = Subtarget.hasVLX() ? 4 : 8;
27568 // Using a 256-bit input here to guarantee 128-bit input for f32 case.
27569 // TODO: Use 128-bit vectors for f64 case?
27570 // TODO: Use 128-bit vectors for f32 by using CVTTP2SI/CVTTP2UI.
27571 MVT VecVT = MVT::getVectorVT(MVT::i64, NumElts);
27572 MVT VecInVT = MVT::getVectorVT(SrcVT.getSimpleVT(), NumElts);
27573
27574 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
27575 SDValue Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecInVT,
27576 DAG.getConstantFP(0.0, dl, VecInVT), Src,
27577 ZeroIdx);
27578 Res = DAG.getNode(N->getOpcode(), SDLoc(N), VecVT, Res);
27579 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Res, ZeroIdx);
27580 Results.push_back(Res);
27581 return;
27582 }
27583
27584 if (SDValue V = FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned))
27585 Results.push_back(V);
27586 return;
27587 }
27588 case ISD::SINT_TO_FP: {
27589 assert(Subtarget.hasDQI() && Subtarget.hasVLX() && "Requires AVX512DQVL!")((Subtarget.hasDQI() && Subtarget.hasVLX() &&
"Requires AVX512DQVL!") ? static_cast<void> (0) : __assert_fail
("Subtarget.hasDQI() && Subtarget.hasVLX() && \"Requires AVX512DQVL!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 27589, __PRETTY_FUNCTION__))
;
27590 SDValue Src = N->getOperand(0);
27591 if (N->getValueType(0) != MVT::v2f32 || Src.getValueType() != MVT::v2i64)
27592 return;
27593 Results.push_back(DAG.getNode(X86ISD::CVTSI2P, dl, MVT::v4f32, Src));
27594 return;
27595 }
27596 case ISD::UINT_TO_FP: {
27597 assert(Subtarget.hasSSE2() && "Requires at least SSE2!")((Subtarget.hasSSE2() && "Requires at least SSE2!") ?
static_cast<void> (0) : __assert_fail ("Subtarget.hasSSE2() && \"Requires at least SSE2!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 27597, __PRETTY_FUNCTION__))
;
27598 EVT VT = N->getValueType(0);
27599 if (VT != MVT::v2f32)
27600 return;
27601 SDValue Src = N->getOperand(0);
27602 EVT SrcVT = Src.getValueType();
27603 if (Subtarget.hasDQI() && Subtarget.hasVLX() && SrcVT == MVT::v2i64) {
27604 Results.push_back(DAG.getNode(X86ISD::CVTUI2P, dl, MVT::v4f32, Src));
27605 return;
27606 }
27607 if (SrcVT != MVT::v2i32)
27608 return;
27609 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64, Src);
27610 SDValue VBias =
27611 DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl, MVT::v2f64);
27612 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
27613 DAG.getBitcast(MVT::v2i64, VBias));
27614 Or = DAG.getBitcast(MVT::v2f64, Or);
27615 // TODO: Are there any fast-math-flags to propagate here?
27616 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
27617 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
27618 return;
27619 }
27620 case ISD::FP_ROUND: {
27621 if (!isTypeLegal(N->getOperand(0).getValueType()))
27622 return;
27623 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
27624 Results.push_back(V);
27625 return;
27626 }
27627 case ISD::FP_EXTEND: {
27628 // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
27629 // No other ValueType for FP_EXTEND should reach this point.
27630 assert(N->getValueType(0) == MVT::v2f32 &&((N->getValueType(0) == MVT::v2f32 && "Do not know how to legalize this Node"
) ? static_cast<void> (0) : __assert_fail ("N->getValueType(0) == MVT::v2f32 && \"Do not know how to legalize this Node\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 27631, __PRETTY_FUNCTION__))
27631 "Do not know how to legalize this Node")((N->getValueType(0) == MVT::v2f32 && "Do not know how to legalize this Node"
) ? static_cast<void> (0) : __assert_fail ("N->getValueType(0) == MVT::v2f32 && \"Do not know how to legalize this Node\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 27631, __PRETTY_FUNCTION__))
;
27632 return;
27633 }
27634 case ISD::INTRINSIC_W_CHAIN: {
27635 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
27636 switch (IntNo) {
27637 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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 27638)
27638 "legalize this intrinsic operation!")::llvm::llvm_unreachable_internal("Do not know how to custom type "
"legalize this intrinsic operation!", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 27638)
;
27639 case Intrinsic::x86_rdtsc:
27640 return getReadTimeStampCounter(N, dl, X86::RDTSC, DAG, Subtarget,
27641 Results);
27642 case Intrinsic::x86_rdtscp:
27643 return getReadTimeStampCounter(N, dl, X86::RDTSCP, DAG, Subtarget,
27644 Results);
27645 case Intrinsic::x86_rdpmc:
27646 expandIntrinsicWChainHelper(N, dl, DAG, X86::RDPMC, X86::ECX, Subtarget,
27647 Results);
27648 return;
27649 case Intrinsic::x86_xgetbv:
27650 expandIntrinsicWChainHelper(N, dl, DAG, X86::XGETBV, X86::ECX, Subtarget,
27651 Results);
27652 return;
27653 }
27654 }
27655 case ISD::READCYCLECOUNTER: {
27656 return getReadTimeStampCounter(N, dl, X86::RDTSC, DAG, Subtarget, Results);
27657 }
27658 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
27659 EVT T = N->getValueType(0);
27660 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair")(((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair"
) ? static_cast<void> (0) : __assert_fail ("(T == MVT::i64 || T == MVT::i128) && \"can only expand cmpxchg pair\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 27660, __PRETTY_FUNCTION__))
;
27661 bool Regs64bit = T == MVT::i128;
27662 assert((!Regs64bit || Subtarget.hasCmpxchg16b()) &&(((!Regs64bit || Subtarget.hasCmpxchg16b()) && "64-bit ATOMIC_CMP_SWAP_WITH_SUCCESS requires CMPXCHG16B"
) ? static_cast<void> (0) : __assert_fail ("(!Regs64bit || Subtarget.hasCmpxchg16b()) && \"64-bit ATOMIC_CMP_SWAP_WITH_SUCCESS requires CMPXCHG16B\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 27663, __PRETTY_FUNCTION__))
27663 "64-bit ATOMIC_CMP_SWAP_WITH_SUCCESS requires CMPXCHG16B")(((!Regs64bit || Subtarget.hasCmpxchg16b()) && "64-bit ATOMIC_CMP_SWAP_WITH_SUCCESS requires CMPXCHG16B"
) ? static_cast<void> (0) : __assert_fail ("(!Regs64bit || Subtarget.hasCmpxchg16b()) && \"64-bit ATOMIC_CMP_SWAP_WITH_SUCCESS requires CMPXCHG16B\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 27663, __PRETTY_FUNCTION__))
;
27664 MVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
27665 SDValue cpInL, cpInH;
27666 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
27667 DAG.getConstant(0, dl, HalfT));
27668 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
27669 DAG.getConstant(1, dl, HalfT));
27670 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
27671 Regs64bit ? X86::RAX : X86::EAX,
27672 cpInL, SDValue());
27673 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
27674 Regs64bit ? X86::RDX : X86::EDX,
27675 cpInH, cpInL.getValue(1));
27676 SDValue swapInL, swapInH;
27677 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
27678 DAG.getConstant(0, dl, HalfT));
27679 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
27680 DAG.getConstant(1, dl, HalfT));
27681 swapInH =
27682 DAG.getCopyToReg(cpInH.getValue(0), dl, Regs64bit ? X86::RCX : X86::ECX,
27683 swapInH, cpInH.getValue(1));
27684 // If the current function needs the base pointer, RBX,
27685 // we shouldn't use cmpxchg directly.
27686 // Indeed the lowering of that instruction will clobber
27687 // that register and since RBX will be a reserved register
27688 // the register allocator will not make sure its value will
27689 // be properly saved and restored around this live-range.
27690 const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
27691 SDValue Result;
27692 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
27693 unsigned BasePtr = TRI->getBaseRegister();
27694 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
27695 if (TRI->hasBasePointer(DAG.getMachineFunction()) &&
27696 (BasePtr == X86::RBX || BasePtr == X86::EBX)) {
27697 // ISel prefers the LCMPXCHG64 variant.
27698 // If that assert breaks, that means it is not the case anymore,
27699 // and we need to teach LCMPXCHG8_SAVE_EBX_DAG how to save RBX,
27700 // not just EBX. This is a matter of accepting i64 input for that
27701 // pseudo, and restoring into the register of the right wide
27702 // in expand pseudo. Everything else should just work.
27703 assert(((Regs64bit == (BasePtr == X86::RBX)) || BasePtr == X86::EBX) &&((((Regs64bit == (BasePtr == X86::RBX)) || BasePtr == X86::EBX
) && "Saving only half of the RBX") ? static_cast<
void> (0) : __assert_fail ("((Regs64bit == (BasePtr == X86::RBX)) || BasePtr == X86::EBX) && \"Saving only half of the RBX\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 27704, __PRETTY_FUNCTION__))
27704 "Saving only half of the RBX")((((Regs64bit == (BasePtr == X86::RBX)) || BasePtr == X86::EBX
) && "Saving only half of the RBX") ? static_cast<
void> (0) : __assert_fail ("((Regs64bit == (BasePtr == X86::RBX)) || BasePtr == X86::EBX) && \"Saving only half of the RBX\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 27704, __PRETTY_FUNCTION__))
;
27705 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_SAVE_RBX_DAG
27706 : X86ISD::LCMPXCHG8_SAVE_EBX_DAG;
27707 SDValue RBXSave = DAG.getCopyFromReg(swapInH.getValue(0), dl,
27708 Regs64bit ? X86::RBX : X86::EBX,
27709 HalfT, swapInH.getValue(1));
27710 SDValue Ops[] = {/*Chain*/ RBXSave.getValue(1), N->getOperand(1), swapInL,
27711 RBXSave,
27712 /*Glue*/ RBXSave.getValue(2)};
27713 Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
27714 } else {
27715 unsigned Opcode =
27716 Regs64bit ? X86ISD::LCMPXCHG16_DAG : X86ISD::LCMPXCHG8_DAG;
27717 swapInL = DAG.getCopyToReg(swapInH.getValue(0), dl,
27718 Regs64bit ? X86::RBX : X86::EBX, swapInL,
27719 swapInH.getValue(1));
27720 SDValue Ops[] = {swapInL.getValue(0), N->getOperand(1),
27721 swapInL.getValue(1)};
27722 Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
27723 }
27724 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
27725 Regs64bit ? X86::RAX : X86::EAX,
27726 HalfT, Result.getValue(1));
27727 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
27728 Regs64bit ? X86::RDX : X86::EDX,
27729 HalfT, cpOutL.getValue(2));
27730 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
27731
27732 SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
27733 MVT::i32, cpOutH.getValue(2));
27734 SDValue Success = getSETCC(X86::COND_E, EFLAGS, dl, DAG);
27735 Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
27736
27737 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
27738 Results.push_back(Success);
27739 Results.push_back(EFLAGS.getValue(1));
27740 return;
27741 }
27742 case ISD::ATOMIC_LOAD: {
27743 assert(N->getValueType(0) == MVT::i64 && "Unexpected VT!")((N->getValueType(0) == MVT::i64 && "Unexpected VT!"
) ? static_cast<void> (0) : __assert_fail ("N->getValueType(0) == MVT::i64 && \"Unexpected VT!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 27743, __PRETTY_FUNCTION__))
;
27744 bool NoImplicitFloatOps =
27745 DAG.getMachineFunction().getFunction().hasFnAttribute(
27746 Attribute::NoImplicitFloat);
27747 if (!Subtarget.useSoftFloat() && !NoImplicitFloatOps) {
27748 auto *Node = cast<AtomicSDNode>(N);
27749 if (Subtarget.hasSSE2()) {
27750 // Use a VZEXT_LOAD which will be selected as MOVQ. Then extract the
27751 // lower 64-bits.
27752 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
27753 SDValue Ops[] = { Node->getChain(), Node->getBasePtr() };
27754 SDValue Ld = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
27755 MVT::i64, Node->getMemOperand());
27756 SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Ld,
27757 DAG.getIntPtrConstant(0, dl));
27758 Results.push_back(Res);
27759 Results.push_back(Ld.getValue(1));
27760 return;
27761 }
27762 if (Subtarget.hasX87()) {
27763 // First load this into an 80-bit X87 register. This will put the whole
27764 // integer into the significand.
27765 // FIXME: Do we need to glue? See FIXME comment in BuildFILD.
27766 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other, MVT::Glue);
27767 SDValue Ops[] = { Node->getChain(), Node->getBasePtr() };
27768 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::FILD_FLAG,
27769 dl, Tys, Ops, MVT::i64,
27770 Node->getMemOperand());
27771 SDValue Chain = Result.getValue(1);
27772 SDValue InFlag = Result.getValue(2);
27773
27774 // Now store the X87 register to a stack temporary and convert to i64.
27775 // This store is not atomic and doesn't need to be.
27776 // FIXME: We don't need a stack temporary if the result of the load
27777 // is already being stored. We could just directly store there.
27778 SDValue StackPtr = DAG.CreateStackTemporary(MVT::i64);
27779 int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
27780 MachinePointerInfo MPI =
27781 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
27782 SDValue StoreOps[] = { Chain, Result, StackPtr, InFlag };
27783 Chain = DAG.getMemIntrinsicNode(X86ISD::FIST, dl,
27784 DAG.getVTList(MVT::Other), StoreOps,
27785 MVT::i64, MPI, 0 /*Align*/,
27786 MachineMemOperand::MOStore);
27787
27788 // Finally load the value back from the stack temporary and return it.
27789 // This load is not atomic and doesn't need to be.
27790 // This load will be further type legalized.
27791 Result = DAG.getLoad(MVT::i64, dl, Chain, StackPtr, MPI);
27792 Results.push_back(Result);
27793 Results.push_back(Result.getValue(1));
27794 return;
27795 }
27796 }
27797 // TODO: Use MOVLPS when SSE1 is available?
27798 // Delegate to generic TypeLegalization. Situations we can really handle
27799 // should have already been dealt with by AtomicExpandPass.cpp.
27800 break;
27801 }
27802 case ISD::ATOMIC_SWAP:
27803 case ISD::ATOMIC_LOAD_ADD:
27804 case ISD::ATOMIC_LOAD_SUB:
27805 case ISD::ATOMIC_LOAD_AND:
27806 case ISD::ATOMIC_LOAD_OR:
27807 case ISD::ATOMIC_LOAD_XOR:
27808 case ISD::ATOMIC_LOAD_NAND:
27809 case ISD::ATOMIC_LOAD_MIN:
27810 case ISD::ATOMIC_LOAD_MAX:
27811 case ISD::ATOMIC_LOAD_UMIN:
27812 case ISD::ATOMIC_LOAD_UMAX:
27813 // Delegate to generic TypeLegalization. Situations we can really handle
27814 // should have already been dealt with by AtomicExpandPass.cpp.
27815 break;
27816
27817 case ISD::BITCAST: {
27818 assert(Subtarget.hasSSE2() && "Requires at least SSE2!")((Subtarget.hasSSE2() && "Requires at least SSE2!") ?
static_cast<void> (0) : __assert_fail ("Subtarget.hasSSE2() && \"Requires at least SSE2!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 27818, __PRETTY_FUNCTION__))
;
27819 EVT DstVT = N->getValueType(0);
27820 EVT SrcVT = N->getOperand(0).getValueType();
27821
27822 // If this is a bitcast from a v64i1 k-register to a i64 on a 32-bit target
27823 // we can split using the k-register rather than memory.
27824 if (SrcVT == MVT::v64i1 && DstVT == MVT::i64 && Subtarget.hasBWI()) {
27825 assert(!Subtarget.is64Bit() && "Expected 32-bit mode")((!Subtarget.is64Bit() && "Expected 32-bit mode") ? static_cast
<void> (0) : __assert_fail ("!Subtarget.is64Bit() && \"Expected 32-bit mode\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 27825, __PRETTY_FUNCTION__))
;
27826 SDValue Lo, Hi;
27827 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
27828 Lo = DAG.getBitcast(MVT::i32, Lo);
27829 Hi = DAG.getBitcast(MVT::i32, Hi);
27830 SDValue Res = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
27831 Results.push_back(Res);
27832 return;
27833 }
27834
27835 // Custom splitting for BWI types when AVX512F is available but BWI isn't.
27836 if ((DstVT == MVT::v32i16 || DstVT == MVT::v64i8) &&
27837 SrcVT.isVector() && isTypeLegal(SrcVT)) {
27838 SDValue Lo, Hi;
27839 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
27840 MVT CastVT = (DstVT == MVT::v32i16) ? MVT::v16i16 : MVT::v32i8;
27841 Lo = DAG.getBitcast(CastVT, Lo);
27842 Hi = DAG.getBitcast(CastVT, Hi);
27843 SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, DstVT, Lo, Hi);
27844 Results.push_back(Res);
27845 return;
27846 }
27847
27848 if (SrcVT != MVT::f64 ||
27849 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8) ||
27850 getTypeAction(*DAG.getContext(), DstVT) == TypeWidenVector)
27851 return;
27852
27853 unsigned NumElts = DstVT.getVectorNumElements();
27854 EVT SVT = DstVT.getVectorElementType();
27855 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
27856 SDValue Res;
27857 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, N->getOperand(0));
27858 Res = DAG.getBitcast(WiderVT, Res);
27859 Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, Res,
27860 DAG.getIntPtrConstant(0, dl));
27861 Results.push_back(Res);
27862 return;
27863 }
27864 case ISD::MGATHER: {
27865 EVT VT = N->getValueType(0);
27866 if (VT == MVT::v2f32 && (Subtarget.hasVLX() || !Subtarget.hasAVX512())) {
27867 auto *Gather = cast<MaskedGatherSDNode>(N);
27868 SDValue Index = Gather->getIndex();
27869 if (Index.getValueType() != MVT::v2i64)
27870 return;
27871 SDValue Mask = Gather->getMask();
27872 assert(Mask.getValueType() == MVT::v2i1 && "Unexpected mask type")((Mask.getValueType() == MVT::v2i1 && "Unexpected mask type"
) ? static_cast<void> (0) : __assert_fail ("Mask.getValueType() == MVT::v2i1 && \"Unexpected mask type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 27872, __PRETTY_FUNCTION__))
;
27873 SDValue PassThru = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
27874 Gather->getPassThru(),
27875 DAG.getUNDEF(MVT::v2f32));
27876 if (!Subtarget.hasVLX()) {
27877 // We need to widen the mask, but the instruction will only use 2
27878 // of its elements. So we can use undef.
27879 Mask = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i1, Mask,
27880 DAG.getUNDEF(MVT::v2i1));
27881 Mask = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Mask);
27882 }
27883 SDValue Ops[] = { Gather->getChain(), PassThru, Mask,
27884 Gather->getBasePtr(), Index, Gather->getScale() };
27885 SDValue Res = DAG.getTargetMemSDNode<X86MaskedGatherSDNode>(
27886 DAG.getVTList(MVT::v4f32, Mask.getValueType(), MVT::Other), Ops, dl,
27887 Gather->getMemoryVT(), Gather->getMemOperand());
27888 Results.push_back(Res);
27889 Results.push_back(Res.getValue(2));
27890 return;
27891 }
27892 if (VT == MVT::v2i32) {
27893 auto *Gather = cast<MaskedGatherSDNode>(N);
27894 SDValue Index = Gather->getIndex();
27895 SDValue Mask = Gather->getMask();
27896 assert(Mask.getValueType() == MVT::v2i1 && "Unexpected mask type")((Mask.getValueType() == MVT::v2i1 && "Unexpected mask type"
) ? static_cast<void> (0) : __assert_fail ("Mask.getValueType() == MVT::v2i1 && \"Unexpected mask type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 27896, __PRETTY_FUNCTION__))
;
27897 SDValue PassThru = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32,
27898 Gather->getPassThru(),
27899 DAG.getUNDEF(MVT::v2i32));
27900 // If the index is v2i64 we can use it directly.
27901 if (Index.getValueType() == MVT::v2i64 &&
27902 (Subtarget.hasVLX() || !Subtarget.hasAVX512())) {
27903 if (!Subtarget.hasVLX()) {
27904 // We need to widen the mask, but the instruction will only use 2
27905 // of its elements. So we can use undef.
27906 Mask = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i1, Mask,
27907 DAG.getUNDEF(MVT::v2i1));
27908 Mask = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Mask);
27909 }
27910 SDValue Ops[] = { Gather->getChain(), PassThru, Mask,
27911 Gather->getBasePtr(), Index, Gather->getScale() };
27912 SDValue Res = DAG.getTargetMemSDNode<X86MaskedGatherSDNode>(
27913 DAG.getVTList(MVT::v4i32, Mask.getValueType(), MVT::Other), Ops, dl,
27914 Gather->getMemoryVT(), Gather->getMemOperand());
27915 SDValue Chain = Res.getValue(2);
27916 if (getTypeAction(*DAG.getContext(), VT) != TypeWidenVector)
27917 Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i32, Res,
27918 DAG.getIntPtrConstant(0, dl));
27919 Results.push_back(Res);
27920 Results.push_back(Chain);
27921 return;
27922 }
27923 if (getTypeAction(*DAG.getContext(), VT) != TypeWidenVector) {
27924 EVT IndexVT = Index.getValueType();
27925 EVT NewIndexVT = EVT::getVectorVT(*DAG.getContext(),
27926 IndexVT.getScalarType(), 4);
27927 // Otherwise we need to custom widen everything to avoid promotion.
27928 Index = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewIndexVT, Index,
27929 DAG.getUNDEF(IndexVT));
27930 Mask = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i1, Mask,
27931 DAG.getConstant(0, dl, MVT::v2i1));
27932 SDValue Ops[] = { Gather->getChain(), PassThru, Mask,
27933 Gather->getBasePtr(), Index, Gather->getScale() };
27934 SDValue Res = DAG.getMaskedGather(DAG.getVTList(MVT::v4i32, MVT::Other),
27935 Gather->getMemoryVT(), dl, Ops,
27936 Gather->getMemOperand());
27937 SDValue Chain = Res.getValue(1);
27938 if (getTypeAction(*DAG.getContext(), MVT::v2i32) != TypeWidenVector)
27939 Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i32, Res,
27940 DAG.getIntPtrConstant(0, dl));
27941 Results.push_back(Res);
27942 Results.push_back(Chain);
27943 return;
27944 }
27945 }
27946 return;
27947 }
27948 case ISD::LOAD: {
27949 // Use an f64/i64 load and a scalar_to_vector for v2f32/v2i32 loads. This
27950 // avoids scalarizing in 32-bit mode. In 64-bit mode this avoids a int->fp
27951 // cast since type legalization will try to use an i64 load.
27952 MVT VT = N->getSimpleValueType(0);
27953 assert(VT.isVector() && VT.getSizeInBits() == 64 && "Unexpected VT")((VT.isVector() && VT.getSizeInBits() == 64 &&
"Unexpected VT") ? static_cast<void> (0) : __assert_fail
("VT.isVector() && VT.getSizeInBits() == 64 && \"Unexpected VT\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 27953, __PRETTY_FUNCTION__))
;
27954 if (getTypeAction(*DAG.getContext(), VT) != TypeWidenVector)
27955 return;
27956 if (!ISD::isNON_EXTLoad(N))
27957 return;
27958 auto *Ld = cast<LoadSDNode>(N);
27959 MVT LdVT = Subtarget.is64Bit() && VT.isInteger() ? MVT::i64 : MVT::f64;
27960 SDValue Res = DAG.getLoad(LdVT, dl, Ld->getChain(), Ld->getBasePtr(),
27961 Ld->getPointerInfo(),
27962 Ld->getAlignment(),
27963 Ld->getMemOperand()->getFlags());
27964 SDValue Chain = Res.getValue(1);
27965 MVT WideVT = MVT::getVectorVT(LdVT, 2);
27966 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, WideVT, Res);
27967 MVT CastVT = MVT::getVectorVT(VT.getVectorElementType(),
27968 VT.getVectorNumElements() * 2);
27969 Res = DAG.getBitcast(CastVT, Res);
27970 Results.push_back(Res);
27971 Results.push_back(Chain);
27972 return;
27973 }
27974 }
27975}
27976
27977const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
27978 switch ((X86ISD::NodeType)Opcode) {
27979 case X86ISD::FIRST_NUMBER: break;
27980 case X86ISD::BSF: return "X86ISD::BSF";
27981 case X86ISD::BSR: return "X86ISD::BSR";
27982 case X86ISD::SHLD: return "X86ISD::SHLD";
27983 case X86ISD::SHRD: return "X86ISD::SHRD";
27984 case X86ISD::FAND: return "X86ISD::FAND";
27985 case X86ISD::FANDN: return "X86ISD::FANDN";
27986 case X86ISD::FOR: return "X86ISD::FOR";
27987 case X86ISD::FXOR: return "X86ISD::FXOR";
27988 case X86ISD::FILD: return "X86ISD::FILD";
27989 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
27990 case X86ISD::FIST: return "X86ISD::FIST";
27991 case X86ISD::FP_TO_INT_IN_MEM: return "X86ISD::FP_TO_INT_IN_MEM";
27992 case X86ISD::FLD: return "X86ISD::FLD";
27993 case X86ISD::FST: return "X86ISD::FST";
27994 case X86ISD::CALL: return "X86ISD::CALL";
27995 case X86ISD::BT: return "X86ISD::BT";
27996 case X86ISD::CMP: return "X86ISD::CMP";
27997 case X86ISD::COMI: return "X86ISD::COMI";
27998 case X86ISD::UCOMI: return "X86ISD::UCOMI";
27999 case X86ISD::CMPM: return "X86ISD::CMPM";
28000 case X86ISD::CMPM_SAE: return "X86ISD::CMPM_SAE";
28001 case X86ISD::SETCC: return "X86ISD::SETCC";
28002 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
28003 case X86ISD::FSETCC: return "X86ISD::FSETCC";
28004 case X86ISD::FSETCCM: return "X86ISD::FSETCCM";
28005 case X86ISD::FSETCCM_SAE: return "X86ISD::FSETCCM_SAE";
28006 case X86ISD::CMOV: return "X86ISD::CMOV";
28007 case X86ISD::BRCOND: return "X86ISD::BRCOND";
28008 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
28009 case X86ISD::IRET: return "X86ISD::IRET";
28010 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
28011 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
28012 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
28013 case X86ISD::Wrapper: return "X86ISD::Wrapper";
28014 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
28015 case X86ISD::MOVDQ2Q: return "X86ISD::MOVDQ2Q";
28016 case X86ISD::MMX_MOVD2W: return "X86ISD::MMX_MOVD2W";
28017 case X86ISD::MMX_MOVW2D: return "X86ISD::MMX_MOVW2D";
28018 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
28019 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
28020 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
28021 case X86ISD::PINSRB: return "X86ISD::PINSRB";
28022 case X86ISD::PINSRW: return "X86ISD::PINSRW";
28023 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
28024 case X86ISD::ANDNP: return "X86ISD::ANDNP";
28025 case X86ISD::BLENDI: return "X86ISD::BLENDI";
28026 case X86ISD::BLENDV: return "X86ISD::BLENDV";
28027 case X86ISD::HADD: return "X86ISD::HADD";
28028 case X86ISD::HSUB: return "X86ISD::HSUB";
28029 case X86ISD::FHADD: return "X86ISD::FHADD";
28030 case X86ISD::FHSUB: return "X86ISD::FHSUB";
28031 case X86ISD::CONFLICT: return "X86ISD::CONFLICT";
28032 case X86ISD::FMAX: return "X86ISD::FMAX";
28033 case X86ISD::FMAXS: return "X86ISD::FMAXS";
28034 case X86ISD::FMAX_SAE: return "X86ISD::FMAX_SAE";
28035 case X86ISD::FMAXS_SAE: return "X86ISD::FMAXS_SAE";
28036 case X86ISD::FMIN: return "X86ISD::FMIN";
28037 case X86ISD::FMINS: return "X86ISD::FMINS";
28038 case X86ISD::FMIN_SAE: return "X86ISD::FMIN_SAE";
28039 case X86ISD::FMINS_SAE: return "X86ISD::FMINS_SAE";
28040 case X86ISD::FMAXC: return "X86ISD::FMAXC";
28041 case X86ISD::FMINC: return "X86ISD::FMINC";
28042 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
28043 case X86ISD::FRCP: return "X86ISD::FRCP";
28044 case X86ISD::EXTRQI: return "X86ISD::EXTRQI";
28045 case X86ISD::INSERTQI: return "X86ISD::INSERTQI";
28046 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
28047 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
28048 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
28049 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
28050 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
28051 case X86ISD::EH_SJLJ_SETUP_DISPATCH:
28052 return "X86ISD::EH_SJLJ_SETUP_DISPATCH";
28053 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
28054 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
28055 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
28056 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
28057 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
28058 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
28059 case X86ISD::LCMPXCHG16_DAG: return "X86ISD::LCMPXCHG16_DAG";
28060 case X86ISD::LCMPXCHG8_SAVE_EBX_DAG:
28061 return "X86ISD::LCMPXCHG8_SAVE_EBX_DAG";
28062 case X86ISD::LCMPXCHG16_SAVE_RBX_DAG:
28063 return "X86ISD::LCMPXCHG16_SAVE_RBX_DAG";
28064 case X86ISD::LADD: return "X86ISD::LADD";
28065 case X86ISD::LSUB: return "X86ISD::LSUB";
28066 case X86ISD::LOR: return "X86ISD::LOR";
28067 case X86ISD::LXOR: return "X86ISD::LXOR";
28068 case X86ISD::LAND: return "X86ISD::LAND";
28069 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
28070 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
28071 case X86ISD::VEXTRACT_STORE: return "X86ISD::VEXTRACT_STORE";
28072 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
28073 case X86ISD::VTRUNCS: return "X86ISD::VTRUNCS";
28074 case X86ISD::VTRUNCUS: return "X86ISD::VTRUNCUS";
28075 case X86ISD::VMTRUNC: return "X86ISD::VMTRUNC";
28076 case X86ISD::VMTRUNCS: return "X86ISD::VMTRUNCS";
28077 case X86ISD::VMTRUNCUS: return "X86ISD::VMTRUNCUS";
28078 case X86ISD::VTRUNCSTORES: return "X86ISD::VTRUNCSTORES";
28079 case X86ISD::VTRUNCSTOREUS: return "X86ISD::VTRUNCSTOREUS";
28080 case X86ISD::VMTRUNCSTORES: return "X86ISD::VMTRUNCSTORES";
28081 case X86ISD::VMTRUNCSTOREUS: return "X86ISD::VMTRUNCSTOREUS";
28082 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
28083 case X86ISD::VFPEXT_SAE: return "X86ISD::VFPEXT_SAE";
28084 case X86ISD::VFPEXTS: return "X86ISD::VFPEXTS";
28085 case X86ISD::VFPEXTS_SAE: return "X86ISD::VFPEXTS_SAE";
28086 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
28087 case X86ISD::VMFPROUND: return "X86ISD::VMFPROUND";
28088 case X86ISD::VFPROUND_RND: return "X86ISD::VFPROUND_RND";
28089 case X86ISD::VFPROUNDS: return "X86ISD::VFPROUNDS";
28090 case X86ISD::VFPROUNDS_RND: return "X86ISD::VFPROUNDS_RND";
28091 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
28092 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
28093 case X86ISD::VSHL: return "X86ISD::VSHL";
28094 case X86ISD::VSRL: return "X86ISD::VSRL";
28095 case X86ISD::VSRA: return "X86ISD::VSRA";
28096 case X86ISD::VSHLI: return "X86ISD::VSHLI";
28097 case X86ISD::VSRLI: return "X86ISD::VSRLI";
28098 case X86ISD::VSRAI: return "X86ISD::VSRAI";
28099 case X86ISD::VSHLV: return "X86ISD::VSHLV";
28100 case X86ISD::VSRLV: return "X86ISD::VSRLV";
28101 case X86ISD::VSRAV: return "X86ISD::VSRAV";
28102 case X86ISD::VROTLI: return "X86ISD::VROTLI";
28103 case X86ISD::VROTRI: return "X86ISD::VROTRI";
28104 case X86ISD::VPPERM: return "X86ISD::VPPERM";
28105 case X86ISD::CMPP: return "X86ISD::CMPP";
28106 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
28107 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
28108 case X86ISD::PHMINPOS: return "X86ISD::PHMINPOS";
28109 case X86ISD::ADD: return "X86ISD::ADD";
28110 case X86ISD::SUB: return "X86ISD::SUB";
28111 case X86ISD::ADC: return "X86ISD::ADC";
28112 case X86ISD::SBB: return "X86ISD::SBB";
28113 case X86ISD::SMUL: return "X86ISD::SMUL";
28114 case X86ISD::UMUL: return "X86ISD::UMUL";
28115 case X86ISD::OR: return "X86ISD::OR";
28116 case X86ISD::XOR: return "X86ISD::XOR";
28117 case X86ISD::AND: return "X86ISD::AND";
28118 case X86ISD::BEXTR: return "X86ISD::BEXTR";
28119 case X86ISD::BZHI: return "X86ISD::BZHI";
28120 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
28121 case X86ISD::MOVMSK: return "X86ISD::MOVMSK";
28122 case X86ISD::PTEST: return "X86ISD::PTEST";
28123 case X86ISD::TESTP: return "X86ISD::TESTP";
28124 case X86ISD::KORTEST: return "X86ISD::KORTEST";
28125 case X86ISD::KTEST: return "X86ISD::KTEST";
28126 case X86ISD::KADD: return "X86ISD::KADD";
28127 case X86ISD::KSHIFTL: return "X86ISD::KSHIFTL";
28128 case X86ISD::KSHIFTR: return "X86ISD::KSHIFTR";
28129 case X86ISD::PACKSS: return "X86ISD::PACKSS";
28130 case X86ISD::PACKUS: return "X86ISD::PACKUS";
28131 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
28132 case X86ISD::VALIGN: return "X86ISD::VALIGN";
28133 case X86ISD::VSHLD: return "X86ISD::VSHLD";
28134 case X86ISD::VSHRD: return "X86ISD::VSHRD";
28135 case X86ISD::VSHLDV: return "X86ISD::VSHLDV";
28136 case X86ISD::VSHRDV: return "X86ISD::VSHRDV";
28137 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
28138 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
28139 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
28140 case X86ISD::SHUFP: return "X86ISD::SHUFP";
28141 case X86ISD::SHUF128: return "X86ISD::SHUF128";
28142 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
28143 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
28144 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
28145 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
28146 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
28147 case X86ISD::MOVSD: return "X86ISD::MOVSD";
28148 case X86ISD::MOVSS: return "X86ISD::MOVSS";
28149 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
28150 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
28151 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
28152 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
28153 case X86ISD::SUBV_BROADCAST: return "X86ISD::SUBV_BROADCAST";
28154 case X86ISD::VPERMILPV: return "X86ISD::VPERMILPV";
28155 case X86ISD::VPERMILPI: return "X86ISD::VPERMILPI";
28156 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
28157 case X86ISD::VPERMV: return "X86ISD::VPERMV";
28158 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
28159 case X86ISD::VPERMI: return "X86ISD::VPERMI";
28160 case X86ISD::VPTERNLOG: return "X86ISD::VPTERNLOG";
28161 case X86ISD::VFIXUPIMM: return "X86ISD::VFIXUPIMM";
28162 case X86ISD::VFIXUPIMM_SAE: return "X86ISD::VFIXUPIMM_SAE";
28163 case X86ISD::VFIXUPIMMS: return "X86ISD::VFIXUPIMMS";
28164 case X86ISD::VFIXUPIMMS_SAE: return "X86ISD::VFIXUPIMMS_SAE";
28165 case X86ISD::VRANGE: return "X86ISD::VRANGE";
28166 case X86ISD::VRANGE_SAE: return "X86ISD::VRANGE_SAE";
28167 case X86ISD::VRANGES: return "X86ISD::VRANGES";
28168 case X86ISD::VRANGES_SAE: return "X86ISD::VRANGES_SAE";
28169 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
28170 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
28171 case X86ISD::PSADBW: return "X86ISD::PSADBW";
28172 case X86ISD::DBPSADBW: return "X86ISD::DBPSADBW";
28173 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
28174 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
28175 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
28176 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
28177 case X86ISD::MFENCE: return "X86ISD::MFENCE";
28178 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
28179 case X86ISD::SAHF: return "X86ISD::SAHF";
28180 case X86ISD::RDRAND: return "X86ISD::RDRAND";
28181 case X86ISD::RDSEED: return "X86ISD::RDSEED";
28182 case X86ISD::RDPKRU: return "X86ISD::RDPKRU";
28183 case X86ISD::WRPKRU: return "X86ISD::WRPKRU";
28184 case X86ISD::VPMADDUBSW: return "X86ISD::VPMADDUBSW";
28185 case X86ISD::VPMADDWD: return "X86ISD::VPMADDWD";
28186 case X86ISD::VPSHA: return "X86ISD::VPSHA";
28187 case X86ISD::VPSHL: return "X86ISD::VPSHL";
28188 case X86ISD::VPCOM: return "X86ISD::VPCOM";
28189 case X86ISD::VPCOMU: return "X86ISD::VPCOMU";
28190 case X86ISD::VPERMIL2: return "X86ISD::VPERMIL2";
28191 case X86ISD::FMSUB: return "X86ISD::FMSUB";
28192 case X86ISD::FNMADD: return "X86ISD::FNMADD";
28193 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
28194 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
28195 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
28196 case X86ISD::FMADD_RND: return "X86ISD::FMADD_RND";
28197 case X86ISD::FNMADD_RND: return "X86ISD::FNMADD_RND";
28198 case X86ISD::FMSUB_RND: return "X86ISD::FMSUB_RND";
28199 case X86ISD::FNMSUB_RND: return "X86ISD::FNMSUB_RND";
28200 case X86ISD::FMADDSUB_RND: return "X86ISD::FMADDSUB_RND";
28201 case X86ISD::FMSUBADD_RND: return "X86ISD::FMSUBADD_RND";
28202 case X86ISD::VPMADD52H: return "X86ISD::VPMADD52H";
28203 case X86ISD::VPMADD52L: return "X86ISD::VPMADD52L";
28204 case X86ISD::VRNDSCALE: return "X86ISD::VRNDSCALE";
28205 case X86ISD::VRNDSCALE_SAE: return "X86ISD::VRNDSCALE_SAE";
28206 case X86ISD::VRNDSCALES: return "X86ISD::VRNDSCALES";
28207 case X86ISD::VRNDSCALES_SAE: return "X86ISD::VRNDSCALES_SAE";
28208 case X86ISD::VREDUCE: return "X86ISD::VREDUCE";
28209 case X86ISD::VREDUCE_SAE: return "X86ISD::VREDUCE_SAE";
28210 case X86ISD::VREDUCES: return "X86ISD::VREDUCES";
28211 case X86ISD::VREDUCES_SAE: return "X86ISD::VREDUCES_SAE";
28212 case X86ISD::VGETMANT: return "X86ISD::VGETMANT";
28213 case X86ISD::VGETMANT_SAE: return "X86ISD::VGETMANT_SAE";
28214 case X86ISD::VGETMANTS: return "X86ISD::VGETMANTS";
28215 case X86ISD::VGETMANTS_SAE: return "X86ISD::VGETMANTS_SAE";
28216 case X86ISD::PCMPESTR: return "X86ISD::PCMPESTR";
28217 case X86ISD::PCMPISTR: return "X86ISD::PCMPISTR";
28218 case X86ISD::XTEST: return "X86ISD::XTEST";
28219 case X86ISD::COMPRESS: return "X86ISD::COMPRESS";
28220 case X86ISD::EXPAND: return "X86ISD::EXPAND";
28221 case X86ISD::SELECTS: return "X86ISD::SELECTS";
28222 case X86ISD::ADDSUB: return "X86ISD::ADDSUB";
28223 case X86ISD::RCP14: return "X86ISD::RCP14";
28224 case X86ISD::RCP14S: return "X86ISD::RCP14S";
28225 case X86ISD::RCP28: return "X86ISD::RCP28";
28226 case X86ISD::RCP28_SAE: return "X86ISD::RCP28_SAE";
28227 case X86ISD::RCP28S: return "X86ISD::RCP28S";
28228 case X86ISD::RCP28S_SAE: return "X86ISD::RCP28S_SAE";
28229 case X86ISD::EXP2: return "X86ISD::EXP2";
28230 case X86ISD::EXP2_SAE: return "X86ISD::EXP2_SAE";
28231 case X86ISD::RSQRT14: return "X86ISD::RSQRT14";
28232 case X86ISD::RSQRT14S: return "X86ISD::RSQRT14S";
28233 case X86ISD::RSQRT28: return "X86ISD::RSQRT28";
28234 case X86ISD::RSQRT28_SAE: return "X86ISD::RSQRT28_SAE";
28235 case X86ISD::RSQRT28S: return "X86ISD::RSQRT28S";
28236 case X86ISD::RSQRT28S_SAE: return "X86ISD::RSQRT28S_SAE";
28237 case X86ISD::FADD_RND: return "X86ISD::FADD_RND";
28238 case X86ISD::FADDS: return "X86ISD::FADDS";
28239 case X86ISD::FADDS_RND: return "X86ISD::FADDS_RND";
28240 case X86ISD::FSUB_RND: return "X86ISD::FSUB_RND";
28241 case X86ISD::FSUBS: return "X86ISD::FSUBS";
28242 case X86ISD::FSUBS_RND: return "X86ISD::FSUBS_RND";
28243 case X86ISD::FMUL_RND: return "X86ISD::FMUL_RND";
28244 case X86ISD::FMULS: return "X86ISD::FMULS";
28245 case X86ISD::FMULS_RND: return "X86ISD::FMULS_RND";
28246 case X86ISD::FDIV_RND: return "X86ISD::FDIV_RND";
28247 case X86ISD::FDIVS: return "X86ISD::FDIVS";
28248 case X86ISD::FDIVS_RND: return "X86ISD::FDIVS_RND";
28249 case X86ISD::FSQRT_RND: return "X86ISD::FSQRT_RND";
28250 case X86ISD::FSQRTS: return "X86ISD::FSQRTS";
28251 case X86ISD::FSQRTS_RND: return "X86ISD::FSQRTS_RND";
28252 case X86ISD::FGETEXP: return "X86ISD::FGETEXP";
28253 case X86ISD::FGETEXP_SAE: return "X86ISD::FGETEXP_SAE";
28254 case X86ISD::FGETEXPS: return "X86ISD::FGETEXPS";
28255 case X86ISD::FGETEXPS_SAE: return "X86ISD::FGETEXPS_SAE";
28256 case X86ISD::SCALEF: return "X86ISD::SCALEF";
28257 case X86ISD::SCALEF_RND: return "X86ISD::SCALEF_RND";
28258 case X86ISD::SCALEFS: return "X86ISD::SCALEFS";
28259 case X86ISD::SCALEFS_RND: return "X86ISD::SCALEFS_RND";
28260 case X86ISD::AVG: return "X86ISD::AVG";
28261 case X86ISD::MULHRS: return "X86ISD::MULHRS";
28262 case X86ISD::SINT_TO_FP_RND: return "X86ISD::SINT_TO_FP_RND";
28263 case X86ISD::UINT_TO_FP_RND: return "X86ISD::UINT_TO_FP_RND";
28264 case X86ISD::CVTTP2SI: return "X86ISD::CVTTP2SI";
28265 case X86ISD::CVTTP2UI: return "X86ISD::CVTTP2UI";
28266 case X86ISD::MCVTTP2SI: return "X86ISD::MCVTTP2SI";
28267 case X86ISD::MCVTTP2UI: return "X86ISD::MCVTTP2UI";
28268 case X86ISD::CVTTP2SI_SAE: return "X86ISD::CVTTP2SI_SAE";
28269 case X86ISD::CVTTP2UI_SAE: return "X86ISD::CVTTP2UI_SAE";
28270 case X86ISD::CVTTS2SI: return "X86ISD::CVTTS2SI";
28271 case X86ISD::CVTTS2UI: return "X86ISD::CVTTS2UI";
28272 case X86ISD::CVTTS2SI_SAE: return "X86ISD::CVTTS2SI_SAE";
28273 case X86ISD::CVTTS2UI_SAE: return "X86ISD::CVTTS2UI_SAE";
28274 case X86ISD::CVTSI2P: return "X86ISD::CVTSI2P";
28275 case X86ISD::CVTUI2P: return "X86ISD::CVTUI2P";
28276 case X86ISD::MCVTSI2P: return "X86ISD::MCVTSI2P";
28277 case X86ISD::MCVTUI2P: return "X86ISD::MCVTUI2P";
28278 case X86ISD::VFPCLASS: return "X86ISD::VFPCLASS";
28279 case X86ISD::VFPCLASSS: return "X86ISD::VFPCLASSS";
28280 case X86ISD::MULTISHIFT: return "X86ISD::MULTISHIFT";
28281 case X86ISD::SCALAR_SINT_TO_FP: return "X86ISD::SCALAR_SINT_TO_FP";
28282 case X86ISD::SCALAR_SINT_TO_FP_RND: return "X86ISD::SCALAR_SINT_TO_FP_RND";
28283 case X86ISD::SCALAR_UINT_TO_FP: return "X86ISD::SCALAR_UINT_TO_FP";
28284 case X86ISD::SCALAR_UINT_TO_FP_RND: return "X86ISD::SCALAR_UINT_TO_FP_RND";
28285 case X86ISD::CVTPS2PH: return "X86ISD::CVTPS2PH";
28286 case X86ISD::MCVTPS2PH: return "X86ISD::MCVTPS2PH";
28287 case X86ISD::CVTPH2PS: return "X86ISD::CVTPH2PS";
28288 case X86ISD::CVTPH2PS_SAE: return "X86ISD::CVTPH2PS_SAE";
28289 case X86ISD::CVTP2SI: return "X86ISD::CVTP2SI";
28290 case X86ISD::CVTP2UI: return "X86ISD::CVTP2UI";
28291 case X86ISD::MCVTP2SI: return "X86ISD::MCVTP2SI";
28292 case X86ISD::MCVTP2UI: return "X86ISD::MCVTP2UI";
28293 case X86ISD::CVTP2SI_RND: return "X86ISD::CVTP2SI_RND";
28294 case X86ISD::CVTP2UI_RND: return "X86ISD::CVTP2UI_RND";
28295 case X86ISD::CVTS2SI: return "X86ISD::CVTS2SI";
28296 case X86ISD::CVTS2UI: return "X86ISD::CVTS2UI";
28297 case X86ISD::CVTS2SI_RND: return "X86ISD::CVTS2SI_RND";
28298 case X86ISD::CVTS2UI_RND: return "X86ISD::CVTS2UI_RND";
28299 case X86ISD::CVTNE2PS2BF16: return "X86ISD::CVTNE2PS2BF16";
28300 case X86ISD::CVTNEPS2BF16: return "X86ISD::CVTNEPS2BF16";
28301 case X86ISD::MCVTNEPS2BF16: return "X86ISD::MCVTNEPS2BF16";
28302 case X86ISD::DPBF16PS: return "X86ISD::DPBF16PS";
28303 case X86ISD::LWPINS: return "X86ISD::LWPINS";
28304 case X86ISD::MGATHER: return "X86ISD::MGATHER";
28305 case X86ISD::MSCATTER: return "X86ISD::MSCATTER";
28306 case X86ISD::VPDPBUSD: return "X86ISD::VPDPBUSD";
28307 case X86ISD::VPDPBUSDS: return "X86ISD::VPDPBUSDS";
28308 case X86ISD::VPDPWSSD: return "X86ISD::VPDPWSSD";
28309 case X86ISD::VPDPWSSDS: return "X86ISD::VPDPWSSDS";
28310 case X86ISD::VPSHUFBITQMB: return "X86ISD::VPSHUFBITQMB";
28311 case X86ISD::GF2P8MULB: return "X86ISD::GF2P8MULB";
28312 case X86ISD::GF2P8AFFINEQB: return "X86ISD::GF2P8AFFINEQB";
28313 case X86ISD::GF2P8AFFINEINVQB: return "X86ISD::GF2P8AFFINEINVQB";
28314 case X86ISD::NT_CALL: return "X86ISD::NT_CALL";
28315 case X86ISD::NT_BRIND: return "X86ISD::NT_BRIND";
28316 case X86ISD::UMWAIT: return "X86ISD::UMWAIT";
28317 case X86ISD::TPAUSE: return "X86ISD::TPAUSE";
28318 case X86ISD::ENQCMD: return "X86ISD:ENQCMD";
28319 case X86ISD::ENQCMDS: return "X86ISD:ENQCMDS";
28320 case X86ISD::VP2INTERSECT: return "X86ISD::VP2INTERSECT";
28321 }
28322 return nullptr;
28323}
28324
28325/// Return true if the addressing mode represented by AM is legal for this
28326/// target, for a load/store of the specified type.
28327bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
28328 const AddrMode &AM, Type *Ty,
28329 unsigned AS,
28330 Instruction *I) const {
28331 // X86 supports extremely general addressing modes.
28332 CodeModel::Model M = getTargetMachine().getCodeModel();
28333
28334 // X86 allows a sign-extended 32-bit immediate field as a displacement.
28335 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
28336 return false;
28337
28338 if (AM.BaseGV) {
28339 unsigned GVFlags = Subtarget.classifyGlobalReference(AM.BaseGV);
28340
28341 // If a reference to this global requires an extra load, we can't fold it.
28342 if (isGlobalStubReference(GVFlags))
28343 return false;
28344
28345 // If BaseGV requires a register for the PIC base, we cannot also have a
28346 // BaseReg specified.
28347 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
28348 return false;
28349
28350 // If lower 4G is not available, then we must use rip-relative addressing.
28351 if ((M != CodeModel::Small || isPositionIndependent()) &&
28352 Subtarget.is64Bit() && (AM.BaseOffs || AM.Scale > 1))
28353 return false;
28354 }
28355
28356 switch (AM.Scale) {
28357 case 0:
28358 case 1:
28359 case 2:
28360 case 4:
28361 case 8:
28362 // These scales always work.
28363 break;
28364 case 3:
28365 case 5:
28366 case 9:
28367 // These scales are formed with basereg+scalereg. Only accept if there is
28368 // no basereg yet.
28369 if (AM.HasBaseReg)
28370 return false;
28371 break;
28372 default: // Other stuff never works.
28373 return false;
28374 }
28375
28376 return true;
28377}
28378
28379bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
28380 unsigned Bits = Ty->getScalarSizeInBits();
28381
28382 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
28383 // particularly cheaper than those without.
28384 if (Bits == 8)
28385 return false;
28386
28387 // XOP has v16i8/v8i16/v4i32/v2i64 variable vector shifts.
28388 if (Subtarget.hasXOP() && Ty->getPrimitiveSizeInBits() == 128 &&
28389 (Bits == 8 || Bits == 16 || Bits == 32 || Bits == 64))
28390 return false;
28391
28392 // AVX2 has vpsllv[dq] instructions (and other shifts) that make variable
28393 // shifts just as cheap as scalar ones.
28394 if (Subtarget.hasAVX2() && (Bits == 32 || Bits == 64))
28395 return false;
28396
28397 // AVX512BW has shifts such as vpsllvw.
28398 if (Subtarget.hasBWI() && Bits == 16)
28399 return false;
28400
28401 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
28402 // fully general vector.
28403 return true;
28404}
28405
28406bool X86TargetLowering::isBinOp(unsigned Opcode) const {
28407 switch (Opcode) {
28408 case X86ISD::PMULUDQ:
28409 case X86ISD::FMAX:
28410 case X86ISD::FMIN:
28411 case X86ISD::FMAXC:
28412 case X86ISD::FMINC:
28413 case X86ISD::FAND:
28414 case X86ISD::FANDN:
28415 case X86ISD::FOR:
28416 case X86ISD::FXOR:
28417 return true;
28418 }
28419
28420 return TargetLoweringBase::isBinOp(Opcode);
28421}
28422
28423bool X86TargetLowering::isCommutativeBinOp(unsigned Opcode) const {
28424 switch (Opcode) {
28425 // TODO: Add more X86ISD opcodes once we have test coverage.
28426 case X86ISD::PMULUDQ:
28427 return true;
28428 }
28429
28430 return TargetLoweringBase::isCommutativeBinOp(Opcode);
28431}
28432
28433bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
28434 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
28435 return false;
28436 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
28437 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
28438 return NumBits1 > NumBits2;
28439}
28440
28441bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
28442 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
28443 return false;
28444
28445 if (!isTypeLegal(EVT::getEVT(Ty1)))
28446 return false;
28447
28448 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop")((Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop"
) ? static_cast<void> (0) : __assert_fail ("Ty1->getPrimitiveSizeInBits() <= 64 && \"i128 is probably not a noop\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 28448, __PRETTY_FUNCTION__))
;
28449
28450 // Assuming the caller doesn't have a zeroext or signext return parameter,
28451 // truncation all the way down to i1 is valid.
28452 return true;
28453}
28454
28455bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
28456 return isInt<32>(Imm);
28457}
28458
28459bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
28460 // Can also use sub to handle negated immediates.
28461 return isInt<32>(Imm);
28462}
28463
28464bool X86TargetLowering::isLegalStoreImmediate(int64_t Imm) const {
28465 return isInt<32>(Imm);
28466}
28467
28468bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
28469 if (!VT1.isInteger() || !VT2.isInteger())
28470 return false;
28471 unsigned NumBits1 = VT1.getSizeInBits();
28472 unsigned NumBits2 = VT2.getSizeInBits();
28473 return NumBits1 > NumBits2;
28474}
28475
28476bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
28477 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
28478 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget.is64Bit();
28479}
28480
28481bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
28482 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
28483 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget.is64Bit();
28484}
28485
28486bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
28487 EVT VT1 = Val.getValueType();
28488 if (isZExtFree(VT1, VT2))
28489 return true;
28490
28491 if (Val.getOpcode() != ISD::LOAD)
28492 return false;
28493
28494 if (!VT1.isSimple() || !VT1.isInteger() ||
28495 !VT2.isSimple() || !VT2.isInteger())
28496 return false;
28497
28498 switch (VT1.getSimpleVT().SimpleTy) {
28499 default: break;
28500 case MVT::i8:
28501 case MVT::i16:
28502 case MVT::i32:
28503 // X86 has 8, 16, and 32-bit zero-extending loads.
28504 return true;
28505 }
28506
28507 return false;
28508}
28509
28510bool X86TargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
28511 EVT SrcVT = ExtVal.getOperand(0).getValueType();
28512
28513 // There is no extending load for vXi1.
28514 if (SrcVT.getScalarType() == MVT::i1)
28515 return false;
28516
28517 return true;
28518}
28519
28520bool
28521X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
28522 if (!Subtarget.hasAnyFMA())
28523 return false;
28524
28525 VT = VT.getScalarType();
28526
28527 if (!VT.isSimple())
28528 return false;
28529
28530 switch (VT.getSimpleVT().SimpleTy) {
28531 case MVT::f32:
28532 case MVT::f64:
28533 return true;
28534 default:
28535 break;
28536 }
28537
28538 return false;
28539}
28540
28541bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
28542 // i16 instructions are longer (0x66 prefix) and potentially slower.
28543 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
28544}
28545
28546/// Targets can use this to indicate that they only support *some*
28547/// VECTOR_SHUFFLE operations, those with specific masks.
28548/// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
28549/// are assumed to be legal.
28550bool X86TargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
28551 if (!VT.isSimple())
28552 return false;
28553
28554 // Not for i1 vectors
28555 if (VT.getSimpleVT().getScalarType() == MVT::i1)
28556 return false;
28557
28558 // Very little shuffling can be done for 64-bit vectors right now.
28559 if (VT.getSimpleVT().getSizeInBits() == 64)
28560 return false;
28561
28562 // We only care that the types being shuffled are legal. The lowering can
28563 // handle any possible shuffle mask that results.
28564 return isTypeLegal(VT.getSimpleVT());
28565}
28566
28567bool X86TargetLowering::isVectorClearMaskLegal(ArrayRef<int> Mask,
28568 EVT VT) const {
28569 // Don't convert an 'and' into a shuffle that we don't directly support.
28570 // vpblendw and vpshufb for 256-bit vectors are not available on AVX1.
28571 if (!Subtarget.hasAVX2())
28572 if (VT == MVT::v32i8 || VT == MVT::v16i16)
28573 return false;
28574
28575 // Just delegate to the generic legality, clear masks aren't special.
28576 return isShuffleMaskLegal(Mask, VT);
28577}
28578
28579bool X86TargetLowering::areJTsAllowed(const Function *Fn) const {
28580 // If the subtarget is using retpolines, we need to not generate jump tables.
28581 if (Subtarget.useRetpolineIndirectBranches())
28582 return false;
28583
28584 // Otherwise, fallback on the generic logic.
28585 return TargetLowering::areJTsAllowed(Fn);
28586}
28587
28588//===----------------------------------------------------------------------===//
28589// X86 Scheduler Hooks
28590//===----------------------------------------------------------------------===//
28591
28592/// Utility function to emit xbegin specifying the start of an RTM region.
28593static MachineBasicBlock *emitXBegin(MachineInstr &MI, MachineBasicBlock *MBB,
28594 const TargetInstrInfo *TII) {
28595 DebugLoc DL = MI.getDebugLoc();
28596
28597 const BasicBlock *BB = MBB->getBasicBlock();
28598 MachineFunction::iterator I = ++MBB->getIterator();
28599
28600 // For the v = xbegin(), we generate
28601 //
28602 // thisMBB:
28603 // xbegin sinkMBB
28604 //
28605 // mainMBB:
28606 // s0 = -1
28607 //
28608 // fallBB:
28609 // eax = # XABORT_DEF
28610 // s1 = eax
28611 //
28612 // sinkMBB:
28613 // v = phi(s0/mainBB, s1/fallBB)
28614
28615 MachineBasicBlock *thisMBB = MBB;
28616 MachineFunction *MF = MBB->getParent();
28617 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
28618 MachineBasicBlock *fallMBB = MF->CreateMachineBasicBlock(BB);
28619 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
28620 MF->insert(I, mainMBB);
28621 MF->insert(I, fallMBB);
28622 MF->insert(I, sinkMBB);
28623
28624 // Transfer the remainder of BB and its successor edges to sinkMBB.
28625 sinkMBB->splice(sinkMBB->begin(), MBB,
28626 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
28627 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
28628
28629 MachineRegisterInfo &MRI = MF->getRegInfo();
28630 unsigned DstReg = MI.getOperand(0).getReg();
28631 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
28632 unsigned mainDstReg = MRI.createVirtualRegister(RC);
28633 unsigned fallDstReg = MRI.createVirtualRegister(RC);
28634
28635 // thisMBB:
28636 // xbegin fallMBB
28637 // # fallthrough to mainMBB
28638 // # abortion to fallMBB
28639 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(fallMBB);
28640 thisMBB->addSuccessor(mainMBB);
28641 thisMBB->addSuccessor(fallMBB);
28642
28643 // mainMBB:
28644 // mainDstReg := -1
28645 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), mainDstReg).addImm(-1);
28646 BuildMI(mainMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
28647 mainMBB->addSuccessor(sinkMBB);
28648
28649 // fallMBB:
28650 // ; pseudo instruction to model hardware's definition from XABORT
28651 // EAX := XABORT_DEF
28652 // fallDstReg := EAX
28653 BuildMI(fallMBB, DL, TII->get(X86::XABORT_DEF));
28654 BuildMI(fallMBB, DL, TII->get(TargetOpcode::COPY), fallDstReg)
28655 .addReg(X86::EAX);
28656 fallMBB->addSuccessor(sinkMBB);
28657
28658 // sinkMBB:
28659 // DstReg := phi(mainDstReg/mainBB, fallDstReg/fallBB)
28660 BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(X86::PHI), DstReg)
28661 .addReg(mainDstReg).addMBB(mainMBB)
28662 .addReg(fallDstReg).addMBB(fallMBB);
28663
28664 MI.eraseFromParent();
28665 return sinkMBB;
28666}
28667
28668
28669
28670MachineBasicBlock *
28671X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr &MI,
28672 MachineBasicBlock *MBB) const {
28673 // Emit va_arg instruction on X86-64.
28674
28675 // Operands to this pseudo-instruction:
28676 // 0 ) Output : destination address (reg)
28677 // 1-5) Input : va_list address (addr, i64mem)
28678 // 6 ) ArgSize : Size (in bytes) of vararg type
28679 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
28680 // 8 ) Align : Alignment of type
28681 // 9 ) EFLAGS (implicit-def)
28682
28683 assert(MI.getNumOperands() == 10 && "VAARG_64 should have 10 operands!")((MI.getNumOperands() == 10 && "VAARG_64 should have 10 operands!"
) ? static_cast<void> (0) : __assert_fail ("MI.getNumOperands() == 10 && \"VAARG_64 should have 10 operands!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 28683, __PRETTY_FUNCTION__))
;
28684 static_assert(X86::AddrNumOperands == 5,
28685 "VAARG_64 assumes 5 address operands");
28686
28687 unsigned DestReg = MI.getOperand(0).getReg();
28688 MachineOperand &Base = MI.getOperand(1);
28689 MachineOperand &Scale = MI.getOperand(2);
28690 MachineOperand &Index = MI.getOperand(3);
28691 MachineOperand &Disp = MI.getOperand(4);
28692 MachineOperand &Segment = MI.getOperand(5);
28693 unsigned ArgSize = MI.getOperand(6).getImm();
28694 unsigned ArgMode = MI.getOperand(7).getImm();
28695 unsigned Align = MI.getOperand(8).getImm();
28696
28697 // Memory Reference
28698 assert(MI.hasOneMemOperand() && "Expected VAARG_64 to have one memoperand")((MI.hasOneMemOperand() && "Expected VAARG_64 to have one memoperand"
) ? static_cast<void> (0) : __assert_fail ("MI.hasOneMemOperand() && \"Expected VAARG_64 to have one memoperand\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 28698, __PRETTY_FUNCTION__))
;
28699 SmallVector<MachineMemOperand *, 1> MMOs(MI.memoperands_begin(),
28700 MI.memoperands_end());
28701
28702 // Machine Information
28703 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
28704 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
28705 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
28706 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
28707 DebugLoc DL = MI.getDebugLoc();
28708
28709 // struct va_list {
28710 // i32 gp_offset
28711 // i32 fp_offset
28712 // i64 overflow_area (address)
28713 // i64 reg_save_area (address)
28714 // }
28715 // sizeof(va_list) = 24
28716 // alignment(va_list) = 8
28717
28718 unsigned TotalNumIntRegs = 6;
28719 unsigned TotalNumXMMRegs = 8;
28720 bool UseGPOffset = (ArgMode == 1);
28721 bool UseFPOffset = (ArgMode == 2);
28722 unsigned MaxOffset = TotalNumIntRegs * 8 +
28723 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
28724
28725 /* Align ArgSize to a multiple of 8 */
28726 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
28727 bool NeedsAlign = (Align > 8);
28728
28729 MachineBasicBlock *thisMBB = MBB;
28730 MachineBasicBlock *overflowMBB;
28731 MachineBasicBlock *offsetMBB;
28732 MachineBasicBlock *endMBB;
28733
28734 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
28735 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
28736 unsigned OffsetReg = 0;
28737
28738 if (!UseGPOffset && !UseFPOffset) {
28739 // If we only pull from the overflow region, we don't create a branch.
28740 // We don't need to alter control flow.
28741 OffsetDestReg = 0; // unused
28742 OverflowDestReg = DestReg;
28743
28744 offsetMBB = nullptr;
28745 overflowMBB = thisMBB;
28746 endMBB = thisMBB;
28747 } else {
28748 // First emit code to check if gp_offset (or fp_offset) is below the bound.
28749 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
28750 // If not, pull from overflow_area. (branch to overflowMBB)
28751 //
28752 // thisMBB
28753 // | .
28754 // | .
28755 // offsetMBB overflowMBB
28756 // | .
28757 // | .
28758 // endMBB
28759
28760 // Registers for the PHI in endMBB
28761 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
28762 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
28763
28764 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
28765 MachineFunction *MF = MBB->getParent();
28766 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
28767 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
28768 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
28769
28770 MachineFunction::iterator MBBIter = ++MBB->getIterator();
28771
28772 // Insert the new basic blocks
28773 MF->insert(MBBIter, offsetMBB);
28774 MF->insert(MBBIter, overflowMBB);
28775 MF->insert(MBBIter, endMBB);
28776
28777 // Transfer the remainder of MBB and its successor edges to endMBB.
28778 endMBB->splice(endMBB->begin(), thisMBB,
28779 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
28780 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
28781
28782 // Make offsetMBB and overflowMBB successors of thisMBB
28783 thisMBB->addSuccessor(offsetMBB);
28784 thisMBB->addSuccessor(overflowMBB);
28785
28786 // endMBB is a successor of both offsetMBB and overflowMBB
28787 offsetMBB->addSuccessor(endMBB);
28788 overflowMBB->addSuccessor(endMBB);
28789
28790 // Load the offset value into a register
28791 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
28792 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
28793 .add(Base)
28794 .add(Scale)
28795 .add(Index)
28796 .addDisp(Disp, UseFPOffset ? 4 : 0)
28797 .add(Segment)
28798 .setMemRefs(MMOs);
28799
28800 // Check if there is enough room left to pull this argument.
28801 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
28802 .addReg(OffsetReg)
28803 .addImm(MaxOffset + 8 - ArgSizeA8);
28804
28805 // Branch to "overflowMBB" if offset >= max
28806 // Fall through to "offsetMBB" otherwise
28807 BuildMI(thisMBB, DL, TII->get(X86::JCC_1))
28808 .addMBB(overflowMBB).addImm(X86::COND_AE);
28809 }
28810
28811 // In offsetMBB, emit code to use the reg_save_area.
28812 if (offsetMBB) {
28813 assert(OffsetReg != 0)((OffsetReg != 0) ? static_cast<void> (0) : __assert_fail
("OffsetReg != 0", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 28813, __PRETTY_FUNCTION__))
;
28814
28815 // Read the reg_save_area address.
28816 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
28817 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
28818 .add(Base)
28819 .add(Scale)
28820 .add(Index)
28821 .addDisp(Disp, 16)
28822 .add(Segment)
28823 .setMemRefs(MMOs);
28824
28825 // Zero-extend the offset
28826 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
28827 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
28828 .addImm(0)
28829 .addReg(OffsetReg)
28830 .addImm(X86::sub_32bit);
28831
28832 // Add the offset to the reg_save_area to get the final address.
28833 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
28834 .addReg(OffsetReg64)
28835 .addReg(RegSaveReg);
28836
28837 // Compute the offset for the next argument
28838 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
28839 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
28840 .addReg(OffsetReg)
28841 .addImm(UseFPOffset ? 16 : 8);
28842
28843 // Store it back into the va_list.
28844 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
28845 .add(Base)
28846 .add(Scale)
28847 .add(Index)
28848 .addDisp(Disp, UseFPOffset ? 4 : 0)
28849 .add(Segment)
28850 .addReg(NextOffsetReg)
28851 .setMemRefs(MMOs);
28852
28853 // Jump to endMBB
28854 BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
28855 .addMBB(endMBB);
28856 }
28857
28858 //
28859 // Emit code to use overflow area
28860 //
28861
28862 // Load the overflow_area address into a register.
28863 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
28864 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
28865 .add(Base)
28866 .add(Scale)
28867 .add(Index)
28868 .addDisp(Disp, 8)
28869 .add(Segment)
28870 .setMemRefs(MMOs);
28871
28872 // If we need to align it, do so. Otherwise, just copy the address
28873 // to OverflowDestReg.
28874 if (NeedsAlign) {
28875 // Align the overflow address
28876 assert(isPowerOf2_32(Align) && "Alignment must be a power of 2")((isPowerOf2_32(Align) && "Alignment must be a power of 2"
) ? static_cast<void> (0) : __assert_fail ("isPowerOf2_32(Align) && \"Alignment must be a power of 2\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 28876, __PRETTY_FUNCTION__))
;
28877 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
28878
28879 // aligned_addr = (addr + (align-1)) & ~(align-1)
28880 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
28881 .addReg(OverflowAddrReg)
28882 .addImm(Align-1);
28883
28884 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
28885 .addReg(TmpReg)
28886 .addImm(~(uint64_t)(Align-1));
28887 } else {
28888 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
28889 .addReg(OverflowAddrReg);
28890 }
28891
28892 // Compute the next overflow address after this argument.
28893 // (the overflow address should be kept 8-byte aligned)
28894 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
28895 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
28896 .addReg(OverflowDestReg)
28897 .addImm(ArgSizeA8);
28898
28899 // Store the new overflow address.
28900 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
28901 .add(Base)
28902 .add(Scale)
28903 .add(Index)
28904 .addDisp(Disp, 8)
28905 .add(Segment)
28906 .addReg(NextAddrReg)
28907 .setMemRefs(MMOs);
28908
28909 // If we branched, emit the PHI to the front of endMBB.
28910 if (offsetMBB) {
28911 BuildMI(*endMBB, endMBB->begin(), DL,
28912 TII->get(X86::PHI), DestReg)
28913 .addReg(OffsetDestReg).addMBB(offsetMBB)
28914 .addReg(OverflowDestReg).addMBB(overflowMBB);
28915 }
28916
28917 // Erase the pseudo instruction
28918 MI.eraseFromParent();
28919
28920 return endMBB;
28921}
28922
28923MachineBasicBlock *X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
28924 MachineInstr &MI, MachineBasicBlock *MBB) const {
28925 // Emit code to save XMM registers to the stack. The ABI says that the
28926 // number of registers to save is given in %al, so it's theoretically
28927 // possible to do an indirect jump trick to avoid saving all of them,
28928 // however this code takes a simpler approach and just executes all
28929 // of the stores if %al is non-zero. It's less code, and it's probably
28930 // easier on the hardware branch predictor, and stores aren't all that
28931 // expensive anyway.
28932
28933 // Create the new basic blocks. One block contains all the XMM stores,
28934 // and one block is the final destination regardless of whether any
28935 // stores were performed.
28936 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
28937 MachineFunction *F = MBB->getParent();
28938 MachineFunction::iterator MBBIter = ++MBB->getIterator();
28939 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
28940 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
28941 F->insert(MBBIter, XMMSaveMBB);
28942 F->insert(MBBIter, EndMBB);
28943
28944 // Transfer the remainder of MBB and its successor edges to EndMBB.
28945 EndMBB->splice(EndMBB->begin(), MBB,
28946 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
28947 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
28948
28949 // The original block will now fall through to the XMM save block.
28950 MBB->addSuccessor(XMMSaveMBB);
28951 // The XMMSaveMBB will fall through to the end block.
28952 XMMSaveMBB->addSuccessor(EndMBB);
28953
28954 // Now add the instructions.
28955 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
28956 DebugLoc DL = MI.getDebugLoc();
28957
28958 unsigned CountReg = MI.getOperand(0).getReg();
28959 int64_t RegSaveFrameIndex = MI.getOperand(1).getImm();
28960 int64_t VarArgsFPOffset = MI.getOperand(2).getImm();
28961
28962 if (!Subtarget.isCallingConvWin64(F->getFunction().getCallingConv())) {
28963 // If %al is 0, branch around the XMM save block.
28964 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
28965 BuildMI(MBB, DL, TII->get(X86::JCC_1)).addMBB(EndMBB).addImm(X86::COND_E);
28966 MBB->addSuccessor(EndMBB);
28967 }
28968
28969 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
28970 // that was just emitted, but clearly shouldn't be "saved".
28971 assert((MI.getNumOperands() <= 3 ||(((MI.getNumOperands() <= 3 || !MI.getOperand(MI.getNumOperands
() - 1).isReg() || MI.getOperand(MI.getNumOperands() - 1).getReg
() == X86::EFLAGS) && "Expected last argument to be EFLAGS"
) ? static_cast<void> (0) : __assert_fail ("(MI.getNumOperands() <= 3 || !MI.getOperand(MI.getNumOperands() - 1).isReg() || MI.getOperand(MI.getNumOperands() - 1).getReg() == X86::EFLAGS) && \"Expected last argument to be EFLAGS\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 28974, __PRETTY_FUNCTION__))
28972 !MI.getOperand(MI.getNumOperands() - 1).isReg() ||(((MI.getNumOperands() <= 3 || !MI.getOperand(MI.getNumOperands
() - 1).isReg() || MI.getOperand(MI.getNumOperands() - 1).getReg
() == X86::EFLAGS) && "Expected last argument to be EFLAGS"
) ? static_cast<void> (0) : __assert_fail ("(MI.getNumOperands() <= 3 || !MI.getOperand(MI.getNumOperands() - 1).isReg() || MI.getOperand(MI.getNumOperands() - 1).getReg() == X86::EFLAGS) && \"Expected last argument to be EFLAGS\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 28974, __PRETTY_FUNCTION__))
28973 MI.getOperand(MI.getNumOperands() - 1).getReg() == X86::EFLAGS) &&(((MI.getNumOperands() <= 3 || !MI.getOperand(MI.getNumOperands
() - 1).isReg() || MI.getOperand(MI.getNumOperands() - 1).getReg
() == X86::EFLAGS) && "Expected last argument to be EFLAGS"
) ? static_cast<void> (0) : __assert_fail ("(MI.getNumOperands() <= 3 || !MI.getOperand(MI.getNumOperands() - 1).isReg() || MI.getOperand(MI.getNumOperands() - 1).getReg() == X86::EFLAGS) && \"Expected last argument to be EFLAGS\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 28974, __PRETTY_FUNCTION__))
28974 "Expected last argument to be EFLAGS")(((MI.getNumOperands() <= 3 || !MI.getOperand(MI.getNumOperands
() - 1).isReg() || MI.getOperand(MI.getNumOperands() - 1).getReg
() == X86::EFLAGS) && "Expected last argument to be EFLAGS"
) ? static_cast<void> (0) : __assert_fail ("(MI.getNumOperands() <= 3 || !MI.getOperand(MI.getNumOperands() - 1).isReg() || MI.getOperand(MI.getNumOperands() - 1).getReg() == X86::EFLAGS) && \"Expected last argument to be EFLAGS\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 28974, __PRETTY_FUNCTION__))
;
28975 unsigned MOVOpc = Subtarget.hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
28976 // In the XMM save block, save all the XMM argument registers.
28977 for (int i = 3, e = MI.getNumOperands() - 1; i != e; ++i) {
28978 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
28979 MachineMemOperand *MMO = F->getMachineMemOperand(
28980 MachinePointerInfo::getFixedStack(*F, RegSaveFrameIndex, Offset),
28981 MachineMemOperand::MOStore,
28982 /*Size=*/16, /*Align=*/16);
28983 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
28984 .addFrameIndex(RegSaveFrameIndex)
28985 .addImm(/*Scale=*/1)
28986 .addReg(/*IndexReg=*/0)
28987 .addImm(/*Disp=*/Offset)
28988 .addReg(/*Segment=*/0)
28989 .addReg(MI.getOperand(i).getReg())
28990 .addMemOperand(MMO);
28991 }
28992
28993 MI.eraseFromParent(); // The pseudo instruction is gone now.
28994
28995 return EndMBB;
28996}
28997
28998// The EFLAGS operand of SelectItr might be missing a kill marker
28999// because there were multiple uses of EFLAGS, and ISel didn't know
29000// which to mark. Figure out whether SelectItr should have had a
29001// kill marker, and set it if it should. Returns the correct kill
29002// marker value.
29003static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
29004 MachineBasicBlock* BB,
29005 const TargetRegisterInfo* TRI) {
29006 // Scan forward through BB for a use/def of EFLAGS.
29007 MachineBasicBlock::iterator miI(std::next(SelectItr));
29008 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
29009 const MachineInstr& mi = *miI;
29010 if (mi.readsRegister(X86::EFLAGS))
29011 return false;
29012 if (mi.definesRegister(X86::EFLAGS))
29013 break; // Should have kill-flag - update below.
29014 }
29015
29016 // If we hit the end of the block, check whether EFLAGS is live into a
29017 // successor.
29018 if (miI == BB->end()) {
29019 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
29020 sEnd = BB->succ_end();
29021 sItr != sEnd; ++sItr) {
29022 MachineBasicBlock* succ = *sItr;
29023 if (succ->isLiveIn(X86::EFLAGS))
29024 return false;
29025 }
29026 }
29027
29028 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
29029 // out. SelectMI should have a kill flag on EFLAGS.
29030 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
29031 return true;
29032}
29033
29034// Return true if it is OK for this CMOV pseudo-opcode to be cascaded
29035// together with other CMOV pseudo-opcodes into a single basic-block with
29036// conditional jump around it.
29037static bool isCMOVPseudo(MachineInstr &MI) {
29038 switch (MI.getOpcode()) {
29039 case X86::CMOV_FR32:
29040 case X86::CMOV_FR64:
29041 case X86::CMOV_GR8:
29042 case X86::CMOV_GR16:
29043 case X86::CMOV_GR32:
29044 case X86::CMOV_RFP32:
29045 case X86::CMOV_RFP64:
29046 case X86::CMOV_RFP80:
29047 case X86::CMOV_VR128:
29048 case X86::CMOV_VR128X:
29049 case X86::CMOV_VR256:
29050 case X86::CMOV_VR256X:
29051 case X86::CMOV_VR512:
29052 case X86::CMOV_VK2:
29053 case X86::CMOV_VK4:
29054 case X86::CMOV_VK8:
29055 case X86::CMOV_VK16:
29056 case X86::CMOV_VK32:
29057 case X86::CMOV_VK64:
29058 return true;
29059
29060 default:
29061 return false;
29062 }
29063}
29064
29065// Helper function, which inserts PHI functions into SinkMBB:
29066// %Result(i) = phi [ %FalseValue(i), FalseMBB ], [ %TrueValue(i), TrueMBB ],
29067// where %FalseValue(i) and %TrueValue(i) are taken from the consequent CMOVs
29068// in [MIItBegin, MIItEnd) range. It returns the last MachineInstrBuilder for
29069// the last PHI function inserted.
29070static MachineInstrBuilder createPHIsForCMOVsInSinkBB(
29071 MachineBasicBlock::iterator MIItBegin, MachineBasicBlock::iterator MIItEnd,
29072 MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB,
29073 MachineBasicBlock *SinkMBB) {
29074 MachineFunction *MF = TrueMBB->getParent();
29075 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
29076 DebugLoc DL = MIItBegin->getDebugLoc();
29077
29078 X86::CondCode CC = X86::CondCode(MIItBegin->getOperand(3).getImm());
29079 X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
29080
29081 MachineBasicBlock::iterator SinkInsertionPoint = SinkMBB->begin();
29082
29083 // As we are creating the PHIs, we have to be careful if there is more than
29084 // one. Later CMOVs may reference the results of earlier CMOVs, but later
29085 // PHIs have to reference the individual true/false inputs from earlier PHIs.
29086 // That also means that PHI construction must work forward from earlier to
29087 // later, and that the code must maintain a mapping from earlier PHI's
29088 // destination registers, and the registers that went into the PHI.
29089 DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
29090 MachineInstrBuilder MIB;
29091
29092 for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
29093 unsigned DestReg = MIIt->getOperand(0).getReg();
29094 unsigned Op1Reg = MIIt->getOperand(1).getReg();
29095 unsigned Op2Reg = MIIt->getOperand(2).getReg();
29096
29097 // If this CMOV we are generating is the opposite condition from
29098 // the jump we generated, then we have to swap the operands for the
29099 // PHI that is going to be generated.
29100 if (MIIt->getOperand(3).getImm() == OppCC)
29101 std::swap(Op1Reg, Op2Reg);
29102
29103 if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
29104 Op1Reg = RegRewriteTable[Op1Reg].first;
29105
29106 if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
29107 Op2Reg = RegRewriteTable[Op2Reg].second;
29108
29109 MIB = BuildMI(*SinkMBB, SinkInsertionPoint, DL, TII->get(X86::PHI), DestReg)
29110 .addReg(Op1Reg)
29111 .addMBB(FalseMBB)
29112 .addReg(Op2Reg)
29113 .addMBB(TrueMBB);
29114
29115 // Add this PHI to the rewrite table.
29116 RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
29117 }
29118
29119 return MIB;
29120}
29121
29122// Lower cascaded selects in form of (SecondCmov (FirstCMOV F, T, cc1), T, cc2).
29123MachineBasicBlock *
29124X86TargetLowering::EmitLoweredCascadedSelect(MachineInstr &FirstCMOV,
29125 MachineInstr &SecondCascadedCMOV,
29126 MachineBasicBlock *ThisMBB) const {
29127 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
29128 DebugLoc DL = FirstCMOV.getDebugLoc();
29129
29130 // We lower cascaded CMOVs such as
29131 //
29132 // (SecondCascadedCMOV (FirstCMOV F, T, cc1), T, cc2)
29133 //
29134 // to two successive branches.
29135 //
29136 // Without this, we would add a PHI between the two jumps, which ends up
29137 // creating a few copies all around. For instance, for
29138 //
29139 // (sitofp (zext (fcmp une)))
29140 //
29141 // we would generate:
29142 //
29143 // ucomiss %xmm1, %xmm0
29144 // movss <1.0f>, %xmm0
29145 // movaps %xmm0, %xmm1
29146 // jne .LBB5_2
29147 // xorps %xmm1, %xmm1
29148 // .LBB5_2:
29149 // jp .LBB5_4
29150 // movaps %xmm1, %xmm0
29151 // .LBB5_4:
29152 // retq
29153 //
29154 // because this custom-inserter would have generated:
29155 //
29156 // A
29157 // | \
29158 // | B
29159 // | /
29160 // C
29161 // | \
29162 // | D
29163 // | /
29164 // E
29165 //
29166 // A: X = ...; Y = ...
29167 // B: empty
29168 // C: Z = PHI [X, A], [Y, B]
29169 // D: empty
29170 // E: PHI [X, C], [Z, D]
29171 //
29172 // If we lower both CMOVs in a single step, we can instead generate:
29173 //
29174 // A
29175 // | \
29176 // | C
29177 // | /|
29178 // |/ |
29179 // | |
29180 // | D
29181 // | /
29182 // E
29183 //
29184 // A: X = ...; Y = ...
29185 // D: empty
29186 // E: PHI [X, A], [X, C], [Y, D]
29187 //
29188 // Which, in our sitofp/fcmp example, gives us something like:
29189 //
29190 // ucomiss %xmm1, %xmm0
29191 // movss <1.0f>, %xmm0
29192 // jne .LBB5_4
29193 // jp .LBB5_4
29194 // xorps %xmm0, %xmm0
29195 // .LBB5_4:
29196 // retq
29197 //
29198
29199 // We lower cascaded CMOV into two successive branches to the same block.
29200 // EFLAGS is used by both, so mark it as live in the second.
29201 const BasicBlock *LLVM_BB = ThisMBB->getBasicBlock();
29202 MachineFunction *F = ThisMBB->getParent();
29203 MachineBasicBlock *FirstInsertedMBB = F->CreateMachineBasicBlock(LLVM_BB);
29204 MachineBasicBlock *SecondInsertedMBB = F->CreateMachineBasicBlock(LLVM_BB);
29205 MachineBasicBlock *SinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
29206
29207 MachineFunction::iterator It = ++ThisMBB->getIterator();
29208 F->insert(It, FirstInsertedMBB);
29209 F->insert(It, SecondInsertedMBB);
29210 F->insert(It, SinkMBB);
29211
29212 // For a cascaded CMOV, we lower it to two successive branches to
29213 // the same block (SinkMBB). EFLAGS is used by both, so mark it as live in
29214 // the FirstInsertedMBB.
29215 FirstInsertedMBB->addLiveIn(X86::EFLAGS);
29216
29217 // If the EFLAGS register isn't dead in the terminator, then claim that it's
29218 // live into the sink and copy blocks.
29219 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
29220 if (!SecondCascadedCMOV.killsRegister(X86::EFLAGS) &&
29221 !checkAndUpdateEFLAGSKill(SecondCascadedCMOV, ThisMBB, TRI)) {
29222 SecondInsertedMBB->addLiveIn(X86::EFLAGS);
29223 SinkMBB->addLiveIn(X86::EFLAGS);
29224 }
29225
29226 // Transfer the remainder of ThisMBB and its successor edges to SinkMBB.
29227 SinkMBB->splice(SinkMBB->begin(), ThisMBB,
29228 std::next(MachineBasicBlock::iterator(FirstCMOV)),
29229 ThisMBB->end());
29230 SinkMBB->transferSuccessorsAndUpdatePHIs(ThisMBB);
29231
29232 // Fallthrough block for ThisMBB.
29233 ThisMBB->addSuccessor(FirstInsertedMBB);
29234 // The true block target of the first branch is always SinkMBB.
29235 ThisMBB->addSuccessor(SinkMBB);
29236 // Fallthrough block for FirstInsertedMBB.
29237 FirstInsertedMBB->addSuccessor(SecondInsertedMBB);
29238 // The true block for the branch of FirstInsertedMBB.
29239 FirstInsertedMBB->addSuccessor(SinkMBB);
29240 // This is fallthrough.
29241 SecondInsertedMBB->addSuccessor(SinkMBB);
29242
29243 // Create the conditional branch instructions.
29244 X86::CondCode FirstCC = X86::CondCode(FirstCMOV.getOperand(3).getImm());
29245 BuildMI(ThisMBB, DL, TII->get(X86::JCC_1)).addMBB(SinkMBB).addImm(FirstCC);
29246
29247 X86::CondCode SecondCC =
29248 X86::CondCode(SecondCascadedCMOV.getOperand(3).getImm());
29249 BuildMI(FirstInsertedMBB, DL, TII->get(X86::JCC_1)).addMBB(SinkMBB).addImm(SecondCC);
29250
29251 // SinkMBB:
29252 // %Result = phi [ %FalseValue, SecondInsertedMBB ], [ %TrueValue, ThisMBB ]
29253 unsigned DestReg = FirstCMOV.getOperand(0).getReg();
29254 unsigned Op1Reg = FirstCMOV.getOperand(1).getReg();
29255 unsigned Op2Reg = FirstCMOV.getOperand(2).getReg();
29256 MachineInstrBuilder MIB =
29257 BuildMI(*SinkMBB, SinkMBB->begin(), DL, TII->get(X86::PHI), DestReg)
29258 .addReg(Op1Reg)
29259 .addMBB(SecondInsertedMBB)
29260 .addReg(Op2Reg)
29261 .addMBB(ThisMBB);
29262
29263 // The second SecondInsertedMBB provides the same incoming value as the
29264 // FirstInsertedMBB (the True operand of the SELECT_CC/CMOV nodes).
29265 MIB.addReg(FirstCMOV.getOperand(2).getReg()).addMBB(FirstInsertedMBB);
29266 // Copy the PHI result to the register defined by the second CMOV.
29267 BuildMI(*SinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())), DL,
29268 TII->get(TargetOpcode::COPY),
29269 SecondCascadedCMOV.getOperand(0).getReg())
29270 .addReg(FirstCMOV.getOperand(0).getReg());
29271
29272 // Now remove the CMOVs.
29273 FirstCMOV.eraseFromParent();
29274 SecondCascadedCMOV.eraseFromParent();
29275
29276 return SinkMBB;
29277}
29278
29279MachineBasicBlock *
29280X86TargetLowering::EmitLoweredSelect(MachineInstr &MI,
29281 MachineBasicBlock *ThisMBB) const {
29282 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
29283 DebugLoc DL = MI.getDebugLoc();
29284
29285 // To "insert" a SELECT_CC instruction, we actually have to insert the
29286 // diamond control-flow pattern. The incoming instruction knows the
29287 // destination vreg to set, the condition code register to branch on, the
29288 // true/false values to select between and a branch opcode to use.
29289
29290 // ThisMBB:
29291 // ...
29292 // TrueVal = ...
29293 // cmpTY ccX, r1, r2
29294 // bCC copy1MBB
29295 // fallthrough --> FalseMBB
29296
29297 // This code lowers all pseudo-CMOV instructions. Generally it lowers these
29298 // as described above, by inserting a BB, and then making a PHI at the join
29299 // point to select the true and false operands of the CMOV in the PHI.
29300 //
29301 // The code also handles two different cases of multiple CMOV opcodes
29302 // in a row.
29303 //
29304 // Case 1:
29305 // In this case, there are multiple CMOVs in a row, all which are based on
29306 // the same condition setting (or the exact opposite condition setting).
29307 // In this case we can lower all the CMOVs using a single inserted BB, and
29308 // then make a number of PHIs at the join point to model the CMOVs. The only
29309 // trickiness here, is that in a case like:
29310 //
29311 // t2 = CMOV cond1 t1, f1
29312 // t3 = CMOV cond1 t2, f2
29313 //
29314 // when rewriting this into PHIs, we have to perform some renaming on the
29315 // temps since you cannot have a PHI operand refer to a PHI result earlier
29316 // in the same block. The "simple" but wrong lowering would be:
29317 //
29318 // t2 = PHI t1(BB1), f1(BB2)
29319 // t3 = PHI t2(BB1), f2(BB2)
29320 //
29321 // but clearly t2 is not defined in BB1, so that is incorrect. The proper
29322 // renaming is to note that on the path through BB1, t2 is really just a
29323 // copy of t1, and do that renaming, properly generating:
29324 //
29325 // t2 = PHI t1(BB1), f1(BB2)
29326 // t3 = PHI t1(BB1), f2(BB2)
29327 //
29328 // Case 2:
29329 // CMOV ((CMOV F, T, cc1), T, cc2) is checked here and handled by a separate
29330 // function - EmitLoweredCascadedSelect.
29331
29332 X86::CondCode CC = X86::CondCode(MI.getOperand(3).getImm());
29333 X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
29334 MachineInstr *LastCMOV = &MI;
29335 MachineBasicBlock::iterator NextMIIt = MachineBasicBlock::iterator(MI);
29336
29337 // Check for case 1, where there are multiple CMOVs with the same condition
29338 // first. Of the two cases of multiple CMOV lowerings, case 1 reduces the
29339 // number of jumps the most.
29340
29341 if (isCMOVPseudo(MI)) {
29342 // See if we have a string of CMOVS with the same condition. Skip over
29343 // intervening debug insts.
29344 while (NextMIIt != ThisMBB->end() && isCMOVPseudo(*NextMIIt) &&
29345 (NextMIIt->getOperand(3).getImm() == CC ||
29346 NextMIIt->getOperand(3).getImm() == OppCC)) {
29347 LastCMOV = &*NextMIIt;
29348 ++NextMIIt;
29349 NextMIIt = skipDebugInstructionsForward(NextMIIt, ThisMBB->end());
29350 }
29351 }
29352
29353 // This checks for case 2, but only do this if we didn't already find
29354 // case 1, as indicated by LastCMOV == MI.
29355 if (LastCMOV == &MI && NextMIIt != ThisMBB->end() &&
29356 NextMIIt->getOpcode() == MI.getOpcode() &&
29357 NextMIIt->getOperand(2).getReg() == MI.getOperand(2).getReg() &&
29358 NextMIIt->getOperand(1).getReg() == MI.getOperand(0).getReg() &&
29359 NextMIIt->getOperand(1).isKill()) {
29360 return EmitLoweredCascadedSelect(MI, *NextMIIt, ThisMBB);
29361 }
29362
29363 const BasicBlock *LLVM_BB = ThisMBB->getBasicBlock();
29364 MachineFunction *F = ThisMBB->getParent();
29365 MachineBasicBlock *FalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
29366 MachineBasicBlock *SinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
29367
29368 MachineFunction::iterator It = ++ThisMBB->getIterator();
29369 F->insert(It, FalseMBB);
29370 F->insert(It, SinkMBB);
29371
29372 // If the EFLAGS register isn't dead in the terminator, then claim that it's
29373 // live into the sink and copy blocks.
29374 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
29375 if (!LastCMOV->killsRegister(X86::EFLAGS) &&
29376 !checkAndUpdateEFLAGSKill(LastCMOV, ThisMBB, TRI)) {
29377 FalseMBB->addLiveIn(X86::EFLAGS);
29378 SinkMBB->addLiveIn(X86::EFLAGS);
29379 }
29380
29381 // Transfer any debug instructions inside the CMOV sequence to the sunk block.
29382 auto DbgEnd = MachineBasicBlock::iterator(LastCMOV);
29383 auto DbgIt = MachineBasicBlock::iterator(MI);
29384 while (DbgIt != DbgEnd) {
29385 auto Next = std::next(DbgIt);
29386 if (DbgIt->isDebugInstr())
29387 SinkMBB->push_back(DbgIt->removeFromParent());
29388 DbgIt = Next;
29389 }
29390
29391 // Transfer the remainder of ThisMBB and its successor edges to SinkMBB.
29392 SinkMBB->splice(SinkMBB->end(), ThisMBB,
29393 std::next(MachineBasicBlock::iterator(LastCMOV)),
29394 ThisMBB->end());
29395 SinkMBB->transferSuccessorsAndUpdatePHIs(ThisMBB);
29396
29397 // Fallthrough block for ThisMBB.
29398 ThisMBB->addSuccessor(FalseMBB);
29399 // The true block target of the first (or only) branch is always a SinkMBB.
29400 ThisMBB->addSuccessor(SinkMBB);
29401 // Fallthrough block for FalseMBB.
29402 FalseMBB->addSuccessor(SinkMBB);
29403
29404 // Create the conditional branch instruction.
29405 BuildMI(ThisMBB, DL, TII->get(X86::JCC_1)).addMBB(SinkMBB).addImm(CC);
29406
29407 // SinkMBB:
29408 // %Result = phi [ %FalseValue, FalseMBB ], [ %TrueValue, ThisMBB ]
29409 // ...
29410 MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
29411 MachineBasicBlock::iterator MIItEnd =
29412 std::next(MachineBasicBlock::iterator(LastCMOV));
29413 createPHIsForCMOVsInSinkBB(MIItBegin, MIItEnd, ThisMBB, FalseMBB, SinkMBB);
29414
29415 // Now remove the CMOV(s).
29416 ThisMBB->erase(MIItBegin, MIItEnd);
29417
29418 return SinkMBB;
29419}
29420
29421MachineBasicBlock *
29422X86TargetLowering::EmitLoweredSegAlloca(MachineInstr &MI,
29423 MachineBasicBlock *BB) const {
29424 MachineFunction *MF = BB->getParent();
29425 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
29426 DebugLoc DL = MI.getDebugLoc();
29427 const BasicBlock *LLVM_BB = BB->getBasicBlock();
29428
29429 assert(MF->shouldSplitStack())((MF->shouldSplitStack()) ? static_cast<void> (0) : __assert_fail
("MF->shouldSplitStack()", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 29429, __PRETTY_FUNCTION__))
;
29430
29431 const bool Is64Bit = Subtarget.is64Bit();
29432 const bool IsLP64 = Subtarget.isTarget64BitLP64();
29433
29434 const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
29435 const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
29436
29437 // BB:
29438 // ... [Till the alloca]
29439 // If stacklet is not large enough, jump to mallocMBB
29440 //
29441 // bumpMBB:
29442 // Allocate by subtracting from RSP
29443 // Jump to continueMBB
29444 //
29445 // mallocMBB:
29446 // Allocate by call to runtime
29447 //
29448 // continueMBB:
29449 // ...
29450 // [rest of original BB]
29451 //
29452
29453 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
29454 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
29455 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
29456
29457 MachineRegisterInfo &MRI = MF->getRegInfo();
29458 const TargetRegisterClass *AddrRegClass =
29459 getRegClassFor(getPointerTy(MF->getDataLayout()));
29460
29461 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
29462 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
29463 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
29464 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
29465 sizeVReg = MI.getOperand(1).getReg(),
29466 physSPReg =
29467 IsLP64 || Subtarget.isTargetNaCl64() ? X86::RSP : X86::ESP;
29468
29469 MachineFunction::iterator MBBIter = ++BB->getIterator();
29470
29471 MF->insert(MBBIter, bumpMBB);
29472 MF->insert(MBBIter, mallocMBB);
29473 MF->insert(MBBIter, continueMBB);
29474
29475 continueMBB->splice(continueMBB->begin(), BB,
29476 std::next(MachineBasicBlock::iterator(MI)), BB->end());
29477 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
29478
29479 // Add code to the main basic block to check if the stack limit has been hit,
29480 // and if so, jump to mallocMBB otherwise to bumpMBB.
29481 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
29482 BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
29483 .addReg(tmpSPVReg).addReg(sizeVReg);
29484 BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
29485 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
29486 .addReg(SPLimitVReg);
29487 BuildMI(BB, DL, TII->get(X86::JCC_1)).addMBB(mallocMBB).addImm(X86::COND_G);
29488
29489 // bumpMBB simply decreases the stack pointer, since we know the current
29490 // stacklet has enough space.
29491 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
29492 .addReg(SPLimitVReg);
29493 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
29494 .addReg(SPLimitVReg);
29495 BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
29496
29497 // Calls into a routine in libgcc to allocate more space from the heap.
29498 const uint32_t *RegMask =
29499 Subtarget.getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
29500 if (IsLP64) {
29501 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
29502 .addReg(sizeVReg);
29503 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
29504 .addExternalSymbol("__morestack_allocate_stack_space")
29505 .addRegMask(RegMask)
29506 .addReg(X86::RDI, RegState::Implicit)
29507 .addReg(X86::RAX, RegState::ImplicitDefine);
29508 } else if (Is64Bit) {
29509 BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
29510 .addReg(sizeVReg);
29511 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
29512 .addExternalSymbol("__morestack_allocate_stack_space")
29513 .addRegMask(RegMask)
29514 .addReg(X86::EDI, RegState::Implicit)
29515 .addReg(X86::EAX, RegState::ImplicitDefine);
29516 } else {
29517 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
29518 .addImm(12);
29519 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
29520 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
29521 .addExternalSymbol("__morestack_allocate_stack_space")
29522 .addRegMask(RegMask)
29523 .addReg(X86::EAX, RegState::ImplicitDefine);
29524 }
29525
29526 if (!Is64Bit)
29527 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
29528 .addImm(16);
29529
29530 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
29531 .addReg(IsLP64 ? X86::RAX : X86::EAX);
29532 BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
29533
29534 // Set up the CFG correctly.
29535 BB->addSuccessor(bumpMBB);
29536 BB->addSuccessor(mallocMBB);
29537 mallocMBB->addSuccessor(continueMBB);
29538 bumpMBB->addSuccessor(continueMBB);
29539
29540 // Take care of the PHI nodes.
29541 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
29542 MI.getOperand(0).getReg())
29543 .addReg(mallocPtrVReg)
29544 .addMBB(mallocMBB)
29545 .addReg(bumpSPPtrVReg)
29546 .addMBB(bumpMBB);
29547
29548 // Delete the original pseudo instruction.
29549 MI.eraseFromParent();
29550
29551 // And we're done.
29552 return continueMBB;
29553}
29554
29555MachineBasicBlock *
29556X86TargetLowering::EmitLoweredCatchRet(MachineInstr &MI,
29557 MachineBasicBlock *BB) const {
29558 MachineFunction *MF = BB->getParent();
29559 const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
29560 MachineBasicBlock *TargetMBB = MI.getOperand(0).getMBB();
29561 DebugLoc DL = MI.getDebugLoc();
29562
29563 assert(!isAsynchronousEHPersonality(((!isAsynchronousEHPersonality( classifyEHPersonality(MF->
getFunction().getPersonalityFn())) && "SEH does not use catchret!"
) ? static_cast<void> (0) : __assert_fail ("!isAsynchronousEHPersonality( classifyEHPersonality(MF->getFunction().getPersonalityFn())) && \"SEH does not use catchret!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 29565, __PRETTY_FUNCTION__))
29564 classifyEHPersonality(MF->getFunction().getPersonalityFn())) &&((!isAsynchronousEHPersonality( classifyEHPersonality(MF->
getFunction().getPersonalityFn())) && "SEH does not use catchret!"
) ? static_cast<void> (0) : __assert_fail ("!isAsynchronousEHPersonality( classifyEHPersonality(MF->getFunction().getPersonalityFn())) && \"SEH does not use catchret!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 29565, __PRETTY_FUNCTION__))
29565 "SEH does not use catchret!")((!isAsynchronousEHPersonality( classifyEHPersonality(MF->
getFunction().getPersonalityFn())) && "SEH does not use catchret!"
) ? static_cast<void> (0) : __assert_fail ("!isAsynchronousEHPersonality( classifyEHPersonality(MF->getFunction().getPersonalityFn())) && \"SEH does not use catchret!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 29565, __PRETTY_FUNCTION__))
;
29566
29567 // Only 32-bit EH needs to worry about manually restoring stack pointers.
29568 if (!Subtarget.is32Bit())
29569 return BB;
29570
29571 // C++ EH creates a new target block to hold the restore code, and wires up
29572 // the new block to the return destination with a normal JMP_4.
29573 MachineBasicBlock *RestoreMBB =
29574 MF->CreateMachineBasicBlock(BB->getBasicBlock());
29575 assert(BB->succ_size() == 1)((BB->succ_size() == 1) ? static_cast<void> (0) : __assert_fail
("BB->succ_size() == 1", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 29575, __PRETTY_FUNCTION__))
;
29576 MF->insert(std::next(BB->getIterator()), RestoreMBB);
29577 RestoreMBB->transferSuccessorsAndUpdatePHIs(BB);
29578 BB->addSuccessor(RestoreMBB);
29579 MI.getOperand(0).setMBB(RestoreMBB);
29580
29581 auto RestoreMBBI = RestoreMBB->begin();
29582 BuildMI(*RestoreMBB, RestoreMBBI, DL, TII.get(X86::EH_RESTORE));
29583 BuildMI(*RestoreMBB, RestoreMBBI, DL, TII.get(X86::JMP_4)).addMBB(TargetMBB);
29584 return BB;
29585}
29586
29587MachineBasicBlock *
29588X86TargetLowering::EmitLoweredCatchPad(MachineInstr &MI,
29589 MachineBasicBlock *BB) const {
29590 MachineFunction *MF = BB->getParent();
29591 const Constant *PerFn = MF->getFunction().getPersonalityFn();
29592 bool IsSEH = isAsynchronousEHPersonality(classifyEHPersonality(PerFn));
29593 // Only 32-bit SEH requires special handling for catchpad.
29594 if (IsSEH && Subtarget.is32Bit()) {
29595 const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
29596 DebugLoc DL = MI.getDebugLoc();
29597 BuildMI(*BB, MI, DL, TII.get(X86::EH_RESTORE));
29598 }
29599 MI.eraseFromParent();
29600 return BB;
29601}
29602
29603MachineBasicBlock *
29604X86TargetLowering::EmitLoweredTLSAddr(MachineInstr &MI,
29605 MachineBasicBlock *BB) const {
29606 // So, here we replace TLSADDR with the sequence:
29607 // adjust_stackdown -> TLSADDR -> adjust_stackup.
29608 // We need this because TLSADDR is lowered into calls
29609 // inside MC, therefore without the two markers shrink-wrapping
29610 // may push the prologue/epilogue pass them.
29611 const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
29612 DebugLoc DL = MI.getDebugLoc();
29613 MachineFunction &MF = *BB->getParent();
29614
29615 // Emit CALLSEQ_START right before the instruction.
29616 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
29617 MachineInstrBuilder CallseqStart =
29618 BuildMI(MF, DL, TII.get(AdjStackDown)).addImm(0).addImm(0).addImm(0);
29619 BB->insert(MachineBasicBlock::iterator(MI), CallseqStart);
29620
29621 // Emit CALLSEQ_END right after the instruction.
29622 // We don't call erase from parent because we want to keep the
29623 // original instruction around.
29624 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
29625 MachineInstrBuilder CallseqEnd =
29626 BuildMI(MF, DL, TII.get(AdjStackUp)).addImm(0).addImm(0);
29627 BB->insertAfter(MachineBasicBlock::iterator(MI), CallseqEnd);
29628
29629 return BB;
29630}
29631
29632MachineBasicBlock *
29633X86TargetLowering::EmitLoweredTLSCall(MachineInstr &MI,
29634 MachineBasicBlock *BB) const {
29635 // This is pretty easy. We're taking the value that we received from
29636 // our load from the relocation, sticking it in either RDI (x86-64)
29637 // or EAX and doing an indirect call. The return value will then
29638 // be in the normal return register.
29639 MachineFunction *F = BB->getParent();
29640 const X86InstrInfo *TII = Subtarget.getInstrInfo();
29641 DebugLoc DL = MI.getDebugLoc();
29642
29643 assert(Subtarget.isTargetDarwin() && "Darwin only instr emitted?")((Subtarget.isTargetDarwin() && "Darwin only instr emitted?"
) ? static_cast<void> (0) : __assert_fail ("Subtarget.isTargetDarwin() && \"Darwin only instr emitted?\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 29643, __PRETTY_FUNCTION__))
;
29644 assert(MI.getOperand(3).isGlobal() && "This should be a global")((MI.getOperand(3).isGlobal() && "This should be a global"
) ? static_cast<void> (0) : __assert_fail ("MI.getOperand(3).isGlobal() && \"This should be a global\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 29644, __PRETTY_FUNCTION__))
;
29645
29646 // Get a register mask for the lowered call.
29647 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
29648 // proper register mask.
29649 const uint32_t *RegMask =
29650 Subtarget.is64Bit() ?
29651 Subtarget.getRegisterInfo()->getDarwinTLSCallPreservedMask() :
29652 Subtarget.getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
29653 if (Subtarget.is64Bit()) {
29654 MachineInstrBuilder MIB =
29655 BuildMI(*BB, MI, DL, TII->get(X86::MOV64rm), X86::RDI)
29656 .addReg(X86::RIP)
29657 .addImm(0)
29658 .addReg(0)
29659 .addGlobalAddress(MI.getOperand(3).getGlobal(), 0,
29660 MI.getOperand(3).getTargetFlags())
29661 .addReg(0);
29662 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
29663 addDirectMem(MIB, X86::RDI);
29664 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
29665 } else if (!isPositionIndependent()) {
29666 MachineInstrBuilder MIB =
29667 BuildMI(*BB, MI, DL, TII->get(X86::MOV32rm), X86::EAX)
29668 .addReg(0)
29669 .addImm(0)
29670 .addReg(0)
29671 .addGlobalAddress(MI.getOperand(3).getGlobal(), 0,
29672 MI.getOperand(3).getTargetFlags())
29673 .addReg(0);
29674 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
29675 addDirectMem(MIB, X86::EAX);
29676 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
29677 } else {
29678 MachineInstrBuilder MIB =
29679 BuildMI(*BB, MI, DL, TII->get(X86::MOV32rm), X86::EAX)
29680 .addReg(TII->getGlobalBaseReg(F))
29681 .addImm(0)
29682 .addReg(0)
29683 .addGlobalAddress(MI.getOperand(3).getGlobal(), 0,
29684 MI.getOperand(3).getTargetFlags())
29685 .addReg(0);
29686 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
29687 addDirectMem(MIB, X86::EAX);
29688 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
29689 }
29690
29691 MI.eraseFromParent(); // The pseudo instruction is gone now.
29692 return BB;
29693}
29694
29695static unsigned getOpcodeForRetpoline(unsigned RPOpc) {
29696 switch (RPOpc) {
29697 case X86::RETPOLINE_CALL32:
29698 return X86::CALLpcrel32;
29699 case X86::RETPOLINE_CALL64:
29700 return X86::CALL64pcrel32;
29701 case X86::RETPOLINE_TCRETURN32:
29702 return X86::TCRETURNdi;
29703 case X86::RETPOLINE_TCRETURN64:
29704 return X86::TCRETURNdi64;
29705 }
29706 llvm_unreachable("not retpoline opcode")::llvm::llvm_unreachable_internal("not retpoline opcode", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 29706)
;
29707}
29708
29709static const char *getRetpolineSymbol(const X86Subtarget &Subtarget,
29710 unsigned Reg) {
29711 if (Subtarget.useRetpolineExternalThunk()) {
29712 // When using an external thunk for retpolines, we pick names that match the
29713 // names GCC happens to use as well. This helps simplify the implementation
29714 // of the thunks for kernels where they have no easy ability to create
29715 // aliases and are doing non-trivial configuration of the thunk's body. For
29716 // example, the Linux kernel will do boot-time hot patching of the thunk
29717 // bodies and cannot easily export aliases of these to loaded modules.
29718 //
29719 // Note that at any point in the future, we may need to change the semantics
29720 // of how we implement retpolines and at that time will likely change the
29721 // name of the called thunk. Essentially, there is no hard guarantee that
29722 // LLVM will generate calls to specific thunks, we merely make a best-effort
29723 // attempt to help out kernels and other systems where duplicating the
29724 // thunks is costly.
29725 switch (Reg) {
29726 case X86::EAX:
29727 assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!")((!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!"
) ? static_cast<void> (0) : __assert_fail ("!Subtarget.is64Bit() && \"Should not be using a 32-bit thunk!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 29727, __PRETTY_FUNCTION__))
;
29728 return "__x86_indirect_thunk_eax";
29729 case X86::ECX:
29730 assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!")((!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!"
) ? static_cast<void> (0) : __assert_fail ("!Subtarget.is64Bit() && \"Should not be using a 32-bit thunk!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 29730, __PRETTY_FUNCTION__))
;
29731 return "__x86_indirect_thunk_ecx";
29732 case X86::EDX:
29733 assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!")((!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!"
) ? static_cast<void> (0) : __assert_fail ("!Subtarget.is64Bit() && \"Should not be using a 32-bit thunk!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 29733, __PRETTY_FUNCTION__))
;
29734 return "__x86_indirect_thunk_edx";
29735 case X86::EDI:
29736 assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!")((!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!"
) ? static_cast<void> (0) : __assert_fail ("!Subtarget.is64Bit() && \"Should not be using a 32-bit thunk!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 29736, __PRETTY_FUNCTION__))
;
29737 return "__x86_indirect_thunk_edi";
29738 case X86::R11:
29739 assert(Subtarget.is64Bit() && "Should not be using a 64-bit thunk!")((Subtarget.is64Bit() && "Should not be using a 64-bit thunk!"
) ? static_cast<void> (0) : __assert_fail ("Subtarget.is64Bit() && \"Should not be using a 64-bit thunk!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 29739, __PRETTY_FUNCTION__))
;
29740 return "__x86_indirect_thunk_r11";
29741 }
29742 llvm_unreachable("unexpected reg for retpoline")::llvm::llvm_unreachable_internal("unexpected reg for retpoline"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 29742)
;
29743 }
29744
29745 // When targeting an internal COMDAT thunk use an LLVM-specific name.
29746 switch (Reg) {
29747 case X86::EAX:
29748 assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!")((!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!"
) ? static_cast<void> (0) : __assert_fail ("!Subtarget.is64Bit() && \"Should not be using a 32-bit thunk!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 29748, __PRETTY_FUNCTION__))
;
29749 return "__llvm_retpoline_eax";
29750 case X86::ECX:
29751 assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!")((!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!"
) ? static_cast<void> (0) : __assert_fail ("!Subtarget.is64Bit() && \"Should not be using a 32-bit thunk!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 29751, __PRETTY_FUNCTION__))
;
29752 return "__llvm_retpoline_ecx";
29753 case X86::EDX:
29754 assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!")((!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!"
) ? static_cast<void> (0) : __assert_fail ("!Subtarget.is64Bit() && \"Should not be using a 32-bit thunk!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 29754, __PRETTY_FUNCTION__))
;
29755 return "__llvm_retpoline_edx";
29756 case X86::EDI:
29757 assert(!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!")((!Subtarget.is64Bit() && "Should not be using a 32-bit thunk!"
) ? static_cast<void> (0) : __assert_fail ("!Subtarget.is64Bit() && \"Should not be using a 32-bit thunk!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 29757, __PRETTY_FUNCTION__))
;
29758 return "__llvm_retpoline_edi";
29759 case X86::R11:
29760 assert(Subtarget.is64Bit() && "Should not be using a 64-bit thunk!")((Subtarget.is64Bit() && "Should not be using a 64-bit thunk!"
) ? static_cast<void> (0) : __assert_fail ("Subtarget.is64Bit() && \"Should not be using a 64-bit thunk!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 29760, __PRETTY_FUNCTION__))
;
29761 return "__llvm_retpoline_r11";
29762 }
29763 llvm_unreachable("unexpected reg for retpoline")::llvm::llvm_unreachable_internal("unexpected reg for retpoline"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 29763)
;
29764}
29765
29766MachineBasicBlock *
29767X86TargetLowering::EmitLoweredRetpoline(MachineInstr &MI,
29768 MachineBasicBlock *BB) const {
29769 // Copy the virtual register into the R11 physical register and
29770 // call the retpoline thunk.
29771 DebugLoc DL = MI.getDebugLoc();
29772 const X86InstrInfo *TII = Subtarget.getInstrInfo();
29773 unsigned CalleeVReg = MI.getOperand(0).getReg();
29774 unsigned Opc = getOpcodeForRetpoline(MI.getOpcode());
29775
29776 // Find an available scratch register to hold the callee. On 64-bit, we can
29777 // just use R11, but we scan for uses anyway to ensure we don't generate
29778 // incorrect code. On 32-bit, we use one of EAX, ECX, or EDX that isn't
29779 // already a register use operand to the call to hold the callee. If none
29780 // are available, use EDI instead. EDI is chosen because EBX is the PIC base
29781 // register and ESI is the base pointer to realigned stack frames with VLAs.
29782 SmallVector<unsigned, 3> AvailableRegs;
29783 if (Subtarget.is64Bit())
29784 AvailableRegs.push_back(X86::R11);
29785 else
29786 AvailableRegs.append({X86::EAX, X86::ECX, X86::EDX, X86::EDI});
29787
29788 // Zero out any registers that are already used.
29789 for (const auto &MO : MI.operands()) {
29790 if (MO.isReg() && MO.isUse())
29791 for (unsigned &Reg : AvailableRegs)
29792 if (Reg == MO.getReg())
29793 Reg = 0;
29794 }
29795
29796 // Choose the first remaining non-zero available register.
29797 unsigned AvailableReg = 0;
29798 for (unsigned MaybeReg : AvailableRegs) {
29799 if (MaybeReg) {
29800 AvailableReg = MaybeReg;
29801 break;
29802 }
29803 }
29804 if (!AvailableReg)
29805 report_fatal_error("calling convention incompatible with retpoline, no "
29806 "available registers");
29807
29808 const char *Symbol = getRetpolineSymbol(Subtarget, AvailableReg);
29809
29810 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY), AvailableReg)
29811 .addReg(CalleeVReg);
29812 MI.getOperand(0).ChangeToES(Symbol);
29813 MI.setDesc(TII->get(Opc));
29814 MachineInstrBuilder(*BB->getParent(), &MI)
29815 .addReg(AvailableReg, RegState::Implicit | RegState::Kill);
29816 return BB;
29817}
29818
29819/// SetJmp implies future control flow change upon calling the corresponding
29820/// LongJmp.
29821/// Instead of using the 'return' instruction, the long jump fixes the stack and
29822/// performs an indirect branch. To do so it uses the registers that were stored
29823/// in the jump buffer (when calling SetJmp).
29824/// In case the shadow stack is enabled we need to fix it as well, because some
29825/// return addresses will be skipped.
29826/// The function will save the SSP for future fixing in the function
29827/// emitLongJmpShadowStackFix.
29828/// \sa emitLongJmpShadowStackFix
29829/// \param [in] MI The temporary Machine Instruction for the builtin.
29830/// \param [in] MBB The Machine Basic Block that will be modified.
29831void X86TargetLowering::emitSetJmpShadowStackFix(MachineInstr &MI,
29832 MachineBasicBlock *MBB) const {
29833 DebugLoc DL = MI.getDebugLoc();
29834 MachineFunction *MF = MBB->getParent();
29835 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
29836 MachineRegisterInfo &MRI = MF->getRegInfo();
29837 MachineInstrBuilder MIB;
29838
29839 // Memory Reference.
29840 SmallVector<MachineMemOperand *, 2> MMOs(MI.memoperands_begin(),
29841 MI.memoperands_end());
29842
29843 // Initialize a register with zero.
29844 MVT PVT = getPointerTy(MF->getDataLayout());
29845 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
29846 unsigned ZReg = MRI.createVirtualRegister(PtrRC);
29847 unsigned XorRROpc = (PVT == MVT::i64) ? X86::XOR64rr : X86::XOR32rr;
29848 BuildMI(*MBB, MI, DL, TII->get(XorRROpc))
29849 .addDef(ZReg)
29850 .addReg(ZReg, RegState::Undef)
29851 .addReg(ZReg, RegState::Undef);
29852
29853 // Read the current SSP Register value to the zeroed register.
29854 unsigned SSPCopyReg = MRI.createVirtualRegister(PtrRC);
29855 unsigned RdsspOpc = (PVT == MVT::i64) ? X86::RDSSPQ : X86::RDSSPD;
29856 BuildMI(*MBB, MI, DL, TII->get(RdsspOpc), SSPCopyReg).addReg(ZReg);
29857
29858 // Write the SSP register value to offset 3 in input memory buffer.
29859 unsigned PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
29860 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrStoreOpc));
29861 const int64_t SSPOffset = 3 * PVT.getStoreSize();
29862 const unsigned MemOpndSlot = 1;
29863 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
29864 if (i == X86::AddrDisp)
29865 MIB.addDisp(MI.getOperand(MemOpndSlot + i), SSPOffset);
29866 else
29867 MIB.add(MI.getOperand(MemOpndSlot + i));
29868 }
29869 MIB.addReg(SSPCopyReg);
29870 MIB.setMemRefs(MMOs);
29871}
29872
29873MachineBasicBlock *
29874X86TargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
29875 MachineBasicBlock *MBB) const {
29876 DebugLoc DL = MI.getDebugLoc();
29877 MachineFunction *MF = MBB->getParent();
29878 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
29879 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
29880 MachineRegisterInfo &MRI = MF->getRegInfo();
29881
29882 const BasicBlock *BB = MBB->getBasicBlock();
29883 MachineFunction::iterator I = ++MBB->getIterator();
29884
29885 // Memory Reference
29886 SmallVector<MachineMemOperand *, 2> MMOs(MI.memoperands_begin(),
29887 MI.memoperands_end());
29888
29889 unsigned DstReg;
29890 unsigned MemOpndSlot = 0;
29891
29892 unsigned CurOp = 0;
29893
29894 DstReg = MI.getOperand(CurOp++).getReg();
29895 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
29896 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!")((TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!"
) ? static_cast<void> (0) : __assert_fail ("TRI->isTypeLegalForClass(*RC, MVT::i32) && \"Invalid destination!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 29896, __PRETTY_FUNCTION__))
;
29897 (void)TRI;
29898 unsigned mainDstReg = MRI.createVirtualRegister(RC);
29899 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
29900
29901 MemOpndSlot = CurOp;
29902
29903 MVT PVT = getPointerTy(MF->getDataLayout());
29904 assert((PVT == MVT::i64 || PVT == MVT::i32) &&(((PVT == MVT::i64 || PVT == MVT::i32) && "Invalid Pointer Size!"
) ? static_cast<void> (0) : __assert_fail ("(PVT == MVT::i64 || PVT == MVT::i32) && \"Invalid Pointer Size!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 29905, __PRETTY_FUNCTION__))
29905 "Invalid Pointer Size!")(((PVT == MVT::i64 || PVT == MVT::i32) && "Invalid Pointer Size!"
) ? static_cast<void> (0) : __assert_fail ("(PVT == MVT::i64 || PVT == MVT::i32) && \"Invalid Pointer Size!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 29905, __PRETTY_FUNCTION__))
;
29906
29907 // For v = setjmp(buf), we generate
29908 //
29909 // thisMBB:
29910 // buf[LabelOffset] = restoreMBB <-- takes address of restoreMBB
29911 // SjLjSetup restoreMBB
29912 //
29913 // mainMBB:
29914 // v_main = 0
29915 //
29916 // sinkMBB:
29917 // v = phi(main, restore)
29918 //
29919 // restoreMBB:
29920 // if base pointer being used, load it from frame
29921 // v_restore = 1
29922
29923 MachineBasicBlock *thisMBB = MBB;
29924 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
29925 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
29926 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
29927 MF->insert(I, mainMBB);
29928 MF->insert(I, sinkMBB);
29929 MF->push_back(restoreMBB);
29930 restoreMBB->setHasAddressTaken();
29931
29932 MachineInstrBuilder MIB;
29933
29934 // Transfer the remainder of BB and its successor edges to sinkMBB.
29935 sinkMBB->splice(sinkMBB->begin(), MBB,
29936 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
29937 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
29938
29939 // thisMBB:
29940 unsigned PtrStoreOpc = 0;
29941 unsigned LabelReg = 0;
29942 const int64_t LabelOffset = 1 * PVT.getStoreSize();
29943 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
29944 !isPositionIndependent();
29945
29946 // Prepare IP either in reg or imm.
29947 if (!UseImmLabel) {
29948 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
29949 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
29950 LabelReg = MRI.createVirtualRegister(PtrRC);
29951 if (Subtarget.is64Bit()) {
29952 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
29953 .addReg(X86::RIP)
29954 .addImm(0)
29955 .addReg(0)
29956 .addMBB(restoreMBB)
29957 .addReg(0);
29958 } else {
29959 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
29960 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
29961 .addReg(XII->getGlobalBaseReg(MF))
29962 .addImm(0)
29963 .addReg(0)
29964 .addMBB(restoreMBB, Subtarget.classifyBlockAddressReference())
29965 .addReg(0);
29966 }
29967 } else
29968 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
29969 // Store IP
29970 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
29971 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
29972 if (i == X86::AddrDisp)
29973 MIB.addDisp(MI.getOperand(MemOpndSlot + i), LabelOffset);
29974 else
29975 MIB.add(MI.getOperand(MemOpndSlot + i));
29976 }
29977 if (!UseImmLabel)
29978 MIB.addReg(LabelReg);
29979 else
29980 MIB.addMBB(restoreMBB);
29981 MIB.setMemRefs(MMOs);
29982
29983 if (MF->getMMI().getModule()->getModuleFlag("cf-protection-return")) {
29984 emitSetJmpShadowStackFix(MI, thisMBB);
29985 }
29986
29987 // Setup
29988 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
29989 .addMBB(restoreMBB);
29990
29991 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
29992 MIB.addRegMask(RegInfo->getNoPreservedMask());
29993 thisMBB->addSuccessor(mainMBB);
29994 thisMBB->addSuccessor(restoreMBB);
29995
29996 // mainMBB:
29997 // EAX = 0
29998 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
29999 mainMBB->addSuccessor(sinkMBB);
30000
30001 // sinkMBB:
30002 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
30003 TII->get(X86::PHI), DstReg)
30004 .addReg(mainDstReg).addMBB(mainMBB)
30005 .addReg(restoreDstReg).addMBB(restoreMBB);
30006
30007 // restoreMBB:
30008 if (RegInfo->hasBasePointer(*MF)) {
30009 const bool Uses64BitFramePtr =
30010 Subtarget.isTarget64BitLP64() || Subtarget.isTargetNaCl64();
30011 X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
30012 X86FI->setRestoreBasePointer(MF);
30013 unsigned FramePtr = RegInfo->getFrameRegister(*MF);
30014 unsigned BasePtr = RegInfo->getBaseRegister();
30015 unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
30016 addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
30017 FramePtr, true, X86FI->getRestoreBasePointerOffset())
30018 .setMIFlag(MachineInstr::FrameSetup);
30019 }
30020 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
30021 BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
30022 restoreMBB->addSuccessor(sinkMBB);
30023
30024 MI.eraseFromParent();
30025 return sinkMBB;
30026}
30027
30028/// Fix the shadow stack using the previously saved SSP pointer.
30029/// \sa emitSetJmpShadowStackFix
30030/// \param [in] MI The temporary Machine Instruction for the builtin.
30031/// \param [in] MBB The Machine Basic Block that will be modified.
30032/// \return The sink MBB that will perform the future indirect branch.
30033MachineBasicBlock *
30034X86TargetLowering::emitLongJmpShadowStackFix(MachineInstr &MI,
30035 MachineBasicBlock *MBB) const {
30036 DebugLoc DL = MI.getDebugLoc();
30037 MachineFunction *MF = MBB->getParent();
30038 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
30039 MachineRegisterInfo &MRI = MF->getRegInfo();
30040
30041 // Memory Reference
30042 SmallVector<MachineMemOperand *, 2> MMOs(MI.memoperands_begin(),
30043 MI.memoperands_end());
30044
30045 MVT PVT = getPointerTy(MF->getDataLayout());
30046 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
30047
30048 // checkSspMBB:
30049 // xor vreg1, vreg1
30050 // rdssp vreg1
30051 // test vreg1, vreg1
30052 // je sinkMBB # Jump if Shadow Stack is not supported
30053 // fallMBB:
30054 // mov buf+24/12(%rip), vreg2
30055 // sub vreg1, vreg2
30056 // jbe sinkMBB # No need to fix the Shadow Stack
30057 // fixShadowMBB:
30058 // shr 3/2, vreg2
30059 // incssp vreg2 # fix the SSP according to the lower 8 bits
30060 // shr 8, vreg2
30061 // je sinkMBB
30062 // fixShadowLoopPrepareMBB:
30063 // shl vreg2
30064 // mov 128, vreg3
30065 // fixShadowLoopMBB:
30066 // incssp vreg3
30067 // dec vreg2
30068 // jne fixShadowLoopMBB # Iterate until you finish fixing
30069 // # the Shadow Stack
30070 // sinkMBB:
30071
30072 MachineFunction::iterator I = ++MBB->getIterator();
30073 const BasicBlock *BB = MBB->getBasicBlock();
30074
30075 MachineBasicBlock *checkSspMBB = MF->CreateMachineBasicBlock(BB);
30076 MachineBasicBlock *fallMBB = MF->CreateMachineBasicBlock(BB);
30077 MachineBasicBlock *fixShadowMBB = MF->CreateMachineBasicBlock(BB);
30078 MachineBasicBlock *fixShadowLoopPrepareMBB = MF->CreateMachineBasicBlock(BB);
30079 MachineBasicBlock *fixShadowLoopMBB = MF->CreateMachineBasicBlock(BB);
30080 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
30081 MF->insert(I, checkSspMBB);
30082 MF->insert(I, fallMBB);
30083 MF->insert(I, fixShadowMBB);
30084 MF->insert(I, fixShadowLoopPrepareMBB);
30085 MF->insert(I, fixShadowLoopMBB);
30086 MF->insert(I, sinkMBB);
30087
30088 // Transfer the remainder of BB and its successor edges to sinkMBB.
30089 sinkMBB->splice(sinkMBB->begin(), MBB, MachineBasicBlock::iterator(MI),
30090 MBB->end());
30091 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
30092
30093 MBB->addSuccessor(checkSspMBB);
30094
30095 // Initialize a register with zero.
30096 unsigned ZReg = MRI.createVirtualRegister(PtrRC);
30097 unsigned XorRROpc = (PVT == MVT::i64) ? X86::XOR64rr : X86::XOR32rr;
30098 BuildMI(checkSspMBB, DL, TII->get(XorRROpc))
30099 .addDef(ZReg)
30100 .addReg(ZReg, RegState::Undef)
30101 .addReg(ZReg, RegState::Undef);
30102
30103 // Read the current SSP Register value to the zeroed register.
30104 unsigned SSPCopyReg = MRI.createVirtualRegister(PtrRC);
30105 unsigned RdsspOpc = (PVT == MVT::i64) ? X86::RDSSPQ : X86::RDSSPD;
30106 BuildMI(checkSspMBB, DL, TII->get(RdsspOpc), SSPCopyReg).addReg(ZReg);
30107
30108 // Check whether the result of the SSP register is zero and jump directly
30109 // to the sink.
30110 unsigned TestRROpc = (PVT == MVT::i64) ? X86::TEST64rr : X86::TEST32rr;
30111 BuildMI(checkSspMBB, DL, TII->get(TestRROpc))
30112 .addReg(SSPCopyReg)
30113 .addReg(SSPCopyReg);
30114 BuildMI(checkSspMBB, DL, TII->get(X86::JCC_1)).addMBB(sinkMBB).addImm(X86::COND_E);
30115 checkSspMBB->addSuccessor(sinkMBB);
30116 checkSspMBB->addSuccessor(fallMBB);
30117
30118 // Reload the previously saved SSP register value.
30119 unsigned PrevSSPReg = MRI.createVirtualRegister(PtrRC);
30120 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
30121 const int64_t SPPOffset = 3 * PVT.getStoreSize();
30122 MachineInstrBuilder MIB =
30123 BuildMI(fallMBB, DL, TII->get(PtrLoadOpc), PrevSSPReg);
30124 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
30125 const MachineOperand &MO = MI.getOperand(i);
30126 if (i == X86::AddrDisp)
30127 MIB.addDisp(MO, SPPOffset);
30128 else if (MO.isReg()) // Don't add the whole operand, we don't want to
30129 // preserve kill flags.
30130 MIB.addReg(MO.getReg());
30131 else
30132 MIB.add(MO);
30133 }
30134 MIB.setMemRefs(MMOs);
30135
30136 // Subtract the current SSP from the previous SSP.
30137 unsigned SspSubReg = MRI.createVirtualRegister(PtrRC);
30138 unsigned SubRROpc = (PVT == MVT::i64) ? X86::SUB64rr : X86::SUB32rr;
30139 BuildMI(fallMBB, DL, TII->get(SubRROpc), SspSubReg)
30140 .addReg(PrevSSPReg)
30141 .addReg(SSPCopyReg);
30142
30143 // Jump to sink in case PrevSSPReg <= SSPCopyReg.
30144 BuildMI(fallMBB, DL, TII->get(X86::JCC_1)).addMBB(sinkMBB).addImm(X86::COND_BE);
30145 fallMBB->addSuccessor(sinkMBB);
30146 fallMBB->addSuccessor(fixShadowMBB);
30147
30148 // Shift right by 2/3 for 32/64 because incssp multiplies the argument by 4/8.
30149 unsigned ShrRIOpc = (PVT == MVT::i64) ? X86::SHR64ri : X86::SHR32ri;
30150 unsigned Offset = (PVT == MVT::i64) ? 3 : 2;
30151 unsigned SspFirstShrReg = MRI.createVirtualRegister(PtrRC);
30152 BuildMI(fixShadowMBB, DL, TII->get(ShrRIOpc), SspFirstShrReg)
30153 .addReg(SspSubReg)
30154 .addImm(Offset);
30155
30156 // Increase SSP when looking only on the lower 8 bits of the delta.
30157 unsigned IncsspOpc = (PVT == MVT::i64) ? X86::INCSSPQ : X86::INCSSPD;
30158 BuildMI(fixShadowMBB, DL, TII->get(IncsspOpc)).addReg(SspFirstShrReg);
30159
30160 // Reset the lower 8 bits.
30161 unsigned SspSecondShrReg = MRI.createVirtualRegister(PtrRC);
30162 BuildMI(fixShadowMBB, DL, TII->get(ShrRIOpc), SspSecondShrReg)
30163 .addReg(SspFirstShrReg)
30164 .addImm(8);
30165
30166 // Jump if the result of the shift is zero.
30167 BuildMI(fixShadowMBB, DL, TII->get(X86::JCC_1)).addMBB(sinkMBB).addImm(X86::COND_E);
30168 fixShadowMBB->addSuccessor(sinkMBB);
30169 fixShadowMBB->addSuccessor(fixShadowLoopPrepareMBB);
30170
30171 // Do a single shift left.
30172 unsigned ShlR1Opc = (PVT == MVT::i64) ? X86::SHL64r1 : X86::SHL32r1;
30173 unsigned SspAfterShlReg = MRI.createVirtualRegister(PtrRC);
30174 BuildMI(fixShadowLoopPrepareMBB, DL, TII->get(ShlR1Opc), SspAfterShlReg)
30175 .addReg(SspSecondShrReg);
30176
30177 // Save the value 128 to a register (will be used next with incssp).
30178 unsigned Value128InReg = MRI.createVirtualRegister(PtrRC);
30179 unsigned MovRIOpc = (PVT == MVT::i64) ? X86::MOV64ri32 : X86::MOV32ri;
30180 BuildMI(fixShadowLoopPrepareMBB, DL, TII->get(MovRIOpc), Value128InReg)
30181 .addImm(128);
30182 fixShadowLoopPrepareMBB->addSuccessor(fixShadowLoopMBB);
30183
30184 // Since incssp only looks at the lower 8 bits, we might need to do several
30185 // iterations of incssp until we finish fixing the shadow stack.
30186 unsigned DecReg = MRI.createVirtualRegister(PtrRC);
30187 unsigned CounterReg = MRI.createVirtualRegister(PtrRC);
30188 BuildMI(fixShadowLoopMBB, DL, TII->get(X86::PHI), CounterReg)
30189 .addReg(SspAfterShlReg)
30190 .addMBB(fixShadowLoopPrepareMBB)
30191 .addReg(DecReg)
30192 .addMBB(fixShadowLoopMBB);
30193
30194 // Every iteration we increase the SSP by 128.
30195 BuildMI(fixShadowLoopMBB, DL, TII->get(IncsspOpc)).addReg(Value128InReg);
30196
30197 // Every iteration we decrement the counter by 1.
30198 unsigned DecROpc = (PVT == MVT::i64) ? X86::DEC64r : X86::DEC32r;
30199 BuildMI(fixShadowLoopMBB, DL, TII->get(DecROpc), DecReg).addReg(CounterReg);
30200
30201 // Jump if the counter is not zero yet.
30202 BuildMI(fixShadowLoopMBB, DL, TII->get(X86::JCC_1)).addMBB(fixShadowLoopMBB).addImm(X86::COND_NE);
30203 fixShadowLoopMBB->addSuccessor(sinkMBB);
30204 fixShadowLoopMBB->addSuccessor(fixShadowLoopMBB);
30205
30206 return sinkMBB;
30207}
30208
30209MachineBasicBlock *
30210X86TargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
30211 MachineBasicBlock *MBB) const {
30212 DebugLoc DL = MI.getDebugLoc();
30213 MachineFunction *MF = MBB->getParent();
30214 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
30215 MachineRegisterInfo &MRI = MF->getRegInfo();
30216
30217 // Memory Reference
30218 SmallVector<MachineMemOperand *, 2> MMOs(MI.memoperands_begin(),
30219 MI.memoperands_end());
30220
30221 MVT PVT = getPointerTy(MF->getDataLayout());
30222 assert((PVT == MVT::i64 || PVT == MVT::i32) &&(((PVT == MVT::i64 || PVT == MVT::i32) && "Invalid Pointer Size!"
) ? static_cast<void> (0) : __assert_fail ("(PVT == MVT::i64 || PVT == MVT::i32) && \"Invalid Pointer Size!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 30223, __PRETTY_FUNCTION__))
30223 "Invalid Pointer Size!")(((PVT == MVT::i64 || PVT == MVT::i32) && "Invalid Pointer Size!"
) ? static_cast<void> (0) : __assert_fail ("(PVT == MVT::i64 || PVT == MVT::i32) && \"Invalid Pointer Size!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 30223, __PRETTY_FUNCTION__))
;
30224
30225 const TargetRegisterClass *RC =
30226 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
30227 unsigned Tmp = MRI.createVirtualRegister(RC);
30228 // Since FP is only updated here but NOT referenced, it's treated as GPR.
30229 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
30230 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
30231 unsigned SP = RegInfo->getStackRegister();
30232
30233 MachineInstrBuilder MIB;
30234
30235 const int64_t LabelOffset = 1 * PVT.getStoreSize();
30236 const int64_t SPOffset = 2 * PVT.getStoreSize();
30237
30238 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
30239 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
30240
30241 MachineBasicBlock *thisMBB = MBB;
30242
30243 // When CET and shadow stack is enabled, we need to fix the Shadow Stack.
30244 if (MF->getMMI().getModule()->getModuleFlag("cf-protection-return")) {
30245 thisMBB = emitLongJmpShadowStackFix(MI, thisMBB);
30246 }
30247
30248 // Reload FP
30249 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrLoadOpc), FP);
30250 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
30251 const MachineOperand &MO = MI.getOperand(i);
30252 if (MO.isReg()) // Don't add the whole operand, we don't want to
30253 // preserve kill flags.
30254 MIB.addReg(MO.getReg());
30255 else
30256 MIB.add(MO);
30257 }
30258 MIB.setMemRefs(MMOs);
30259
30260 // Reload IP
30261 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
30262 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
30263 const MachineOperand &MO = MI.getOperand(i);
30264 if (i == X86::AddrDisp)
30265 MIB.addDisp(MO, LabelOffset);
30266 else if (MO.isReg()) // Don't add the whole operand, we don't want to
30267 // preserve kill flags.
30268 MIB.addReg(MO.getReg());
30269 else
30270 MIB.add(MO);
30271 }
30272 MIB.setMemRefs(MMOs);
30273
30274 // Reload SP
30275 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrLoadOpc), SP);
30276 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
30277 if (i == X86::AddrDisp)
30278 MIB.addDisp(MI.getOperand(i), SPOffset);
30279 else
30280 MIB.add(MI.getOperand(i)); // We can preserve the kill flags here, it's
30281 // the last instruction of the expansion.
30282 }
30283 MIB.setMemRefs(MMOs);
30284
30285 // Jump
30286 BuildMI(*thisMBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
30287
30288 MI.eraseFromParent();
30289 return thisMBB;
30290}
30291
30292void X86TargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
30293 MachineBasicBlock *MBB,
30294 MachineBasicBlock *DispatchBB,
30295 int FI) const {
30296 DebugLoc DL = MI.getDebugLoc();
30297 MachineFunction *MF = MBB->getParent();
30298 MachineRegisterInfo *MRI = &MF->getRegInfo();
30299 const X86InstrInfo *TII = Subtarget.getInstrInfo();
30300
30301 MVT PVT = getPointerTy(MF->getDataLayout());
30302 assert((PVT == MVT::i64 || PVT == MVT::i32) && "Invalid Pointer Size!")(((PVT == MVT::i64 || PVT == MVT::i32) && "Invalid Pointer Size!"
) ? static_cast<void> (0) : __assert_fail ("(PVT == MVT::i64 || PVT == MVT::i32) && \"Invalid Pointer Size!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 30302, __PRETTY_FUNCTION__))
;
30303
30304 unsigned Op = 0;
30305 unsigned VR = 0;
30306
30307 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
30308 !isPositionIndependent();
30309
30310 if (UseImmLabel) {
30311 Op = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
30312 } else {
30313 const TargetRegisterClass *TRC =
30314 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
30315 VR = MRI->createVirtualRegister(TRC);
30316 Op = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
30317
30318 if (Subtarget.is64Bit())
30319 BuildMI(*MBB, MI, DL, TII->get(X86::LEA64r), VR)
30320 .addReg(X86::RIP)
30321 .addImm(1)
30322 .addReg(0)
30323 .addMBB(DispatchBB)
30324 .addReg(0);
30325 else
30326 BuildMI(*MBB, MI, DL, TII->get(X86::LEA32r), VR)
30327 .addReg(0) /* TII->getGlobalBaseReg(MF) */
30328 .addImm(1)
30329 .addReg(0)
30330 .addMBB(DispatchBB, Subtarget.classifyBlockAddressReference())
30331 .addReg(0);
30332 }
30333
30334 MachineInstrBuilder MIB = BuildMI(*MBB, MI, DL, TII->get(Op));
30335 addFrameReference(MIB, FI, Subtarget.is64Bit() ? 56 : 36);
30336 if (UseImmLabel)
30337 MIB.addMBB(DispatchBB);
30338 else
30339 MIB.addReg(VR);
30340}
30341
30342MachineBasicBlock *
30343X86TargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
30344 MachineBasicBlock *BB) const {
30345 DebugLoc DL = MI.getDebugLoc();
30346 MachineFunction *MF = BB->getParent();
30347 MachineRegisterInfo *MRI = &MF->getRegInfo();
30348 const X86InstrInfo *TII = Subtarget.getInstrInfo();
30349 int FI = MF->getFrameInfo().getFunctionContextIndex();
30350
30351 // Get a mapping of the call site numbers to all of the landing pads they're
30352 // associated with.
30353 DenseMap<unsigned, SmallVector<MachineBasicBlock *, 2>> CallSiteNumToLPad;
30354 unsigned MaxCSNum = 0;
30355 for (auto &MBB : *MF) {
30356 if (!MBB.isEHPad())
30357 continue;
30358
30359 MCSymbol *Sym = nullptr;
30360 for (const auto &MI : MBB) {
30361 if (MI.isDebugInstr())
30362 continue;
30363
30364 assert(MI.isEHLabel() && "expected EH_LABEL")((MI.isEHLabel() && "expected EH_LABEL") ? static_cast
<void> (0) : __assert_fail ("MI.isEHLabel() && \"expected EH_LABEL\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 30364, __PRETTY_FUNCTION__))
;
30365 Sym = MI.getOperand(0).getMCSymbol();
30366 break;
30367 }
30368
30369 if (!MF->hasCallSiteLandingPad(Sym))
30370 continue;
30371
30372 for (unsigned CSI : MF->getCallSiteLandingPad(Sym)) {
30373 CallSiteNumToLPad[CSI].push_back(&MBB);
30374 MaxCSNum = std::max(MaxCSNum, CSI);
30375 }
30376 }
30377
30378 // Get an ordered list of the machine basic blocks for the jump table.
30379 std::vector<MachineBasicBlock *> LPadList;
30380 SmallPtrSet<MachineBasicBlock *, 32> InvokeBBs;
30381 LPadList.reserve(CallSiteNumToLPad.size());
30382
30383 for (unsigned CSI = 1; CSI <= MaxCSNum; ++CSI) {
30384 for (auto &LP : CallSiteNumToLPad[CSI]) {
30385 LPadList.push_back(LP);
30386 InvokeBBs.insert(LP->pred_begin(), LP->pred_end());
30387 }
30388 }
30389
30390 assert(!LPadList.empty() &&((!LPadList.empty() && "No landing pad destinations for the dispatch jump table!"
) ? static_cast<void> (0) : __assert_fail ("!LPadList.empty() && \"No landing pad destinations for the dispatch jump table!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 30391, __PRETTY_FUNCTION__))
30391 "No landing pad destinations for the dispatch jump table!")((!LPadList.empty() && "No landing pad destinations for the dispatch jump table!"
) ? static_cast<void> (0) : __assert_fail ("!LPadList.empty() && \"No landing pad destinations for the dispatch jump table!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 30391, __PRETTY_FUNCTION__))
;
30392
30393 // Create the MBBs for the dispatch code.
30394
30395 // Shove the dispatch's address into the return slot in the function context.
30396 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
30397 DispatchBB->setIsEHPad(true);
30398
30399 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
30400 BuildMI(TrapBB, DL, TII->get(X86::TRAP));
30401 DispatchBB->addSuccessor(TrapBB);
30402
30403 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
30404 DispatchBB->addSuccessor(DispContBB);
30405
30406 // Insert MBBs.
30407 MF->push_back(DispatchBB);
30408 MF->push_back(DispContBB);
30409 MF->push_back(TrapBB);
30410
30411 // Insert code into the entry block that creates and registers the function
30412 // context.
30413 SetupEntryBlockForSjLj(MI, BB, DispatchBB, FI);
30414
30415 // Create the jump table and associated information
30416 unsigned JTE = getJumpTableEncoding();
30417 MachineJumpTableInfo *JTI = MF->getOrCreateJumpTableInfo(JTE);
30418 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
30419
30420 const X86RegisterInfo &RI = TII->getRegisterInfo();
30421 // Add a register mask with no preserved registers. This results in all
30422 // registers being marked as clobbered.
30423 if (RI.hasBasePointer(*MF)) {
30424 const bool FPIs64Bit =
30425 Subtarget.isTarget64BitLP64() || Subtarget.isTargetNaCl64();
30426 X86MachineFunctionInfo *MFI = MF->getInfo<X86MachineFunctionInfo>();
30427 MFI->setRestoreBasePointer(MF);
30428
30429 unsigned FP = RI.getFrameRegister(*MF);
30430 unsigned BP = RI.getBaseRegister();
30431 unsigned Op = FPIs64Bit ? X86::MOV64rm : X86::MOV32rm;
30432 addRegOffset(BuildMI(DispatchBB, DL, TII->get(Op), BP), FP, true,
30433 MFI->getRestoreBasePointerOffset())
30434 .addRegMask(RI.getNoPreservedMask());
30435 } else {
30436 BuildMI(DispatchBB, DL, TII->get(X86::NOOP))
30437 .addRegMask(RI.getNoPreservedMask());
30438 }
30439
30440 // IReg is used as an index in a memory operand and therefore can't be SP
30441 unsigned IReg = MRI->createVirtualRegister(&X86::GR32_NOSPRegClass);
30442 addFrameReference(BuildMI(DispatchBB, DL, TII->get(X86::MOV32rm), IReg), FI,
30443 Subtarget.is64Bit() ? 8 : 4);
30444 BuildMI(DispatchBB, DL, TII->get(X86::CMP32ri))
30445 .addReg(IReg)
30446 .addImm(LPadList.size());
30447 BuildMI(DispatchBB, DL, TII->get(X86::JCC_1)).addMBB(TrapBB).addImm(X86::COND_AE);
30448
30449 if (Subtarget.is64Bit()) {
30450 unsigned BReg = MRI->createVirtualRegister(&X86::GR64RegClass);
30451 unsigned IReg64 = MRI->createVirtualRegister(&X86::GR64_NOSPRegClass);
30452
30453 // leaq .LJTI0_0(%rip), BReg
30454 BuildMI(DispContBB, DL, TII->get(X86::LEA64r), BReg)
30455 .addReg(X86::RIP)
30456 .addImm(1)
30457 .addReg(0)
30458 .addJumpTableIndex(MJTI)
30459 .addReg(0);
30460 // movzx IReg64, IReg
30461 BuildMI(DispContBB, DL, TII->get(TargetOpcode::SUBREG_TO_REG), IReg64)
30462 .addImm(0)
30463 .addReg(IReg)
30464 .addImm(X86::sub_32bit);
30465
30466 switch (JTE) {
30467 case MachineJumpTableInfo::EK_BlockAddress:
30468 // jmpq *(BReg,IReg64,8)
30469 BuildMI(DispContBB, DL, TII->get(X86::JMP64m))
30470 .addReg(BReg)
30471 .addImm(8)
30472 .addReg(IReg64)
30473 .addImm(0)
30474 .addReg(0);
30475 break;
30476 case MachineJumpTableInfo::EK_LabelDifference32: {
30477 unsigned OReg = MRI->createVirtualRegister(&X86::GR32RegClass);
30478 unsigned OReg64 = MRI->createVirtualRegister(&X86::GR64RegClass);
30479 unsigned TReg = MRI->createVirtualRegister(&X86::GR64RegClass);
30480
30481 // movl (BReg,IReg64,4), OReg
30482 BuildMI(DispContBB, DL, TII->get(X86::MOV32rm), OReg)
30483 .addReg(BReg)
30484 .addImm(4)
30485 .addReg(IReg64)
30486 .addImm(0)
30487 .addReg(0);
30488 // movsx OReg64, OReg
30489 BuildMI(DispContBB, DL, TII->get(X86::MOVSX64rr32), OReg64).addReg(OReg);
30490 // addq BReg, OReg64, TReg
30491 BuildMI(DispContBB, DL, TII->get(X86::ADD64rr), TReg)
30492 .addReg(OReg64)
30493 .addReg(BReg);
30494 // jmpq *TReg
30495 BuildMI(DispContBB, DL, TII->get(X86::JMP64r)).addReg(TReg);
30496 break;
30497 }
30498 default:
30499 llvm_unreachable("Unexpected jump table encoding")::llvm::llvm_unreachable_internal("Unexpected jump table encoding"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 30499)
;
30500 }
30501 } else {
30502 // jmpl *.LJTI0_0(,IReg,4)
30503 BuildMI(DispContBB, DL, TII->get(X86::JMP32m))
30504 .addReg(0)
30505 .addImm(4)
30506 .addReg(IReg)
30507 .addJumpTableIndex(MJTI)
30508 .addReg(0);
30509 }
30510
30511 // Add the jump table entries as successors to the MBB.
30512 SmallPtrSet<MachineBasicBlock *, 8> SeenMBBs;
30513 for (auto &LP : LPadList)
30514 if (SeenMBBs.insert(LP).second)
30515 DispContBB->addSuccessor(LP);
30516
30517 // N.B. the order the invoke BBs are processed in doesn't matter here.
30518 SmallVector<MachineBasicBlock *, 64> MBBLPads;
30519 const MCPhysReg *SavedRegs = MF->getRegInfo().getCalleeSavedRegs();
30520 for (MachineBasicBlock *MBB : InvokeBBs) {
30521 // Remove the landing pad successor from the invoke block and replace it
30522 // with the new dispatch block.
30523 // Keep a copy of Successors since it's modified inside the loop.
30524 SmallVector<MachineBasicBlock *, 8> Successors(MBB->succ_rbegin(),
30525 MBB->succ_rend());
30526 // FIXME: Avoid quadratic complexity.
30527 for (auto MBBS : Successors) {
30528 if (MBBS->isEHPad()) {
30529 MBB->removeSuccessor(MBBS);
30530 MBBLPads.push_back(MBBS);
30531 }
30532 }
30533
30534 MBB->addSuccessor(DispatchBB);
30535
30536 // Find the invoke call and mark all of the callee-saved registers as
30537 // 'implicit defined' so that they're spilled. This prevents code from
30538 // moving instructions to before the EH block, where they will never be
30539 // executed.
30540 for (auto &II : reverse(*MBB)) {
30541 if (!II.isCall())
30542 continue;
30543
30544 DenseMap<unsigned, bool> DefRegs;
30545 for (auto &MOp : II.operands())
30546 if (MOp.isReg())
30547 DefRegs[MOp.getReg()] = true;
30548
30549 MachineInstrBuilder MIB(*MF, &II);
30550 for (unsigned RI = 0; SavedRegs[RI]; ++RI) {
30551 unsigned Reg = SavedRegs[RI];
30552 if (!DefRegs[Reg])
30553 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
30554 }
30555
30556 break;
30557 }
30558 }
30559
30560 // Mark all former landing pads as non-landing pads. The dispatch is the only
30561 // landing pad now.
30562 for (auto &LP : MBBLPads)
30563 LP->setIsEHPad(false);
30564
30565 // The instruction is gone now.
30566 MI.eraseFromParent();
30567 return BB;
30568}
30569
30570MachineBasicBlock *
30571X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
30572 MachineBasicBlock *BB) const {
30573 MachineFunction *MF = BB->getParent();
30574 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
30575 DebugLoc DL = MI.getDebugLoc();
30576
30577 switch (MI.getOpcode()) {
30578 default: llvm_unreachable("Unexpected instr type to insert")::llvm::llvm_unreachable_internal("Unexpected instr type to insert"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 30578)
;
30579 case X86::TLS_addr32:
30580 case X86::TLS_addr64:
30581 case X86::TLS_base_addr32:
30582 case X86::TLS_base_addr64:
30583 return EmitLoweredTLSAddr(MI, BB);
30584 case X86::RETPOLINE_CALL32:
30585 case X86::RETPOLINE_CALL64:
30586 case X86::RETPOLINE_TCRETURN32:
30587 case X86::RETPOLINE_TCRETURN64:
30588 return EmitLoweredRetpoline(MI, BB);
30589 case X86::CATCHRET:
30590 return EmitLoweredCatchRet(MI, BB);
30591 case X86::CATCHPAD:
30592 return EmitLoweredCatchPad(MI, BB);
30593 case X86::SEG_ALLOCA_32:
30594 case X86::SEG_ALLOCA_64:
30595 return EmitLoweredSegAlloca(MI, BB);
30596 case X86::TLSCall_32:
30597 case X86::TLSCall_64:
30598 return EmitLoweredTLSCall(MI, BB);
30599 case X86::CMOV_FR32:
30600 case X86::CMOV_FR32X:
30601 case X86::CMOV_FR64:
30602 case X86::CMOV_FR64X:
30603 case X86::CMOV_GR8:
30604 case X86::CMOV_GR16:
30605 case X86::CMOV_GR32:
30606 case X86::CMOV_RFP32:
30607 case X86::CMOV_RFP64:
30608 case X86::CMOV_RFP80:
30609 case X86::CMOV_VR128:
30610 case X86::CMOV_VR128X:
30611 case X86::CMOV_VR256:
30612 case X86::CMOV_VR256X:
30613 case X86::CMOV_VR512:
30614 case X86::CMOV_VK2:
30615 case X86::CMOV_VK4:
30616 case X86::CMOV_VK8:
30617 case X86::CMOV_VK16:
30618 case X86::CMOV_VK32:
30619 case X86::CMOV_VK64:
30620 return EmitLoweredSelect(MI, BB);
30621
30622 case X86::RDFLAGS32:
30623 case X86::RDFLAGS64: {
30624 unsigned PushF =
30625 MI.getOpcode() == X86::RDFLAGS32 ? X86::PUSHF32 : X86::PUSHF64;
30626 unsigned Pop = MI.getOpcode() == X86::RDFLAGS32 ? X86::POP32r : X86::POP64r;
30627 MachineInstr *Push = BuildMI(*BB, MI, DL, TII->get(PushF));
30628 // Permit reads of the EFLAGS and DF registers without them being defined.
30629 // This intrinsic exists to read external processor state in flags, such as
30630 // the trap flag, interrupt flag, and direction flag, none of which are
30631 // modeled by the backend.
30632 assert(Push->getOperand(2).getReg() == X86::EFLAGS &&((Push->getOperand(2).getReg() == X86::EFLAGS && "Unexpected register in operand!"
) ? static_cast<void> (0) : __assert_fail ("Push->getOperand(2).getReg() == X86::EFLAGS && \"Unexpected register in operand!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 30633, __PRETTY_FUNCTION__))
30633 "Unexpected register in operand!")((Push->getOperand(2).getReg() == X86::EFLAGS && "Unexpected register in operand!"
) ? static_cast<void> (0) : __assert_fail ("Push->getOperand(2).getReg() == X86::EFLAGS && \"Unexpected register in operand!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 30633, __PRETTY_FUNCTION__))
;
30634 Push->getOperand(2).setIsUndef();
30635 assert(Push->getOperand(3).getReg() == X86::DF &&((Push->getOperand(3).getReg() == X86::DF && "Unexpected register in operand!"
) ? static_cast<void> (0) : __assert_fail ("Push->getOperand(3).getReg() == X86::DF && \"Unexpected register in operand!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 30636, __PRETTY_FUNCTION__))
30636 "Unexpected register in operand!")((Push->getOperand(3).getReg() == X86::DF && "Unexpected register in operand!"
) ? static_cast<void> (0) : __assert_fail ("Push->getOperand(3).getReg() == X86::DF && \"Unexpected register in operand!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 30636, __PRETTY_FUNCTION__))
;
30637 Push->getOperand(3).setIsUndef();
30638 BuildMI(*BB, MI, DL, TII->get(Pop), MI.getOperand(0).getReg());
30639
30640 MI.eraseFromParent(); // The pseudo is gone now.
30641 return BB;
30642 }
30643
30644 case X86::WRFLAGS32:
30645 case X86::WRFLAGS64: {
30646 unsigned Push =
30647 MI.getOpcode() == X86::WRFLAGS32 ? X86::PUSH32r : X86::PUSH64r;
30648 unsigned PopF =
30649 MI.getOpcode() == X86::WRFLAGS32 ? X86::POPF32 : X86::POPF64;
30650 BuildMI(*BB, MI, DL, TII->get(Push)).addReg(MI.getOperand(0).getReg());
30651 BuildMI(*BB, MI, DL, TII->get(PopF));
30652
30653 MI.eraseFromParent(); // The pseudo is gone now.
30654 return BB;
30655 }
30656
30657 case X86::FP32_TO_INT16_IN_MEM:
30658 case X86::FP32_TO_INT32_IN_MEM:
30659 case X86::FP32_TO_INT64_IN_MEM:
30660 case X86::FP64_TO_INT16_IN_MEM:
30661 case X86::FP64_TO_INT32_IN_MEM:
30662 case X86::FP64_TO_INT64_IN_MEM:
30663 case X86::FP80_TO_INT16_IN_MEM:
30664 case X86::FP80_TO_INT32_IN_MEM:
30665 case X86::FP80_TO_INT64_IN_MEM: {
30666 // Change the floating point control register to use "round towards zero"
30667 // mode when truncating to an integer value.
30668 int OrigCWFrameIdx = MF->getFrameInfo().CreateStackObject(2, 2, false);
30669 addFrameReference(BuildMI(*BB, MI, DL,
30670 TII->get(X86::FNSTCW16m)), OrigCWFrameIdx);
30671
30672 // Load the old value of the control word...
30673 unsigned OldCW =
30674 MF->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
30675 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOVZX32rm16), OldCW),
30676 OrigCWFrameIdx);
30677
30678 // OR 0b11 into bit 10 and 11. 0b11 is the encoding for round toward zero.
30679 unsigned NewCW =
30680 MF->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
30681 BuildMI(*BB, MI, DL, TII->get(X86::OR32ri), NewCW)
30682 .addReg(OldCW, RegState::Kill).addImm(0xC00);
30683
30684 // Extract to 16 bits.
30685 unsigned NewCW16 =
30686 MF->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
30687 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY), NewCW16)
30688 .addReg(NewCW, RegState::Kill, X86::sub_16bit);
30689
30690 // Prepare memory for FLDCW.
30691 int NewCWFrameIdx = MF->getFrameInfo().CreateStackObject(2, 2, false);
30692 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)),
30693 NewCWFrameIdx)
30694 .addReg(NewCW16, RegState::Kill);
30695
30696 // Reload the modified control word now...
30697 addFrameReference(BuildMI(*BB, MI, DL,
30698 TII->get(X86::FLDCW16m)), NewCWFrameIdx);
30699
30700 // Get the X86 opcode to use.
30701 unsigned Opc;
30702 switch (MI.getOpcode()) {
30703 default: llvm_unreachable("illegal opcode!")::llvm::llvm_unreachable_internal("illegal opcode!", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 30703)
;
30704 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
30705 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
30706 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
30707 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
30708 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
30709 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
30710 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
30711 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
30712 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
30713 }
30714
30715 X86AddressMode AM = getAddressFromInstr(&MI, 0);
30716 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
30717 .addReg(MI.getOperand(X86::AddrNumOperands).getReg());
30718
30719 // Reload the original control word now.
30720 addFrameReference(BuildMI(*BB, MI, DL,
30721 TII->get(X86::FLDCW16m)), OrigCWFrameIdx);
30722
30723 MI.eraseFromParent(); // The pseudo instruction is gone now.
30724 return BB;
30725 }
30726
30727 // xbegin
30728 case X86::XBEGIN:
30729 return emitXBegin(MI, BB, Subtarget.getInstrInfo());
30730
30731 case X86::VASTART_SAVE_XMM_REGS:
30732 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
30733
30734 case X86::VAARG_64:
30735 return EmitVAARG64WithCustomInserter(MI, BB);
30736
30737 case X86::EH_SjLj_SetJmp32:
30738 case X86::EH_SjLj_SetJmp64:
30739 return emitEHSjLjSetJmp(MI, BB);
30740
30741 case X86::EH_SjLj_LongJmp32:
30742 case X86::EH_SjLj_LongJmp64:
30743 return emitEHSjLjLongJmp(MI, BB);
30744
30745 case X86::Int_eh_sjlj_setup_dispatch:
30746 return EmitSjLjDispatchBlock(MI, BB);
30747
30748 case TargetOpcode::STATEPOINT:
30749 // As an implementation detail, STATEPOINT shares the STACKMAP format at
30750 // this point in the process. We diverge later.
30751 return emitPatchPoint(MI, BB);
30752
30753 case TargetOpcode::STACKMAP:
30754 case TargetOpcode::PATCHPOINT:
30755 return emitPatchPoint(MI, BB);
30756
30757 case TargetOpcode::PATCHABLE_EVENT_CALL:
30758 return emitXRayCustomEvent(MI, BB);
30759
30760 case TargetOpcode::PATCHABLE_TYPED_EVENT_CALL:
30761 return emitXRayTypedEvent(MI, BB);
30762
30763 case X86::LCMPXCHG8B: {
30764 const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
30765 // In addition to 4 E[ABCD] registers implied by encoding, CMPXCHG8B
30766 // requires a memory operand. If it happens that current architecture is
30767 // i686 and for current function we need a base pointer
30768 // - which is ESI for i686 - register allocator would not be able to
30769 // allocate registers for an address in form of X(%reg, %reg, Y)
30770 // - there never would be enough unreserved registers during regalloc
30771 // (without the need for base ptr the only option would be X(%edi, %esi, Y).
30772 // We are giving a hand to register allocator by precomputing the address in
30773 // a new vreg using LEA.
30774
30775 // If it is not i686 or there is no base pointer - nothing to do here.
30776 if (!Subtarget.is32Bit() || !TRI->hasBasePointer(*MF))
30777 return BB;
30778
30779 // Even though this code does not necessarily needs the base pointer to
30780 // be ESI, we check for that. The reason: if this assert fails, there are
30781 // some changes happened in the compiler base pointer handling, which most
30782 // probably have to be addressed somehow here.
30783 assert(TRI->getBaseRegister() == X86::ESI &&((TRI->getBaseRegister() == X86::ESI && "LCMPXCHG8B custom insertion for i686 is written with X86::ESI as a "
"base pointer in mind") ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 30785, __PRETTY_FUNCTION__))
30784 "LCMPXCHG8B custom insertion for i686 is written with X86::ESI as a "((TRI->getBaseRegister() == X86::ESI && "LCMPXCHG8B custom insertion for i686 is written with X86::ESI as a "
"base pointer in mind") ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 30785, __PRETTY_FUNCTION__))
30785 "base pointer in mind")((TRI->getBaseRegister() == X86::ESI && "LCMPXCHG8B custom insertion for i686 is written with X86::ESI as a "
"base pointer in mind") ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 30785, __PRETTY_FUNCTION__))
;
30786
30787 MachineRegisterInfo &MRI = MF->getRegInfo();
30788 MVT SPTy = getPointerTy(MF->getDataLayout());
30789 const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
30790 unsigned computedAddrVReg = MRI.createVirtualRegister(AddrRegClass);
30791
30792 X86AddressMode AM = getAddressFromInstr(&MI, 0);
30793 // Regalloc does not need any help when the memory operand of CMPXCHG8B
30794 // does not use index register.
30795 if (AM.IndexReg == X86::NoRegister)
30796 return BB;
30797
30798 // After X86TargetLowering::ReplaceNodeResults CMPXCHG8B is glued to its
30799 // four operand definitions that are E[ABCD] registers. We skip them and
30800 // then insert the LEA.
30801 MachineBasicBlock::iterator MBBI(MI);
30802 while (MBBI->definesRegister(X86::EAX) || MBBI->definesRegister(X86::EBX) ||
30803 MBBI->definesRegister(X86::ECX) || MBBI->definesRegister(X86::EDX))
30804 --MBBI;
30805 addFullAddress(
30806 BuildMI(*BB, *MBBI, DL, TII->get(X86::LEA32r), computedAddrVReg), AM);
30807
30808 setDirectAddressInInstr(&MI, 0, computedAddrVReg);
30809
30810 return BB;
30811 }
30812 case X86::LCMPXCHG16B:
30813 return BB;
30814 case X86::LCMPXCHG8B_SAVE_EBX:
30815 case X86::LCMPXCHG16B_SAVE_RBX: {
30816 unsigned BasePtr =
30817 MI.getOpcode() == X86::LCMPXCHG8B_SAVE_EBX ? X86::EBX : X86::RBX;
30818 if (!BB->isLiveIn(BasePtr))
30819 BB->addLiveIn(BasePtr);
30820 return BB;
30821 }
30822 }
30823}
30824
30825//===----------------------------------------------------------------------===//
30826// X86 Optimization Hooks
30827//===----------------------------------------------------------------------===//
30828
30829bool
30830X86TargetLowering::targetShrinkDemandedConstant(SDValue Op,
30831 const APInt &Demanded,
30832 TargetLoweringOpt &TLO) const {
30833 // Only optimize Ands to prevent shrinking a constant that could be
30834 // matched by movzx.
30835 if (Op.getOpcode() != ISD::AND)
30836 return false;
30837
30838 EVT VT = Op.getValueType();
30839
30840 // Ignore vectors.
30841 if (VT.isVector())
30842 return false;
30843
30844 unsigned Size = VT.getSizeInBits();
30845
30846 // Make sure the RHS really is a constant.
30847 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
30848 if (!C)
30849 return false;
30850
30851 const APInt &Mask = C->getAPIntValue();
30852
30853 // Clear all non-demanded bits initially.
30854 APInt ShrunkMask = Mask & Demanded;
30855
30856 // Find the width of the shrunk mask.
30857 unsigned Width = ShrunkMask.getActiveBits();
30858
30859 // If the mask is all 0s there's nothing to do here.
30860 if (Width == 0)
30861 return false;
30862
30863 // Find the next power of 2 width, rounding up to a byte.
30864 Width = PowerOf2Ceil(std::max(Width, 8U));
30865 // Truncate the width to size to handle illegal types.
30866 Width = std::min(Width, Size);
30867
30868 // Calculate a possible zero extend mask for this constant.
30869 APInt ZeroExtendMask = APInt::getLowBitsSet(Size, Width);
30870
30871 // If we aren't changing the mask, just return true to keep it and prevent
30872 // the caller from optimizing.
30873 if (ZeroExtendMask == Mask)
30874 return true;
30875
30876 // Make sure the new mask can be represented by a combination of mask bits
30877 // and non-demanded bits.
30878 if (!ZeroExtendMask.isSubsetOf(Mask | ~Demanded))
30879 return false;
30880
30881 // Replace the constant with the zero extend mask.
30882 SDLoc DL(Op);
30883 SDValue NewC = TLO.DAG.getConstant(ZeroExtendMask, DL, VT);
30884 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
30885 return TLO.CombineTo(Op, NewOp);
30886}
30887
30888void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
30889 KnownBits &Known,
30890 const APInt &DemandedElts,
30891 const SelectionDAG &DAG,
30892 unsigned Depth) const {
30893 unsigned BitWidth = Known.getBitWidth();
30894 unsigned Opc = Op.getOpcode();
30895 EVT VT = Op.getValueType();
30896 assert((Opc >= ISD::BUILTIN_OP_END ||(((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!") ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 30901, __PRETTY_FUNCTION__))
30897 Opc == ISD::INTRINSIC_WO_CHAIN ||(((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!") ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 30901, __PRETTY_FUNCTION__))
30898 Opc == ISD::INTRINSIC_W_CHAIN ||(((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!") ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 30901, __PRETTY_FUNCTION__))
30899 Opc == ISD::INTRINSIC_VOID) &&(((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!") ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 30901, __PRETTY_FUNCTION__))
30900 "Should use MaskedValueIsZero if you don't know whether Op"(((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!") ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 30901, __PRETTY_FUNCTION__))
30901 " is a target node!")(((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!") ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 30901, __PRETTY_FUNCTION__))
;
30902
30903 Known.resetAll();
30904 switch (Opc) {
30905 default: break;
30906 case X86ISD::SETCC:
30907 Known.Zero.setBitsFrom(1);
30908 break;
30909 case X86ISD::MOVMSK: {
30910 unsigned NumLoBits = Op.getOperand(0).getValueType().getVectorNumElements();
30911 Known.Zero.setBitsFrom(NumLoBits);
30912 break;
30913 }
30914 case X86ISD::PEXTRB:
30915 case X86ISD::PEXTRW: {
30916 SDValue Src = Op.getOperand(0);
30917 EVT SrcVT = Src.getValueType();
30918 APInt DemandedElt = APInt::getOneBitSet(SrcVT.getVectorNumElements(),
30919 Op.getConstantOperandVal(1));
30920 Known = DAG.computeKnownBits(Src, DemandedElt, Depth + 1);
30921 Known = Known.zextOrTrunc(BitWidth, false);
30922 Known.Zero.setBitsFrom(SrcVT.getScalarSizeInBits());
30923 break;
30924 }
30925 case X86ISD::VSRAI:
30926 case X86ISD::VSHLI:
30927 case X86ISD::VSRLI: {
30928 if (auto *ShiftImm = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
30929 if (ShiftImm->getAPIntValue().uge(VT.getScalarSizeInBits())) {
30930 Known.setAllZero();
30931 break;
30932 }
30933
30934 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
30935 unsigned ShAmt = ShiftImm->getZExtValue();
30936 if (Opc == X86ISD::VSHLI) {
30937 Known.Zero <<= ShAmt;
30938 Known.One <<= ShAmt;
30939 // Low bits are known zero.
30940 Known.Zero.setLowBits(ShAmt);
30941 } else if (Opc == X86ISD::VSRLI) {
30942 Known.Zero.lshrInPlace(ShAmt);
30943 Known.One.lshrInPlace(ShAmt);
30944 // High bits are known zero.
30945 Known.Zero.setHighBits(ShAmt);
30946 } else {
30947 Known.Zero.ashrInPlace(ShAmt);
30948 Known.One.ashrInPlace(ShAmt);
30949 }
30950 }
30951 break;
30952 }
30953 case X86ISD::PACKUS: {
30954 // PACKUS is just a truncation if the upper half is zero.
30955 APInt DemandedLHS, DemandedRHS;
30956 getPackDemandedElts(VT, DemandedElts, DemandedLHS, DemandedRHS);
30957
30958 Known.One = APInt::getAllOnesValue(BitWidth * 2);
30959 Known.Zero = APInt::getAllOnesValue(BitWidth * 2);
30960
30961 KnownBits Known2;
30962 if (!!DemandedLHS) {
30963 Known2 = DAG.computeKnownBits(Op.getOperand(0), DemandedLHS, Depth + 1);
30964 Known.One &= Known2.One;
30965 Known.Zero &= Known2.Zero;
30966 }
30967 if (!!DemandedRHS) {
30968 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedRHS, Depth + 1);
30969 Known.One &= Known2.One;
30970 Known.Zero &= Known2.Zero;
30971 }
30972
30973 if (Known.countMinLeadingZeros() < BitWidth)
30974 Known.resetAll();
30975 Known = Known.trunc(BitWidth);
30976 break;
30977 }
30978 case X86ISD::ANDNP: {
30979 KnownBits Known2;
30980 Known = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
30981 Known2 = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
30982
30983 // ANDNP = (~X & Y);
30984 Known.One &= Known2.Zero;
30985 Known.Zero |= Known2.One;
30986 break;
30987 }
30988 case X86ISD::FOR: {
30989 KnownBits Known2;
30990 Known = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
30991 Known2 = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
30992
30993 // Output known-0 bits are only known if clear in both the LHS & RHS.
30994 Known.Zero &= Known2.Zero;
30995 // Output known-1 are known to be set if set in either the LHS | RHS.
30996 Known.One |= Known2.One;
30997 break;
30998 }
30999 case X86ISD::CMOV: {
31000 Known = DAG.computeKnownBits(Op.getOperand(1), Depth+1);
31001 // If we don't know any bits, early out.
31002 if (Known.isUnknown())
31003 break;
31004 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth+1);
31005
31006 // Only known if known in both the LHS and RHS.
31007 Known.One &= Known2.One;
31008 Known.Zero &= Known2.Zero;
31009 break;
31010 }
31011 }
31012
31013 // Handle target shuffles.
31014 // TODO - use resolveTargetShuffleInputs once we can limit recursive depth.
31015 if (isTargetShuffle(Opc)) {
31016 bool IsUnary;
31017 SmallVector<int, 64> Mask;
31018 SmallVector<SDValue, 2> Ops;
31019 if (getTargetShuffleMask(Op.getNode(), VT.getSimpleVT(), true, Ops, Mask,
31020 IsUnary)) {
31021 unsigned NumOps = Ops.size();
31022 unsigned NumElts = VT.getVectorNumElements();
31023 if (Mask.size() == NumElts) {
31024 SmallVector<APInt, 2> DemandedOps(NumOps, APInt(NumElts, 0));
31025 Known.Zero.setAllBits(); Known.One.setAllBits();
31026 for (unsigned i = 0; i != NumElts; ++i) {
31027 if (!DemandedElts[i])
31028 continue;
31029 int M = Mask[i];
31030 if (M == SM_SentinelUndef) {
31031 // For UNDEF elements, we don't know anything about the common state
31032 // of the shuffle result.
31033 Known.resetAll();
31034 break;
31035 } else if (M == SM_SentinelZero) {
31036 Known.One.clearAllBits();
31037 continue;
31038 }
31039 assert(0 <= M && (unsigned)M < (NumOps * NumElts) &&((0 <= M && (unsigned)M < (NumOps * NumElts) &&
"Shuffle index out of range") ? static_cast<void> (0) :
__assert_fail ("0 <= M && (unsigned)M < (NumOps * NumElts) && \"Shuffle index out of range\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 31040, __PRETTY_FUNCTION__))
31040 "Shuffle index out of range")((0 <= M && (unsigned)M < (NumOps * NumElts) &&
"Shuffle index out of range") ? static_cast<void> (0) :
__assert_fail ("0 <= M && (unsigned)M < (NumOps * NumElts) && \"Shuffle index out of range\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 31040, __PRETTY_FUNCTION__))
;
31041
31042 unsigned OpIdx = (unsigned)M / NumElts;
31043 unsigned EltIdx = (unsigned)M % NumElts;
31044 if (Ops[OpIdx].getValueType() != VT) {
31045 // TODO - handle target shuffle ops with different value types.
31046 Known.resetAll();
31047 break;
31048 }
31049 DemandedOps[OpIdx].setBit(EltIdx);
31050 }
31051 // Known bits are the values that are shared by every demanded element.
31052 for (unsigned i = 0; i != NumOps && !Known.isUnknown(); ++i) {
31053 if (!DemandedOps[i])
31054 continue;
31055 KnownBits Known2 =
31056 DAG.computeKnownBits(Ops[i], DemandedOps[i], Depth + 1);
31057 Known.One &= Known2.One;
31058 Known.Zero &= Known2.Zero;
31059 }
31060 }
31061 }
31062 }
31063}
31064
31065unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
31066 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
31067 unsigned Depth) const {
31068 unsigned VTBits = Op.getScalarValueSizeInBits();
31069 unsigned Opcode = Op.getOpcode();
31070 switch (Opcode) {
31071 case X86ISD::SETCC_CARRY:
31072 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
31073 return VTBits;
31074
31075 case X86ISD::VTRUNC: {
31076 // TODO: Add DemandedElts support.
31077 SDValue Src = Op.getOperand(0);
31078 unsigned NumSrcBits = Src.getScalarValueSizeInBits();
31079 assert(VTBits < NumSrcBits && "Illegal truncation input type")((VTBits < NumSrcBits && "Illegal truncation input type"
) ? static_cast<void> (0) : __assert_fail ("VTBits < NumSrcBits && \"Illegal truncation input type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 31079, __PRETTY_FUNCTION__))
;
31080 unsigned Tmp = DAG.ComputeNumSignBits(Src, Depth + 1);
31081 if (Tmp > (NumSrcBits - VTBits))
31082 return Tmp - (NumSrcBits - VTBits);
31083 return 1;
31084 }
31085
31086 case X86ISD::PACKSS: {
31087 // PACKSS is just a truncation if the sign bits extend to the packed size.
31088 APInt DemandedLHS, DemandedRHS;
31089 getPackDemandedElts(Op.getValueType(), DemandedElts, DemandedLHS,
31090 DemandedRHS);
31091
31092 unsigned SrcBits = Op.getOperand(0).getScalarValueSizeInBits();
31093 unsigned Tmp0 = SrcBits, Tmp1 = SrcBits;
31094 if (!!DemandedLHS)
31095 Tmp0 = DAG.ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
31096 if (!!DemandedRHS)
31097 Tmp1 = DAG.ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
31098 unsigned Tmp = std::min(Tmp0, Tmp1);
31099 if (Tmp > (SrcBits - VTBits))
31100 return Tmp - (SrcBits - VTBits);
31101 return 1;
31102 }
31103
31104 case X86ISD::VSHLI: {
31105 SDValue Src = Op.getOperand(0);
31106 const APInt &ShiftVal = Op.getConstantOperandAPInt(1);
31107 if (ShiftVal.uge(VTBits))
31108 return VTBits; // Shifted all bits out --> zero.
31109 unsigned Tmp = DAG.ComputeNumSignBits(Src, DemandedElts, Depth + 1);
31110 if (ShiftVal.uge(Tmp))
31111 return 1; // Shifted all sign bits out --> unknown.
31112 return Tmp - ShiftVal.getZExtValue();
31113 }
31114
31115 case X86ISD::VSRAI: {
31116 SDValue Src = Op.getOperand(0);
31117 APInt ShiftVal = Op.getConstantOperandAPInt(1);
31118 if (ShiftVal.uge(VTBits - 1))
31119 return VTBits; // Sign splat.
31120 unsigned Tmp = DAG.ComputeNumSignBits(Src, DemandedElts, Depth + 1);
31121 ShiftVal += Tmp;
31122 return ShiftVal.uge(VTBits) ? VTBits : ShiftVal.getZExtValue();
31123 }
31124
31125 case X86ISD::PCMPGT:
31126 case X86ISD::PCMPEQ:
31127 case X86ISD::CMPP:
31128 case X86ISD::VPCOM:
31129 case X86ISD::VPCOMU:
31130 // Vector compares return zero/all-bits result values.
31131 return VTBits;
31132
31133 case X86ISD::ANDNP: {
31134 unsigned Tmp0 =
31135 DAG.ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
31136 if (Tmp0 == 1) return 1; // Early out.
31137 unsigned Tmp1 =
31138 DAG.ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
31139 return std::min(Tmp0, Tmp1);
31140 }
31141
31142 case X86ISD::CMOV: {
31143 unsigned Tmp0 = DAG.ComputeNumSignBits(Op.getOperand(0), Depth+1);
31144 if (Tmp0 == 1) return 1; // Early out.
31145 unsigned Tmp1 = DAG.ComputeNumSignBits(Op.getOperand(1), Depth+1);
31146 return std::min(Tmp0, Tmp1);
31147 }
31148 }
31149
31150 // Fallback case.
31151 return 1;
31152}
31153
31154SDValue X86TargetLowering::unwrapAddress(SDValue N) const {
31155 if (N->getOpcode() == X86ISD::Wrapper || N->getOpcode() == X86ISD::WrapperRIP)
31156 return N->getOperand(0);
31157 return N;
31158}
31159
31160// Attempt to match a combined shuffle mask against supported unary shuffle
31161// instructions.
31162// TODO: Investigate sharing more of this with shuffle lowering.
31163static bool matchUnaryShuffle(MVT MaskVT, ArrayRef<int> Mask,
31164 bool AllowFloatDomain, bool AllowIntDomain,
31165 SDValue &V1, const SDLoc &DL, SelectionDAG &DAG,
31166 const X86Subtarget &Subtarget, unsigned &Shuffle,
31167 MVT &SrcVT, MVT &DstVT) {
31168 unsigned NumMaskElts = Mask.size();
31169 unsigned MaskEltSize = MaskVT.getScalarSizeInBits();
31170
31171 // Match against a VZEXT_MOVL vXi32 zero-extending instruction.
31172 if (MaskEltSize == 32 && isUndefOrEqual(Mask[0], 0) &&
31173 isUndefOrZero(Mask[1]) && isUndefInRange(Mask, 2, NumMaskElts - 2)) {
31174 Shuffle = X86ISD::VZEXT_MOVL;
31175 SrcVT = DstVT = !Subtarget.hasSSE2() ? MVT::v4f32 : MaskVT;
31176 return true;
31177 }
31178
31179 // Match against a ZERO_EXTEND_VECTOR_INREG/VZEXT instruction.
31180 // TODO: Add 512-bit vector support (split AVX512F and AVX512BW).
31181 if (AllowIntDomain && ((MaskVT.is128BitVector() && Subtarget.hasSSE41()) ||
31182 (MaskVT.is256BitVector() && Subtarget.hasInt256()))) {
31183 unsigned MaxScale = 64 / MaskEltSize;
31184 for (unsigned Scale = 2; Scale <= MaxScale; Scale *= 2) {
31185 bool Match = true;
31186 unsigned NumDstElts = NumMaskElts / Scale;
31187 for (unsigned i = 0; i != NumDstElts && Match; ++i) {
31188 Match &= isUndefOrEqual(Mask[i * Scale], (int)i);
31189 Match &= isUndefOrZeroInRange(Mask, (i * Scale) + 1, Scale - 1);
31190 }
31191 if (Match) {
31192 unsigned SrcSize = std::max(128u, NumDstElts * MaskEltSize);
31193 MVT ScalarTy = MaskVT.isInteger() ? MaskVT.getScalarType() :
31194 MVT::getIntegerVT(MaskEltSize);
31195 SrcVT = MVT::getVectorVT(ScalarTy, SrcSize / MaskEltSize);
31196
31197 if (SrcVT.getSizeInBits() != MaskVT.getSizeInBits())
31198 V1 = extractSubVector(V1, 0, DAG, DL, SrcSize);
31199
31200 if (SrcVT.getVectorNumElements() == NumDstElts)
31201 Shuffle = unsigned(ISD::ZERO_EXTEND);
31202 else
31203 Shuffle = unsigned(ISD::ZERO_EXTEND_VECTOR_INREG);
31204
31205 DstVT = MVT::getIntegerVT(Scale * MaskEltSize);
31206 DstVT = MVT::getVectorVT(DstVT, NumDstElts);
31207 return true;
31208 }
31209 }
31210 }
31211
31212 // Match against a VZEXT_MOVL instruction, SSE1 only supports 32-bits (MOVSS).
31213 if (((MaskEltSize == 32) || (MaskEltSize == 64 && Subtarget.hasSSE2())) &&
31214 isUndefOrEqual(Mask[0], 0) &&
31215 isUndefOrZeroInRange(Mask, 1, NumMaskElts - 1)) {
31216 Shuffle = X86ISD::VZEXT_MOVL;
31217 SrcVT = DstVT = !Subtarget.hasSSE2() ? MVT::v4f32 : MaskVT;
31218 return true;
31219 }
31220
31221 // Check if we have SSE3 which will let us use MOVDDUP etc. The
31222 // instructions are no slower than UNPCKLPD but has the option to
31223 // fold the input operand into even an unaligned memory load.
31224 if (MaskVT.is128BitVector() && Subtarget.hasSSE3() && AllowFloatDomain) {
31225 if (isTargetShuffleEquivalent(Mask, {0, 0})) {
31226 Shuffle = X86ISD::MOVDDUP;
31227 SrcVT = DstVT = MVT::v2f64;
31228 return true;
31229 }
31230 if (isTargetShuffleEquivalent(Mask, {0, 0, 2, 2})) {
31231 Shuffle = X86ISD::MOVSLDUP;
31232 SrcVT = DstVT = MVT::v4f32;
31233 return true;
31234 }
31235 if (isTargetShuffleEquivalent(Mask, {1, 1, 3, 3})) {
31236 Shuffle = X86ISD::MOVSHDUP;
31237 SrcVT = DstVT = MVT::v4f32;
31238 return true;
31239 }
31240 }
31241
31242 if (MaskVT.is256BitVector() && AllowFloatDomain) {
31243 assert(Subtarget.hasAVX() && "AVX required for 256-bit vector shuffles")((Subtarget.hasAVX() && "AVX required for 256-bit vector shuffles"
) ? static_cast<void> (0) : __assert_fail ("Subtarget.hasAVX() && \"AVX required for 256-bit vector shuffles\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 31243, __PRETTY_FUNCTION__))
;
31244 if (isTargetShuffleEquivalent(Mask, {0, 0, 2, 2})) {
31245 Shuffle = X86ISD::MOVDDUP;
31246 SrcVT = DstVT = MVT::v4f64;
31247 return true;
31248 }
31249 if (isTargetShuffleEquivalent(Mask, {0, 0, 2, 2, 4, 4, 6, 6})) {
31250 Shuffle = X86ISD::MOVSLDUP;
31251 SrcVT = DstVT = MVT::v8f32;
31252 return true;
31253 }
31254 if (isTargetShuffleEquivalent(Mask, {1, 1, 3, 3, 5, 5, 7, 7})) {
31255 Shuffle = X86ISD::MOVSHDUP;
31256 SrcVT = DstVT = MVT::v8f32;
31257 return true;
31258 }
31259 }
31260
31261 if (MaskVT.is512BitVector() && AllowFloatDomain) {
31262 assert(Subtarget.hasAVX512() &&((Subtarget.hasAVX512() && "AVX512 required for 512-bit vector shuffles"
) ? static_cast<void> (0) : __assert_fail ("Subtarget.hasAVX512() && \"AVX512 required for 512-bit vector shuffles\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 31263, __PRETTY_FUNCTION__))
31263 "AVX512 required for 512-bit vector shuffles")((Subtarget.hasAVX512() && "AVX512 required for 512-bit vector shuffles"
) ? static_cast<void> (0) : __assert_fail ("Subtarget.hasAVX512() && \"AVX512 required for 512-bit vector shuffles\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 31263, __PRETTY_FUNCTION__))
;
31264 if (isTargetShuffleEquivalent(Mask, {0, 0, 2, 2, 4, 4, 6, 6})) {
31265 Shuffle = X86ISD::MOVDDUP;
31266 SrcVT = DstVT = MVT::v8f64;
31267 return true;
31268 }
31269 if (isTargetShuffleEquivalent(
31270 Mask, {0, 0, 2, 2, 4, 4, 6, 6, 8, 8, 10, 10, 12, 12, 14, 14})) {
31271 Shuffle = X86ISD::MOVSLDUP;
31272 SrcVT = DstVT = MVT::v16f32;
31273 return true;
31274 }
31275 if (isTargetShuffleEquivalent(
31276 Mask, {1, 1, 3, 3, 5, 5, 7, 7, 9, 9, 11, 11, 13, 13, 15, 15})) {
31277 Shuffle = X86ISD::MOVSHDUP;
31278 SrcVT = DstVT = MVT::v16f32;
31279 return true;
31280 }
31281 }
31282
31283 return false;
31284}
31285
31286// Attempt to match a combined shuffle mask against supported unary immediate
31287// permute instructions.
31288// TODO: Investigate sharing more of this with shuffle lowering.
31289static bool matchUnaryPermuteShuffle(MVT MaskVT, ArrayRef<int> Mask,
31290 const APInt &Zeroable,
31291 bool AllowFloatDomain, bool AllowIntDomain,
31292 const X86Subtarget &Subtarget,
31293 unsigned &Shuffle, MVT &ShuffleVT,
31294 unsigned &PermuteImm) {
31295 unsigned NumMaskElts = Mask.size();
31296 unsigned InputSizeInBits = MaskVT.getSizeInBits();
31297 unsigned MaskScalarSizeInBits = InputSizeInBits / NumMaskElts;
31298 MVT MaskEltVT = MVT::getIntegerVT(MaskScalarSizeInBits);
31299
31300 bool ContainsZeros =
31301 llvm::any_of(Mask, [](int M) { return M == SM_SentinelZero; });
31302
31303 // Handle VPERMI/VPERMILPD vXi64/vXi64 patterns.
31304 if (!ContainsZeros && MaskScalarSizeInBits == 64) {
31305 // Check for lane crossing permutes.
31306 if (is128BitLaneCrossingShuffleMask(MaskEltVT, Mask)) {
31307 // PERMPD/PERMQ permutes within a 256-bit vector (AVX2+).
31308 if (Subtarget.hasAVX2() && MaskVT.is256BitVector()) {
31309 Shuffle = X86ISD::VPERMI;
31310 ShuffleVT = (AllowFloatDomain ? MVT::v4f64 : MVT::v4i64);
31311 PermuteImm = getV4X86ShuffleImm(Mask);
31312 return true;
31313 }
31314 if (Subtarget.hasAVX512() && MaskVT.is512BitVector()) {
31315 SmallVector<int, 4> RepeatedMask;
31316 if (is256BitLaneRepeatedShuffleMask(MVT::v8f64, Mask, RepeatedMask)) {
31317 Shuffle = X86ISD::VPERMI;
31318 ShuffleVT = (AllowFloatDomain ? MVT::v8f64 : MVT::v8i64);
31319 PermuteImm = getV4X86ShuffleImm(RepeatedMask);
31320 return true;
31321 }
31322 }
31323 } else if (AllowFloatDomain && Subtarget.hasAVX()) {
31324 // VPERMILPD can permute with a non-repeating shuffle.
31325 Shuffle = X86ISD::VPERMILPI;
31326 ShuffleVT = MVT::getVectorVT(MVT::f64, Mask.size());
31327 PermuteImm = 0;
31328 for (int i = 0, e = Mask.size(); i != e; ++i) {
31329 int M = Mask[i];
31330 if (M == SM_SentinelUndef)
31331 continue;
31332 assert(((M / 2) == (i / 2)) && "Out of range shuffle mask index")((((M / 2) == (i / 2)) && "Out of range shuffle mask index"
) ? static_cast<void> (0) : __assert_fail ("((M / 2) == (i / 2)) && \"Out of range shuffle mask index\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 31332, __PRETTY_FUNCTION__))
;
31333 PermuteImm |= (M & 1) << i;
31334 }
31335 return true;
31336 }
31337 }
31338
31339 // Handle PSHUFD/VPERMILPI vXi32/vXf32 repeated patterns.
31340 // AVX introduced the VPERMILPD/VPERMILPS float permutes, before then we
31341 // had to use 2-input SHUFPD/SHUFPS shuffles (not handled here).
31342 if ((MaskScalarSizeInBits == 64 || MaskScalarSizeInBits == 32) &&
31343 !ContainsZeros && (AllowIntDomain || Subtarget.hasAVX())) {
31344 SmallVector<int, 4> RepeatedMask;
31345 if (is128BitLaneRepeatedShuffleMask(MaskEltVT, Mask, RepeatedMask)) {
31346 // Narrow the repeated mask to create 32-bit element permutes.
31347 SmallVector<int, 4> WordMask = RepeatedMask;
31348 if (MaskScalarSizeInBits == 64)
31349 scaleShuffleMask<int>(2, RepeatedMask, WordMask);
31350
31351 Shuffle = (AllowIntDomain ? X86ISD::PSHUFD : X86ISD::VPERMILPI);
31352 ShuffleVT = (AllowIntDomain ? MVT::i32 : MVT::f32);
31353 ShuffleVT = MVT::getVectorVT(ShuffleVT, InputSizeInBits / 32);
31354 PermuteImm = getV4X86ShuffleImm(WordMask);
31355 return true;
31356 }
31357 }
31358
31359 // Handle PSHUFLW/PSHUFHW vXi16 repeated patterns.
31360 if (!ContainsZeros && AllowIntDomain && MaskScalarSizeInBits == 16) {
31361 SmallVector<int, 4> RepeatedMask;
31362 if (is128BitLaneRepeatedShuffleMask(MaskEltVT, Mask, RepeatedMask)) {
31363 ArrayRef<int> LoMask(Mask.data() + 0, 4);
31364 ArrayRef<int> HiMask(Mask.data() + 4, 4);
31365
31366 // PSHUFLW: permute lower 4 elements only.
31367 if (isUndefOrInRange(LoMask, 0, 4) &&
31368 isSequentialOrUndefInRange(HiMask, 0, 4, 4)) {
31369 Shuffle = X86ISD::PSHUFLW;
31370 ShuffleVT = MVT::getVectorVT(MVT::i16, InputSizeInBits / 16);
31371 PermuteImm = getV4X86ShuffleImm(LoMask);
31372 return true;
31373 }
31374
31375 // PSHUFHW: permute upper 4 elements only.
31376 if (isUndefOrInRange(HiMask, 4, 8) &&
31377 isSequentialOrUndefInRange(LoMask, 0, 4, 0)) {
31378 // Offset the HiMask so that we can create the shuffle immediate.
31379 int OffsetHiMask[4];
31380 for (int i = 0; i != 4; ++i)
31381 OffsetHiMask[i] = (HiMask[i] < 0 ? HiMask[i] : HiMask[i] - 4);
31382
31383 Shuffle = X86ISD::PSHUFHW;
31384 ShuffleVT = MVT::getVectorVT(MVT::i16, InputSizeInBits / 16);
31385 PermuteImm = getV4X86ShuffleImm(OffsetHiMask);
31386 return true;
31387 }
31388 }
31389 }
31390
31391 // Attempt to match against byte/bit shifts.
31392 // FIXME: Add 512-bit support.
31393 if (AllowIntDomain && ((MaskVT.is128BitVector() && Subtarget.hasSSE2()) ||
31394 (MaskVT.is256BitVector() && Subtarget.hasAVX2()))) {
31395 int ShiftAmt = matchShuffleAsShift(ShuffleVT, Shuffle, MaskScalarSizeInBits,
31396 Mask, 0, Zeroable, Subtarget);
31397 if (0 < ShiftAmt) {
31398 PermuteImm = (unsigned)ShiftAmt;
31399 return true;
31400 }
31401 }
31402
31403 return false;
31404}
31405
31406// Attempt to match a combined unary shuffle mask against supported binary
31407// shuffle instructions.
31408// TODO: Investigate sharing more of this with shuffle lowering.
31409static bool matchBinaryShuffle(MVT MaskVT, ArrayRef<int> Mask,
31410 bool AllowFloatDomain, bool AllowIntDomain,
31411 SDValue &V1, SDValue &V2, const SDLoc &DL,
31412 SelectionDAG &DAG, const X86Subtarget &Subtarget,
31413 unsigned &Shuffle, MVT &SrcVT, MVT &DstVT,
31414 bool IsUnary) {
31415 unsigned EltSizeInBits = MaskVT.getScalarSizeInBits();
31416
31417 if (MaskVT.is128BitVector()) {
31418 if (isTargetShuffleEquivalent(Mask, {0, 0}) && AllowFloatDomain) {
31419 V2 = V1;
31420 V1 = (SM_SentinelUndef == Mask[0] ? DAG.getUNDEF(MVT::v4f32) : V1);
31421 Shuffle = Subtarget.hasSSE2() ? X86ISD::UNPCKL : X86ISD::MOVLHPS;
31422 SrcVT = DstVT = Subtarget.hasSSE2() ? MVT::v2f64 : MVT::v4f32;
31423 return true;
31424 }
31425 if (isTargetShuffleEquivalent(Mask, {1, 1}) && AllowFloatDomain) {
31426 V2 = V1;
31427 Shuffle = Subtarget.hasSSE2() ? X86ISD::UNPCKH : X86ISD::MOVHLPS;
31428 SrcVT = DstVT = Subtarget.hasSSE2() ? MVT::v2f64 : MVT::v4f32;
31429 return true;
31430 }
31431 if (isTargetShuffleEquivalent(Mask, {0, 3}) && Subtarget.hasSSE2() &&
31432 (AllowFloatDomain || !Subtarget.hasSSE41())) {
31433 std::swap(V1, V2);
31434 Shuffle = X86ISD::MOVSD;
31435 SrcVT = DstVT = MVT::v2f64;
31436 return true;
31437 }
31438 if (isTargetShuffleEquivalent(Mask, {4, 1, 2, 3}) &&
31439 (AllowFloatDomain || !Subtarget.hasSSE41())) {
31440 Shuffle = X86ISD::MOVSS;
31441 SrcVT = DstVT = MVT::v4f32;
31442 return true;
31443 }
31444 }
31445
31446 // Attempt to match against either an unary or binary PACKSS/PACKUS shuffle.
31447 if (((MaskVT == MVT::v8i16 || MaskVT == MVT::v16i8) && Subtarget.hasSSE2()) ||
31448 ((MaskVT == MVT::v16i16 || MaskVT == MVT::v32i8) && Subtarget.hasInt256()) ||
31449 ((MaskVT == MVT::v32i16 || MaskVT == MVT::v64i8) && Subtarget.hasBWI())) {
31450 if (matchVectorShuffleWithPACK(MaskVT, SrcVT, V1, V2, Shuffle, Mask, DAG,
31451 Subtarget)) {
31452 DstVT = MaskVT;
31453 return true;
31454 }
31455 }
31456
31457 // Attempt to match against either a unary or binary UNPCKL/UNPCKH shuffle.
31458 if ((MaskVT == MVT::v4f32 && Subtarget.hasSSE1()) ||
31459 (MaskVT.is128BitVector() && Subtarget.hasSSE2()) ||
31460 (MaskVT.is256BitVector() && 32 <= EltSizeInBits && Subtarget.hasAVX()) ||
31461 (MaskVT.is256BitVector() && Subtarget.hasAVX2()) ||
31462 (MaskVT.is512BitVector() && Subtarget.hasAVX512())) {
31463 if (matchVectorShuffleWithUNPCK(MaskVT, V1, V2, Shuffle, IsUnary, Mask, DL,
31464 DAG, Subtarget)) {
31465 SrcVT = DstVT = MaskVT;
31466 if (MaskVT.is256BitVector() && !Subtarget.hasAVX2())
31467 SrcVT = DstVT = (32 == EltSizeInBits ? MVT::v8f32 : MVT::v4f64);
31468 return true;
31469 }
31470 }
31471
31472 return false;
31473}
31474
31475static bool matchBinaryPermuteShuffle(
31476 MVT MaskVT, ArrayRef<int> Mask, const APInt &Zeroable,
31477 bool AllowFloatDomain, bool AllowIntDomain, SDValue &V1, SDValue &V2,
31478 const SDLoc &DL, SelectionDAG &DAG, const X86Subtarget &Subtarget,
31479 unsigned &Shuffle, MVT &ShuffleVT, unsigned &PermuteImm) {
31480 unsigned NumMaskElts = Mask.size();
31481 unsigned EltSizeInBits = MaskVT.getScalarSizeInBits();
31482
31483 // Attempt to match against PALIGNR byte rotate.
31484 if (AllowIntDomain && ((MaskVT.is128BitVector() && Subtarget.hasSSSE3()) ||
31485 (MaskVT.is256BitVector() && Subtarget.hasAVX2()))) {
31486 int ByteRotation = matchShuffleAsByteRotate(MaskVT, V1, V2, Mask);
31487 if (0 < ByteRotation) {
31488 Shuffle = X86ISD::PALIGNR;
31489 ShuffleVT = MVT::getVectorVT(MVT::i8, MaskVT.getSizeInBits() / 8);
31490 PermuteImm = ByteRotation;
31491 return true;
31492 }
31493 }
31494
31495 // Attempt to combine to X86ISD::BLENDI.
31496 if ((NumMaskElts <= 8 && ((Subtarget.hasSSE41() && MaskVT.is128BitVector()) ||
31497 (Subtarget.hasAVX() && MaskVT.is256BitVector()))) ||
31498 (MaskVT == MVT::v16i16 && Subtarget.hasAVX2())) {
31499 uint64_t BlendMask = 0;
31500 bool ForceV1Zero = false, ForceV2Zero = false;
31501 SmallVector<int, 8> TargetMask(Mask.begin(), Mask.end());
31502 if (matchVectorShuffleAsBlend(V1, V2, TargetMask, ForceV1Zero, ForceV2Zero,
31503 BlendMask)) {
31504 if (MaskVT == MVT::v16i16) {
31505 // We can only use v16i16 PBLENDW if the lanes are repeated.
31506 SmallVector<int, 8> RepeatedMask;
31507 if (isRepeatedTargetShuffleMask(128, MaskVT, TargetMask,
31508 RepeatedMask)) {
31509 assert(RepeatedMask.size() == 8 &&((RepeatedMask.size() == 8 && "Repeated mask size doesn't match!"
) ? static_cast<void> (0) : __assert_fail ("RepeatedMask.size() == 8 && \"Repeated mask size doesn't match!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 31510, __PRETTY_FUNCTION__))
31510 "Repeated mask size doesn't match!")((RepeatedMask.size() == 8 && "Repeated mask size doesn't match!"
) ? static_cast<void> (0) : __assert_fail ("RepeatedMask.size() == 8 && \"Repeated mask size doesn't match!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 31510, __PRETTY_FUNCTION__))
;
31511 PermuteImm = 0;
31512 for (int i = 0; i < 8; ++i)
31513 if (RepeatedMask[i] >= 8)
31514 PermuteImm |= 1 << i;
31515 V1 = ForceV1Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V1;
31516 V2 = ForceV2Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V2;
31517 Shuffle = X86ISD::BLENDI;
31518 ShuffleVT = MaskVT;
31519 return true;
31520 }
31521 } else {
31522 V1 = ForceV1Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V1;
31523 V2 = ForceV2Zero ? getZeroVector(MaskVT, Subtarget, DAG, DL) : V2;
31524 PermuteImm = (unsigned)BlendMask;
31525 Shuffle = X86ISD::BLENDI;
31526 ShuffleVT = MaskVT;
31527 return true;
31528 }
31529 }
31530 }
31531
31532 // Attempt to combine to INSERTPS.
31533 if (AllowFloatDomain && EltSizeInBits == 32 && Subtarget.hasSSE41() &&
31534 MaskVT.is128BitVector()) {
31535 if (Zeroable.getBoolValue() &&
31536 matchShuffleAsInsertPS(V1, V2, PermuteImm, Zeroable, Mask, DAG)) {
31537 Shuffle = X86ISD::INSERTPS;
31538 ShuffleVT = MVT::v4f32;
31539 return true;
31540 }
31541 }
31542
31543 // Attempt to combine to SHUFPD.
31544 if (AllowFloatDomain && EltSizeInBits == 64 &&
31545 ((MaskVT.is128BitVector() && Subtarget.hasSSE2()) ||
31546 (MaskVT.is256BitVector() && Subtarget.hasAVX()) ||
31547 (MaskVT.is512BitVector() && Subtarget.hasAVX512()))) {
31548 if (matchShuffleWithSHUFPD(MaskVT, V1, V2, PermuteImm, Mask)) {
31549 Shuffle = X86ISD::SHUFP;
31550 ShuffleVT = MVT::getVectorVT(MVT::f64, MaskVT.getSizeInBits() / 64);
31551 return true;
31552 }
31553 }
31554
31555 // Attempt to combine to SHUFPS.
31556 if (AllowFloatDomain && EltSizeInBits == 32 &&
31557 ((MaskVT.is128BitVector() && Subtarget.hasSSE1()) ||
31558 (MaskVT.is256BitVector() && Subtarget.hasAVX()) ||
31559 (MaskVT.is512BitVector() && Subtarget.hasAVX512()))) {
31560 SmallVector<int, 4> RepeatedMask;
31561 if (isRepeatedTargetShuffleMask(128, MaskVT, Mask, RepeatedMask)) {
31562 // Match each half of the repeated mask, to determine if its just
31563 // referencing one of the vectors, is zeroable or entirely undef.
31564 auto MatchHalf = [&](unsigned Offset, int &S0, int &S1) {
31565 int M0 = RepeatedMask[Offset];
31566 int M1 = RepeatedMask[Offset + 1];
31567
31568 if (isUndefInRange(RepeatedMask, Offset, 2)) {
31569 return DAG.getUNDEF(MaskVT);
31570 } else if (isUndefOrZeroInRange(RepeatedMask, Offset, 2)) {
31571 S0 = (SM_SentinelUndef == M0 ? -1 : 0);
31572 S1 = (SM_SentinelUndef == M1 ? -1 : 1);
31573 return getZeroVector(MaskVT, Subtarget, DAG, DL);
31574 } else if (isUndefOrInRange(M0, 0, 4) && isUndefOrInRange(M1, 0, 4)) {
31575 S0 = (SM_SentinelUndef == M0 ? -1 : M0 & 3);
31576 S1 = (SM_SentinelUndef == M1 ? -1 : M1 & 3);
31577 return V1;
31578 } else if (isUndefOrInRange(M0, 4, 8) && isUndefOrInRange(M1, 4, 8)) {
31579 S0 = (SM_SentinelUndef == M0 ? -1 : M0 & 3);
31580 S1 = (SM_SentinelUndef == M1 ? -1 : M1 & 3);
31581 return V2;
31582 }
31583
31584 return SDValue();
31585 };
31586
31587 int ShufMask[4] = {-1, -1, -1, -1};
31588 SDValue Lo = MatchHalf(0, ShufMask[0], ShufMask[1]);
31589 SDValue Hi = MatchHalf(2, ShufMask[2], ShufMask[3]);
31590
31591 if (Lo && Hi) {
31592 V1 = Lo;
31593 V2 = Hi;
31594 Shuffle = X86ISD::SHUFP;
31595 ShuffleVT = MVT::getVectorVT(MVT::f32, MaskVT.getSizeInBits() / 32);
31596 PermuteImm = getV4X86ShuffleImm(ShufMask);
31597 return true;
31598 }
31599 }
31600 }
31601
31602 return false;
31603}
31604
31605/// Combine an arbitrary chain of shuffles into a single instruction if
31606/// possible.
31607///
31608/// This is the leaf of the recursive combine below. When we have found some
31609/// chain of single-use x86 shuffle instructions and accumulated the combined
31610/// shuffle mask represented by them, this will try to pattern match that mask
31611/// into either a single instruction if there is a special purpose instruction
31612/// for this operation, or into a PSHUFB instruction which is a fully general
31613/// instruction but should only be used to replace chains over a certain depth.
31614static SDValue combineX86ShuffleChain(ArrayRef<SDValue> Inputs, SDValue Root,
31615 ArrayRef<int> BaseMask, int Depth,
31616 bool HasVariableMask,
31617 bool AllowVariableMask, SelectionDAG &DAG,
31618 const X86Subtarget &Subtarget) {
31619 assert(!BaseMask.empty() && "Cannot combine an empty shuffle mask!")((!BaseMask.empty() && "Cannot combine an empty shuffle mask!"
) ? static_cast<void> (0) : __assert_fail ("!BaseMask.empty() && \"Cannot combine an empty shuffle mask!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 31619, __PRETTY_FUNCTION__))
;
31620 assert((Inputs.size() == 1 || Inputs.size() == 2) &&(((Inputs.size() == 1 || Inputs.size() == 2) && "Unexpected number of shuffle inputs!"
) ? static_cast<void> (0) : __assert_fail ("(Inputs.size() == 1 || Inputs.size() == 2) && \"Unexpected number of shuffle inputs!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 31621, __PRETTY_FUNCTION__))
31621 "Unexpected number of shuffle inputs!")(((Inputs.size() == 1 || Inputs.size() == 2) && "Unexpected number of shuffle inputs!"
) ? static_cast<void> (0) : __assert_fail ("(Inputs.size() == 1 || Inputs.size() == 2) && \"Unexpected number of shuffle inputs!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 31621, __PRETTY_FUNCTION__))
;
31622
31623 // Find the inputs that enter the chain. Note that multiple uses are OK
31624 // here, we're not going to remove the operands we find.
31625 bool UnaryShuffle = (Inputs.size() == 1);
31626 SDValue V1 = peekThroughBitcasts(Inputs[0]);
31627 SDValue V2 = (UnaryShuffle ? DAG.getUNDEF(V1.getValueType())
31628 : peekThroughBitcasts(Inputs[1]));
31629
31630 MVT VT1 = V1.getSimpleValueType();
31631 MVT VT2 = V2.getSimpleValueType();
31632 MVT RootVT = Root.getSimpleValueType();
31633 assert(VT1.getSizeInBits() == RootVT.getSizeInBits() &&((VT1.getSizeInBits() == RootVT.getSizeInBits() && VT2
.getSizeInBits() == RootVT.getSizeInBits() && "Vector size mismatch"
) ? static_cast<void> (0) : __assert_fail ("VT1.getSizeInBits() == RootVT.getSizeInBits() && VT2.getSizeInBits() == RootVT.getSizeInBits() && \"Vector size mismatch\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 31635, __PRETTY_FUNCTION__))
31634 VT2.getSizeInBits() == RootVT.getSizeInBits() &&((VT1.getSizeInBits() == RootVT.getSizeInBits() && VT2
.getSizeInBits() == RootVT.getSizeInBits() && "Vector size mismatch"
) ? static_cast<void> (0) : __assert_fail ("VT1.getSizeInBits() == RootVT.getSizeInBits() && VT2.getSizeInBits() == RootVT.getSizeInBits() && \"Vector size mismatch\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 31635, __PRETTY_FUNCTION__))
31635 "Vector size mismatch")((VT1.getSizeInBits() == RootVT.getSizeInBits() && VT2
.getSizeInBits() == RootVT.getSizeInBits() && "Vector size mismatch"
) ? static_cast<void> (0) : __assert_fail ("VT1.getSizeInBits() == RootVT.getSizeInBits() && VT2.getSizeInBits() == RootVT.getSizeInBits() && \"Vector size mismatch\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 31635, __PRETTY_FUNCTION__))
;
31636
31637 SDLoc DL(Root);
31638 SDValue Res;
31639
31640 unsigned NumBaseMaskElts = BaseMask.size();
31641 if (NumBaseMaskElts == 1) {
31642 assert(BaseMask[0] == 0 && "Invalid shuffle index found!")((BaseMask[0] == 0 && "Invalid shuffle index found!")
? static_cast<void> (0) : __assert_fail ("BaseMask[0] == 0 && \"Invalid shuffle index found!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 31642, __PRETTY_FUNCTION__))
;
31643 return DAG.getBitcast(RootVT, V1);
31644 }
31645
31646 unsigned RootSizeInBits = RootVT.getSizeInBits();
31647 unsigned NumRootElts = RootVT.getVectorNumElements();
31648 unsigned BaseMaskEltSizeInBits = RootSizeInBits / NumBaseMaskElts;
31649 bool FloatDomain = VT1.isFloatingPoint() || VT2.isFloatingPoint() ||
31650 (RootVT.isFloatingPoint() && Depth >= 2) ||
31651 (RootVT.is256BitVector() && !Subtarget.hasAVX2());
31652
31653 // Don't combine if we are a AVX512/EVEX target and the mask element size
31654 // is different from the root element size - this would prevent writemasks
31655 // from being reused.
31656 // TODO - this currently prevents all lane shuffles from occurring.
31657 // TODO - check for writemasks usage instead of always preventing combining.
31658 // TODO - attempt to narrow Mask back to writemask size.
31659 bool IsEVEXShuffle =
31660 RootSizeInBits == 512 || (Subtarget.hasVLX() && RootSizeInBits >= 128);
31661
31662 // Attempt to match a subvector broadcast.
31663 // shuffle(insert_subvector(undef, sub, 0), undef, 0, 0, 0, 0)
31664 if (UnaryShuffle &&
31665 (BaseMaskEltSizeInBits == 128 || BaseMaskEltSizeInBits == 256)) {
31666 SmallVector<int, 64> BroadcastMask(NumBaseMaskElts, 0);
31667 if (isTargetShuffleEquivalent(BaseMask, BroadcastMask)) {
31668 SDValue Src = Inputs[0];
31669 if (Src.getOpcode() == ISD::INSERT_SUBVECTOR &&
31670 Src.getOperand(0).isUndef() &&
31671 Src.getOperand(1).getValueSizeInBits() == BaseMaskEltSizeInBits &&
31672 MayFoldLoad(Src.getOperand(1)) && isNullConstant(Src.getOperand(2))) {
31673 return DAG.getBitcast(RootVT, DAG.getNode(X86ISD::SUBV_BROADCAST, DL,
31674 Src.getValueType(),
31675 Src.getOperand(1)));
31676 }
31677 }
31678 }
31679
31680 // TODO - handle 128/256-bit lane shuffles of 512-bit vectors.
31681
31682 // Handle 128-bit lane shuffles of 256-bit vectors.
31683 // If we have AVX2, prefer to use VPERMQ/VPERMPD for unary shuffles unless
31684 // we need to use the zeroing feature.
31685 // TODO - this should support binary shuffles.
31686 if (UnaryShuffle && RootVT.is256BitVector() && NumBaseMaskElts == 2 &&
31687 !(Subtarget.hasAVX2() && BaseMask[0] >= -1 && BaseMask[1] >= -1) &&
31688 !isSequentialOrUndefOrZeroInRange(BaseMask, 0, 2, 0)) {
31689 if (Depth == 1 && Root.getOpcode() == X86ISD::VPERM2X128)
31690 return SDValue(); // Nothing to do!
31691 MVT ShuffleVT = (FloatDomain ? MVT::v4f64 : MVT::v4i64);
31692 unsigned PermMask = 0;
31693 PermMask |= ((BaseMask[0] < 0 ? 0x8 : (BaseMask[0] & 1)) << 0);
31694 PermMask |= ((BaseMask[1] < 0 ? 0x8 : (BaseMask[1] & 1)) << 4);
31695
31696 Res = DAG.getBitcast(ShuffleVT, V1);
31697 Res = DAG.getNode(X86ISD::VPERM2X128, DL, ShuffleVT, Res,
31698 DAG.getUNDEF(ShuffleVT),
31699 DAG.getConstant(PermMask, DL, MVT::i8));
31700 return DAG.getBitcast(RootVT, Res);
31701 }
31702
31703 // For masks that have been widened to 128-bit elements or more,
31704 // narrow back down to 64-bit elements.
31705 SmallVector<int, 64> Mask;
31706 if (BaseMaskEltSizeInBits > 64) {
31707 assert((BaseMaskEltSizeInBits % 64) == 0 && "Illegal mask size")(((BaseMaskEltSizeInBits % 64) == 0 && "Illegal mask size"
) ? static_cast<void> (0) : __assert_fail ("(BaseMaskEltSizeInBits % 64) == 0 && \"Illegal mask size\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 31707, __PRETTY_FUNCTION__))
;
31708 int MaskScale = BaseMaskEltSizeInBits / 64;
31709 scaleShuffleMask<int>(MaskScale, BaseMask, Mask);
31710 } else {
31711 Mask = SmallVector<int, 64>(BaseMask.begin(), BaseMask.end());
31712 }
31713
31714 unsigned NumMaskElts = Mask.size();
31715 unsigned MaskEltSizeInBits = RootSizeInBits / NumMaskElts;
31716
31717 // Determine the effective mask value type.
31718 FloatDomain &= (32 <= MaskEltSizeInBits);
31719 MVT MaskVT = FloatDomain ? MVT::getFloatingPointVT(MaskEltSizeInBits)
31720 : MVT::getIntegerVT(MaskEltSizeInBits);
31721 MaskVT = MVT::getVectorVT(MaskVT, NumMaskElts);
31722
31723 // Only allow legal mask types.
31724 if (!DAG.getTargetLoweringInfo().isTypeLegal(MaskVT))
31725 return SDValue();
31726
31727 // Attempt to match the mask against known shuffle patterns.
31728 MVT ShuffleSrcVT, ShuffleVT;
31729 unsigned Shuffle, PermuteImm;
31730
31731 // Which shuffle domains are permitted?
31732 // Permit domain crossing at higher combine depths.
31733 bool AllowFloatDomain = FloatDomain || (Depth > 3);
31734 bool AllowIntDomain = (!FloatDomain || (Depth > 3)) && Subtarget.hasSSE2() &&
31735 (!MaskVT.is256BitVector() || Subtarget.hasAVX2());
31736
31737 // Determine zeroable mask elements.
31738 APInt Zeroable(NumMaskElts, 0);
31739 for (unsigned i = 0; i != NumMaskElts; ++i)
31740 if (isUndefOrZero(Mask[i]))
31741 Zeroable.setBit(i);
31742
31743 if (UnaryShuffle) {
31744 // If we are shuffling a X86ISD::VZEXT_LOAD then we can use the load
31745 // directly if we don't shuffle the lower element and we shuffle the upper
31746 // (zero) elements within themselves.
31747 if (V1.getOpcode() == X86ISD::VZEXT_LOAD &&
31748 (V1.getScalarValueSizeInBits() % MaskEltSizeInBits) == 0) {
31749 unsigned Scale = V1.getScalarValueSizeInBits() / MaskEltSizeInBits;
31750 ArrayRef<int> HiMask(Mask.data() + Scale, NumMaskElts - Scale);
31751 if (isSequentialOrUndefInRange(Mask, 0, Scale, 0) &&
31752 isUndefOrZeroOrInRange(HiMask, Scale, NumMaskElts)) {
31753 return DAG.getBitcast(RootVT, V1);
31754 }
31755 }
31756
31757 // Attempt to match against broadcast-from-vector.
31758 // Limit AVX1 to cases where we're loading+broadcasting a scalar element.
31759 if ((Subtarget.hasAVX2() || (Subtarget.hasAVX() && 32 <= MaskEltSizeInBits))
31760 && (!IsEVEXShuffle || NumRootElts == NumMaskElts)) {
31761 SmallVector<int, 64> BroadcastMask(NumMaskElts, 0);
31762 if (isTargetShuffleEquivalent(Mask, BroadcastMask)) {
31763 if (V1.getValueType() == MaskVT &&
31764 V1.getOpcode() == ISD::SCALAR_TO_VECTOR &&
31765 MayFoldLoad(V1.getOperand(0))) {
31766 if (Depth == 1 && Root.getOpcode() == X86ISD::VBROADCAST)
31767 return SDValue(); // Nothing to do!
31768 Res = V1.getOperand(0);
31769 Res = DAG.getNode(X86ISD::VBROADCAST, DL, MaskVT, Res);
31770 return DAG.getBitcast(RootVT, Res);
31771 }
31772 if (Subtarget.hasAVX2()) {
31773 if (Depth == 1 && Root.getOpcode() == X86ISD::VBROADCAST)
31774 return SDValue(); // Nothing to do!
31775 Res = DAG.getBitcast(MaskVT, V1);
31776 Res = DAG.getNode(X86ISD::VBROADCAST, DL, MaskVT, Res);
31777 return DAG.getBitcast(RootVT, Res);
31778 }
31779 }
31780 }
31781
31782 SDValue NewV1 = V1; // Save operand in case early exit happens.
31783 if (matchUnaryShuffle(MaskVT, Mask, AllowFloatDomain, AllowIntDomain, NewV1,
31784 DL, DAG, Subtarget, Shuffle, ShuffleSrcVT,
31785 ShuffleVT) &&
31786 (!IsEVEXShuffle || (NumRootElts == ShuffleVT.getVectorNumElements()))) {
31787 if (Depth == 1 && Root.getOpcode() == Shuffle)
31788 return SDValue(); // Nothing to do!
31789 Res = DAG.getBitcast(ShuffleSrcVT, NewV1);
31790 Res = DAG.getNode(Shuffle, DL, ShuffleVT, Res);
31791 return DAG.getBitcast(RootVT, Res);
31792 }
31793
31794 if (matchUnaryPermuteShuffle(MaskVT, Mask, Zeroable, AllowFloatDomain,
31795 AllowIntDomain, Subtarget, Shuffle, ShuffleVT,
31796 PermuteImm) &&
31797 (!IsEVEXShuffle || (NumRootElts == ShuffleVT.getVectorNumElements()))) {
31798 if (Depth == 1 && Root.getOpcode() == Shuffle)
31799 return SDValue(); // Nothing to do!
31800 Res = DAG.getBitcast(ShuffleVT, V1);
31801 Res = DAG.getNode(Shuffle, DL, ShuffleVT, Res,
31802 DAG.getConstant(PermuteImm, DL, MVT::i8));
31803 return DAG.getBitcast(RootVT, Res);
31804 }
31805 }
31806
31807 SDValue NewV1 = V1; // Save operands in case early exit happens.
31808 SDValue NewV2 = V2;
31809 if (matchBinaryShuffle(MaskVT, Mask, AllowFloatDomain, AllowIntDomain, NewV1,
31810 NewV2, DL, DAG, Subtarget, Shuffle, ShuffleSrcVT,
31811 ShuffleVT, UnaryShuffle) &&
31812 (!IsEVEXShuffle || (NumRootElts == ShuffleVT.getVectorNumElements()))) {
31813 if (Depth == 1 && Root.getOpcode() == Shuffle)
31814 return SDValue(); // Nothing to do!
31815 NewV1 = DAG.getBitcast(ShuffleSrcVT, NewV1);
31816 NewV2 = DAG.getBitcast(ShuffleSrcVT, NewV2);
31817 Res = DAG.getNode(Shuffle, DL, ShuffleVT, NewV1, NewV2);
31818 return DAG.getBitcast(RootVT, Res);
31819 }
31820
31821 NewV1 = V1; // Save operands in case early exit happens.
31822 NewV2 = V2;
31823 if (matchBinaryPermuteShuffle(
31824 MaskVT, Mask, Zeroable, AllowFloatDomain, AllowIntDomain, NewV1,
31825 NewV2, DL, DAG, Subtarget, Shuffle, ShuffleVT, PermuteImm) &&
31826 (!IsEVEXShuffle || (NumRootElts == ShuffleVT.getVectorNumElements()))) {
31827 if (Depth == 1 && Root.getOpcode() == Shuffle)
31828 return SDValue(); // Nothing to do!
31829 NewV1 = DAG.getBitcast(ShuffleVT, NewV1);
31830 NewV2 = DAG.getBitcast(ShuffleVT, NewV2);
31831 Res = DAG.getNode(Shuffle, DL, ShuffleVT, NewV1, NewV2,
31832 DAG.getConstant(PermuteImm, DL, MVT::i8));
31833 return DAG.getBitcast(RootVT, Res);
31834 }
31835
31836 // Typically from here on, we need an integer version of MaskVT.
31837 MVT IntMaskVT = MVT::getIntegerVT(MaskEltSizeInBits);
31838 IntMaskVT = MVT::getVectorVT(IntMaskVT, NumMaskElts);
31839
31840 // Annoyingly, SSE4A instructions don't map into the above match helpers.
31841 if (Subtarget.hasSSE4A() && AllowIntDomain && RootSizeInBits == 128) {
31842 uint64_t BitLen, BitIdx;
31843 if (matchShuffleAsEXTRQ(IntMaskVT, V1, V2, Mask, BitLen, BitIdx,
31844 Zeroable)) {
31845 if (Depth == 1 && Root.getOpcode() == X86ISD::EXTRQI)
31846 return SDValue(); // Nothing to do!
31847 V1 = DAG.getBitcast(IntMaskVT, V1);
31848 Res = DAG.getNode(X86ISD::EXTRQI, DL, IntMaskVT, V1,
31849 DAG.getConstant(BitLen, DL, MVT::i8),
31850 DAG.getConstant(BitIdx, DL, MVT::i8));
31851 return DAG.getBitcast(RootVT, Res);
31852 }
31853
31854 if (matchShuffleAsINSERTQ(IntMaskVT, V1, V2, Mask, BitLen, BitIdx)) {
31855 if (Depth == 1 && Root.getOpcode() == X86ISD::INSERTQI)
31856 return SDValue(); // Nothing to do!
31857 V1 = DAG.getBitcast(IntMaskVT, V1);
31858 V2 = DAG.getBitcast(IntMaskVT, V2);
31859 Res = DAG.getNode(X86ISD::INSERTQI, DL, IntMaskVT, V1, V2,
31860 DAG.getConstant(BitLen, DL, MVT::i8),
31861 DAG.getConstant(BitIdx, DL, MVT::i8));
31862 return DAG.getBitcast(RootVT, Res);
31863 }
31864 }
31865
31866 // Don't try to re-form single instruction chains under any circumstances now
31867 // that we've done encoding canonicalization for them.
31868 if (Depth < 2)
31869 return SDValue();
31870
31871 // Depth threshold above which we can efficiently use variable mask shuffles.
31872 int VariableShuffleDepth = Subtarget.hasFastVariableShuffle() ? 2 : 3;
31873 AllowVariableMask &= (Depth >= VariableShuffleDepth) || HasVariableMask;
31874
31875 bool MaskContainsZeros =
31876 any_of(Mask, [](int M) { return M == SM_SentinelZero; });
31877
31878 if (is128BitLaneCrossingShuffleMask(MaskVT, Mask)) {
31879 // If we have a single input lane-crossing shuffle then lower to VPERMV.
31880 if (UnaryShuffle && AllowVariableMask && !MaskContainsZeros &&
31881 ((Subtarget.hasAVX2() &&
31882 (MaskVT == MVT::v8f32 || MaskVT == MVT::v8i32)) ||
31883 (Subtarget.hasAVX512() &&
31884 (MaskVT == MVT::v8f64 || MaskVT == MVT::v8i64 ||
31885 MaskVT == MVT::v16f32 || MaskVT == MVT::v16i32)) ||
31886 (Subtarget.hasBWI() && MaskVT == MVT::v32i16) ||
31887 (Subtarget.hasBWI() && Subtarget.hasVLX() && MaskVT == MVT::v16i16) ||
31888 (Subtarget.hasVBMI() && MaskVT == MVT::v64i8) ||
31889 (Subtarget.hasVBMI() && Subtarget.hasVLX() && MaskVT == MVT::v32i8))) {
31890 SDValue VPermMask = getConstVector(Mask, IntMaskVT, DAG, DL, true);
31891 Res = DAG.getBitcast(MaskVT, V1);
31892 Res = DAG.getNode(X86ISD::VPERMV, DL, MaskVT, VPermMask, Res);
31893 return DAG.getBitcast(RootVT, Res);
31894 }
31895
31896 // Lower a unary+zero lane-crossing shuffle as VPERMV3 with a zero
31897 // vector as the second source.
31898 if (UnaryShuffle && AllowVariableMask &&
31899 ((Subtarget.hasAVX512() &&
31900 (MaskVT == MVT::v8f64 || MaskVT == MVT::v8i64 ||
31901 MaskVT == MVT::v16f32 || MaskVT == MVT::v16i32)) ||
31902 (Subtarget.hasVLX() &&
31903 (MaskVT == MVT::v4f64 || MaskVT == MVT::v4i64 ||
31904 MaskVT == MVT::v8f32 || MaskVT == MVT::v8i32)) ||
31905 (Subtarget.hasBWI() && MaskVT == MVT::v32i16) ||
31906 (Subtarget.hasBWI() && Subtarget.hasVLX() && MaskVT == MVT::v16i16) ||
31907 (Subtarget.hasVBMI() && MaskVT == MVT::v64i8) ||
31908 (Subtarget.hasVBMI() && Subtarget.hasVLX() && MaskVT == MVT::v32i8))) {
31909 // Adjust shuffle mask - replace SM_SentinelZero with second source index.
31910 for (unsigned i = 0; i != NumMaskElts; ++i)
31911 if (Mask[i] == SM_SentinelZero)
31912 Mask[i] = NumMaskElts + i;
31913
31914 SDValue VPermMask = getConstVector(Mask, IntMaskVT, DAG, DL, true);
31915 Res = DAG.getBitcast(MaskVT, V1);
31916 SDValue Zero = getZeroVector(MaskVT, Subtarget, DAG, DL);
31917 Res = DAG.getNode(X86ISD::VPERMV3, DL, MaskVT, Res, VPermMask, Zero);
31918 return DAG.getBitcast(RootVT, Res);
31919 }
31920
31921 // If we have a dual input lane-crossing shuffle then lower to VPERMV3.
31922 if (AllowVariableMask && !MaskContainsZeros &&
31923 ((Subtarget.hasAVX512() &&
31924 (MaskVT == MVT::v8f64 || MaskVT == MVT::v8i64 ||
31925 MaskVT == MVT::v16f32 || MaskVT == MVT::v16i32)) ||
31926 (Subtarget.hasVLX() &&
31927 (MaskVT == MVT::v4f64 || MaskVT == MVT::v4i64 ||
31928 MaskVT == MVT::v8f32 || MaskVT == MVT::v8i32)) ||
31929 (Subtarget.hasBWI() && MaskVT == MVT::v32i16) ||
31930 (Subtarget.hasBWI() && Subtarget.hasVLX() && MaskVT == MVT::v16i16) ||
31931 (Subtarget.hasVBMI() && MaskVT == MVT::v64i8) ||
31932 (Subtarget.hasVBMI() && Subtarget.hasVLX() && MaskVT == MVT::v32i8))) {
31933 SDValue VPermMask = getConstVector(Mask, IntMaskVT, DAG, DL, true);
31934 V1 = DAG.getBitcast(MaskVT, V1);
31935 V2 = DAG.getBitcast(MaskVT, V2);
31936 Res = DAG.getNode(X86ISD::VPERMV3, DL, MaskVT, V1, VPermMask, V2);
31937 return DAG.getBitcast(RootVT, Res);
31938 }
31939 return SDValue();
31940 }
31941
31942 // See if we can combine a single input shuffle with zeros to a bit-mask,
31943 // which is much simpler than any shuffle.
31944 if (UnaryShuffle && MaskContainsZeros && AllowVariableMask &&
31945 isSequentialOrUndefOrZeroInRange(Mask, 0, NumMaskElts, 0) &&
31946 DAG.getTargetLoweringInfo().isTypeLegal(MaskVT)) {
31947 APInt Zero = APInt::getNullValue(MaskEltSizeInBits);
31948 APInt AllOnes = APInt::getAllOnesValue(MaskEltSizeInBits);
31949 APInt UndefElts(NumMaskElts, 0);
31950 SmallVector<APInt, 64> EltBits(NumMaskElts, Zero);
31951 for (unsigned i = 0; i != NumMaskElts; ++i) {
31952 int M = Mask[i];
31953 if (M == SM_SentinelUndef) {
31954 UndefElts.setBit(i);
31955 continue;
31956 }
31957 if (M == SM_SentinelZero)
31958 continue;
31959 EltBits[i] = AllOnes;
31960 }
31961 SDValue BitMask = getConstVector(EltBits, UndefElts, MaskVT, DAG, DL);
31962 Res = DAG.getBitcast(MaskVT, V1);
31963 unsigned AndOpcode =
31964 FloatDomain ? unsigned(X86ISD::FAND) : unsigned(ISD::AND);
31965 Res = DAG.getNode(AndOpcode, DL, MaskVT, Res, BitMask);
31966 return DAG.getBitcast(RootVT, Res);
31967 }
31968
31969 // If we have a single input shuffle with different shuffle patterns in the
31970 // the 128-bit lanes use the variable mask to VPERMILPS.
31971 // TODO Combine other mask types at higher depths.
31972 if (UnaryShuffle && AllowVariableMask && !MaskContainsZeros &&
31973 ((MaskVT == MVT::v8f32 && Subtarget.hasAVX()) ||
31974 (MaskVT == MVT::v16f32 && Subtarget.hasAVX512()))) {
31975 SmallVector<SDValue, 16> VPermIdx;
31976 for (int M : Mask) {
31977 SDValue Idx =
31978 M < 0 ? DAG.getUNDEF(MVT::i32) : DAG.getConstant(M % 4, DL, MVT::i32);
31979 VPermIdx.push_back(Idx);
31980 }
31981 SDValue VPermMask = DAG.getBuildVector(IntMaskVT, DL, VPermIdx);
31982 Res = DAG.getBitcast(MaskVT, V1);
31983 Res = DAG.getNode(X86ISD::VPERMILPV, DL, MaskVT, Res, VPermMask);
31984 return DAG.getBitcast(RootVT, Res);
31985 }
31986
31987 // With XOP, binary shuffles of 128/256-bit floating point vectors can combine
31988 // to VPERMIL2PD/VPERMIL2PS.
31989 if (AllowVariableMask && Subtarget.hasXOP() &&
31990 (MaskVT == MVT::v2f64 || MaskVT == MVT::v4f64 || MaskVT == MVT::v4f32 ||
31991 MaskVT == MVT::v8f32)) {
31992 // VPERMIL2 Operation.
31993 // Bits[3] - Match Bit.
31994 // Bits[2:1] - (Per Lane) PD Shuffle Mask.
31995 // Bits[2:0] - (Per Lane) PS Shuffle Mask.
31996 unsigned NumLanes = MaskVT.getSizeInBits() / 128;
31997 unsigned NumEltsPerLane = NumMaskElts / NumLanes;
31998 SmallVector<int, 8> VPerm2Idx;
31999 unsigned M2ZImm = 0;
32000 for (int M : Mask) {
32001 if (M == SM_SentinelUndef) {
32002 VPerm2Idx.push_back(-1);
32003 continue;
32004 }
32005 if (M == SM_SentinelZero) {
32006 M2ZImm = 2;
32007 VPerm2Idx.push_back(8);
32008 continue;
32009 }
32010 int Index = (M % NumEltsPerLane) + ((M / NumMaskElts) * NumEltsPerLane);
32011 Index = (MaskVT.getScalarSizeInBits() == 64 ? Index << 1 : Index);
32012 VPerm2Idx.push_back(Index);
32013 }
32014 V1 = DAG.getBitcast(MaskVT, V1);
32015 V2 = DAG.getBitcast(MaskVT, V2);
32016 SDValue VPerm2MaskOp = getConstVector(VPerm2Idx, IntMaskVT, DAG, DL, true);
32017 Res = DAG.getNode(X86ISD::VPERMIL2, DL, MaskVT, V1, V2, VPerm2MaskOp,
32018 DAG.getConstant(M2ZImm, DL, MVT::i8));
32019 return DAG.getBitcast(RootVT, Res);
32020 }
32021
32022 // If we have 3 or more shuffle instructions or a chain involving a variable
32023 // mask, we can replace them with a single PSHUFB instruction profitably.
32024 // Intel's manuals suggest only using PSHUFB if doing so replacing 5
32025 // instructions, but in practice PSHUFB tends to be *very* fast so we're
32026 // more aggressive.
32027 if (UnaryShuffle && AllowVariableMask &&
32028 ((RootVT.is128BitVector() && Subtarget.hasSSSE3()) ||
32029 (RootVT.is256BitVector() && Subtarget.hasAVX2()) ||
32030 (RootVT.is512BitVector() && Subtarget.hasBWI()))) {
32031 SmallVector<SDValue, 16> PSHUFBMask;
32032 int NumBytes = RootVT.getSizeInBits() / 8;
32033 int Ratio = NumBytes / NumMaskElts;
32034 for (int i = 0; i < NumBytes; ++i) {
32035 int M = Mask[i / Ratio];
32036 if (M == SM_SentinelUndef) {
32037 PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
32038 continue;
32039 }
32040 if (M == SM_SentinelZero) {
32041 PSHUFBMask.push_back(DAG.getConstant(255, DL, MVT::i8));
32042 continue;
32043 }
32044 M = Ratio * M + i % Ratio;
32045 assert((M / 16) == (i / 16) && "Lane crossing detected")(((M / 16) == (i / 16) && "Lane crossing detected") ?
static_cast<void> (0) : __assert_fail ("(M / 16) == (i / 16) && \"Lane crossing detected\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 32045, __PRETTY_FUNCTION__))
;
32046 PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
32047 }
32048 MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
32049 Res = DAG.getBitcast(ByteVT, V1);
32050 SDValue PSHUFBMaskOp = DAG.getBuildVector(ByteVT, DL, PSHUFBMask);
32051 Res = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Res, PSHUFBMaskOp);
32052 return DAG.getBitcast(RootVT, Res);
32053 }
32054
32055 // With XOP, if we have a 128-bit binary input shuffle we can always combine
32056 // to VPPERM. We match the depth requirement of PSHUFB - VPPERM is never
32057 // slower than PSHUFB on targets that support both.
32058 if (AllowVariableMask && RootVT.is128BitVector() && Subtarget.hasXOP()) {
32059 // VPPERM Mask Operation
32060 // Bits[4:0] - Byte Index (0 - 31)
32061 // Bits[7:5] - Permute Operation (0 - Source byte, 4 - ZERO)
32062 SmallVector<SDValue, 16> VPPERMMask;
32063 int NumBytes = 16;
32064 int Ratio = NumBytes / NumMaskElts;
32065 for (int i = 0; i < NumBytes; ++i) {
32066 int M = Mask[i / Ratio];
32067 if (M == SM_SentinelUndef) {
32068 VPPERMMask.push_back(DAG.getUNDEF(MVT::i8));
32069 continue;
32070 }
32071 if (M == SM_SentinelZero) {
32072 VPPERMMask.push_back(DAG.getConstant(128, DL, MVT::i8));
32073 continue;
32074 }
32075 M = Ratio * M + i % Ratio;
32076 VPPERMMask.push_back(DAG.getConstant(M, DL, MVT::i8));
32077 }
32078 MVT ByteVT = MVT::v16i8;
32079 V1 = DAG.getBitcast(ByteVT, V1);
32080 V2 = DAG.getBitcast(ByteVT, V2);
32081 SDValue VPPERMMaskOp = DAG.getBuildVector(ByteVT, DL, VPPERMMask);
32082 Res = DAG.getNode(X86ISD::VPPERM, DL, ByteVT, V1, V2, VPPERMMaskOp);
32083 return DAG.getBitcast(RootVT, Res);
32084 }
32085
32086 // If that failed and both inputs are extracted from the same source then
32087 // try to combine as an unary shuffle with the larger type.
32088 if (!UnaryShuffle && V1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
32089 V2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
32090 isa<ConstantSDNode>(V1.getOperand(1)) &&
32091 isa<ConstantSDNode>(V2.getOperand(1))) {
32092 SDValue Src1 = V1.getOperand(0);
32093 SDValue Src2 = V2.getOperand(0);
32094 if (Src1 == Src2) {
32095 unsigned Offset1 = V1.getConstantOperandVal(1);
32096 unsigned Offset2 = V2.getConstantOperandVal(1);
32097 assert(((Offset1 % VT1.getVectorNumElements()) == 0 ||((((Offset1 % VT1.getVectorNumElements()) == 0 || (Offset2 % VT2
.getVectorNumElements()) == 0 || (Src1.getValueSizeInBits() %
RootSizeInBits) == 0) && "Unexpected subvector extraction"
) ? static_cast<void> (0) : __assert_fail ("((Offset1 % VT1.getVectorNumElements()) == 0 || (Offset2 % VT2.getVectorNumElements()) == 0 || (Src1.getValueSizeInBits() % RootSizeInBits) == 0) && \"Unexpected subvector extraction\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 32100, __PRETTY_FUNCTION__))
32098 (Offset2 % VT2.getVectorNumElements()) == 0 ||((((Offset1 % VT1.getVectorNumElements()) == 0 || (Offset2 % VT2
.getVectorNumElements()) == 0 || (Src1.getValueSizeInBits() %
RootSizeInBits) == 0) && "Unexpected subvector extraction"
) ? static_cast<void> (0) : __assert_fail ("((Offset1 % VT1.getVectorNumElements()) == 0 || (Offset2 % VT2.getVectorNumElements()) == 0 || (Src1.getValueSizeInBits() % RootSizeInBits) == 0) && \"Unexpected subvector extraction\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 32100, __PRETTY_FUNCTION__))
32099 (Src1.getValueSizeInBits() % RootSizeInBits) == 0) &&((((Offset1 % VT1.getVectorNumElements()) == 0 || (Offset2 % VT2
.getVectorNumElements()) == 0 || (Src1.getValueSizeInBits() %
RootSizeInBits) == 0) && "Unexpected subvector extraction"
) ? static_cast<void> (0) : __assert_fail ("((Offset1 % VT1.getVectorNumElements()) == 0 || (Offset2 % VT2.getVectorNumElements()) == 0 || (Src1.getValueSizeInBits() % RootSizeInBits) == 0) && \"Unexpected subvector extraction\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 32100, __PRETTY_FUNCTION__))
32100 "Unexpected subvector extraction")((((Offset1 % VT1.getVectorNumElements()) == 0 || (Offset2 % VT2
.getVectorNumElements()) == 0 || (Src1.getValueSizeInBits() %
RootSizeInBits) == 0) && "Unexpected subvector extraction"
) ? static_cast<void> (0) : __assert_fail ("((Offset1 % VT1.getVectorNumElements()) == 0 || (Offset2 % VT2.getVectorNumElements()) == 0 || (Src1.getValueSizeInBits() % RootSizeInBits) == 0) && \"Unexpected subvector extraction\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 32100, __PRETTY_FUNCTION__))
;
32101 // Convert extraction indices to mask size.
32102 Offset1 /= VT1.getVectorNumElements();
32103 Offset2 /= VT2.getVectorNumElements();
32104 Offset1 *= NumMaskElts;
32105 Offset2 *= NumMaskElts;
32106
32107 // Create new mask for larger type.
32108 SmallVector<int, 64> NewMask(Mask);
32109 for (int &M : NewMask) {
32110 if (M < 0)
32111 continue;
32112 if (M < (int)NumMaskElts)
32113 M += Offset1;
32114 else
32115 M = (M - NumMaskElts) + Offset2;
32116 }
32117 unsigned Scale = Src1.getValueSizeInBits() / RootSizeInBits;
32118 NewMask.append((Scale - 1) * NumMaskElts, SM_SentinelUndef);
32119
32120 SDValue NewInputs[] = {Src1};
32121 if (SDValue Res = combineX86ShuffleChain(
32122 NewInputs, Src1, NewMask, Depth, HasVariableMask,
32123 AllowVariableMask, DAG, Subtarget)) {
32124 Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT1, Res,
32125 DAG.getIntPtrConstant(0, DL));
32126 return DAG.getBitcast(RootVT, Res);
32127 }
32128 }
32129 }
32130
32131 // If we have a dual input shuffle then lower to VPERMV3.
32132 if (!UnaryShuffle && AllowVariableMask && !MaskContainsZeros &&
32133 ((Subtarget.hasAVX512() &&
32134 (MaskVT == MVT::v8f64 || MaskVT == MVT::v8i64 ||
32135 MaskVT == MVT::v16f32 || MaskVT == MVT::v16i32)) ||
32136 (Subtarget.hasVLX() &&
32137 (MaskVT == MVT::v2f64 || MaskVT == MVT::v2i64 || MaskVT == MVT::v4f64 ||
32138 MaskVT == MVT::v4i64 || MaskVT == MVT::v4f32 || MaskVT == MVT::v4i32 ||
32139 MaskVT == MVT::v8f32 || MaskVT == MVT::v8i32)) ||
32140 (Subtarget.hasBWI() && MaskVT == MVT::v32i16) ||
32141 (Subtarget.hasBWI() && Subtarget.hasVLX() &&
32142 (MaskVT == MVT::v8i16 || MaskVT == MVT::v16i16)) ||
32143 (Subtarget.hasVBMI() && MaskVT == MVT::v64i8) ||
32144 (Subtarget.hasVBMI() && Subtarget.hasVLX() &&
32145 (MaskVT == MVT::v16i8 || MaskVT == MVT::v32i8)))) {
32146 SDValue VPermMask = getConstVector(Mask, IntMaskVT, DAG, DL, true);
32147 V1 = DAG.getBitcast(MaskVT, V1);
32148 V2 = DAG.getBitcast(MaskVT, V2);
32149 Res = DAG.getNode(X86ISD::VPERMV3, DL, MaskVT, V1, VPermMask, V2);
32150 return DAG.getBitcast(RootVT, Res);
32151 }
32152
32153 // Failed to find any combines.
32154 return SDValue();
32155}
32156
32157// Attempt to constant fold all of the constant source ops.
32158// Returns true if the entire shuffle is folded to a constant.
32159// TODO: Extend this to merge multiple constant Ops and update the mask.
32160static SDValue combineX86ShufflesConstants(ArrayRef<SDValue> Ops,
32161 ArrayRef<int> Mask, SDValue Root,
32162 bool HasVariableMask,
32163 SelectionDAG &DAG,
32164 const X86Subtarget &Subtarget) {
32165 MVT VT = Root.getSimpleValueType();
32166
32167 unsigned SizeInBits = VT.getSizeInBits();
32168 unsigned NumMaskElts = Mask.size();
32169 unsigned MaskSizeInBits = SizeInBits / NumMaskElts;
32170 unsigned NumOps = Ops.size();
32171
32172 // Extract constant bits from each source op.
32173 bool OneUseConstantOp = false;
32174 SmallVector<APInt, 16> UndefEltsOps(NumOps);
32175 SmallVector<SmallVector<APInt, 16>, 16> RawBitsOps(NumOps);
32176 for (unsigned i = 0; i != NumOps; ++i) {
32177 SDValue SrcOp = Ops[i];
32178 OneUseConstantOp |= SrcOp.hasOneUse();
32179 if (!getTargetConstantBitsFromNode(SrcOp, MaskSizeInBits, UndefEltsOps[i],
32180 RawBitsOps[i]))
32181 return SDValue();
32182 }
32183
32184 // Only fold if at least one of the constants is only used once or
32185 // the combined shuffle has included a variable mask shuffle, this
32186 // is to avoid constant pool bloat.
32187 if (!OneUseConstantOp && !HasVariableMask)
32188 return SDValue();
32189
32190 // Shuffle the constant bits according to the mask.
32191 APInt UndefElts(NumMaskElts, 0);
32192 APInt ZeroElts(NumMaskElts, 0);
32193 APInt ConstantElts(NumMaskElts, 0);
32194 SmallVector<APInt, 8> ConstantBitData(NumMaskElts,
32195 APInt::getNullValue(MaskSizeInBits));
32196 for (unsigned i = 0; i != NumMaskElts; ++i) {
32197 int M = Mask[i];
32198 if (M == SM_SentinelUndef) {
32199 UndefElts.setBit(i);
32200 continue;
32201 } else if (M == SM_SentinelZero) {
32202 ZeroElts.setBit(i);
32203 continue;
32204 }
32205 assert(0 <= M && M < (int)(NumMaskElts * NumOps))((0 <= M && M < (int)(NumMaskElts * NumOps)) ? static_cast
<void> (0) : __assert_fail ("0 <= M && M < (int)(NumMaskElts * NumOps)"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 32205, __PRETTY_FUNCTION__))
;
32206
32207 unsigned SrcOpIdx = (unsigned)M / NumMaskElts;
32208 unsigned SrcMaskIdx = (unsigned)M % NumMaskElts;
32209
32210 auto &SrcUndefElts = UndefEltsOps[SrcOpIdx];
32211 if (SrcUndefElts[SrcMaskIdx]) {
32212 UndefElts.setBit(i);
32213 continue;
32214 }
32215
32216 auto &SrcEltBits = RawBitsOps[SrcOpIdx];
32217 APInt &Bits = SrcEltBits[SrcMaskIdx];
32218 if (!Bits) {
32219 ZeroElts.setBit(i);
32220 continue;
32221 }
32222
32223 ConstantElts.setBit(i);
32224 ConstantBitData[i] = Bits;
32225 }
32226 assert((UndefElts | ZeroElts | ConstantElts).isAllOnesValue())(((UndefElts | ZeroElts | ConstantElts).isAllOnesValue()) ? static_cast
<void> (0) : __assert_fail ("(UndefElts | ZeroElts | ConstantElts).isAllOnesValue()"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 32226, __PRETTY_FUNCTION__))
;
32227
32228 // Create the constant data.
32229 MVT MaskSVT;
32230 if (VT.isFloatingPoint() && (MaskSizeInBits == 32 || MaskSizeInBits == 64))
32231 MaskSVT = MVT::getFloatingPointVT(MaskSizeInBits);
32232 else
32233 MaskSVT = MVT::getIntegerVT(MaskSizeInBits);
32234
32235 MVT MaskVT = MVT::getVectorVT(MaskSVT, NumMaskElts);
32236
32237 SDLoc DL(Root);
32238 SDValue CstOp = getConstVector(ConstantBitData, UndefElts, MaskVT, DAG, DL);
32239 return DAG.getBitcast(VT, CstOp);
32240}
32241
32242/// Fully generic combining of x86 shuffle instructions.
32243///
32244/// This should be the last combine run over the x86 shuffle instructions. Once
32245/// they have been fully optimized, this will recursively consider all chains
32246/// of single-use shuffle instructions, build a generic model of the cumulative
32247/// shuffle operation, and check for simpler instructions which implement this
32248/// operation. We use this primarily for two purposes:
32249///
32250/// 1) Collapse generic shuffles to specialized single instructions when
32251/// equivalent. In most cases, this is just an encoding size win, but
32252/// sometimes we will collapse multiple generic shuffles into a single
32253/// special-purpose shuffle.
32254/// 2) Look for sequences of shuffle instructions with 3 or more total
32255/// instructions, and replace them with the slightly more expensive SSSE3
32256/// PSHUFB instruction if available. We do this as the last combining step
32257/// to ensure we avoid using PSHUFB if we can implement the shuffle with
32258/// a suitable short sequence of other instructions. The PSHUFB will either
32259/// use a register or have to read from memory and so is slightly (but only
32260/// slightly) more expensive than the other shuffle instructions.
32261///
32262/// Because this is inherently a quadratic operation (for each shuffle in
32263/// a chain, we recurse up the chain), the depth is limited to 8 instructions.
32264/// This should never be an issue in practice as the shuffle lowering doesn't
32265/// produce sequences of more than 8 instructions.
32266///
32267/// FIXME: We will currently miss some cases where the redundant shuffling
32268/// would simplify under the threshold for PSHUFB formation because of
32269/// combine-ordering. To fix this, we should do the redundant instruction
32270/// combining in this recursive walk.
32271static SDValue combineX86ShufflesRecursively(
32272 ArrayRef<SDValue> SrcOps, int SrcOpIndex, SDValue Root,
32273 ArrayRef<int> RootMask, ArrayRef<const SDNode *> SrcNodes, unsigned Depth,
32274 bool HasVariableMask, bool AllowVariableMask, SelectionDAG &DAG,
32275 const X86Subtarget &Subtarget) {
32276 // Bound the depth of our recursive combine because this is ultimately
32277 // quadratic in nature.
32278 const unsigned MaxRecursionDepth = 8;
32279 if (Depth > MaxRecursionDepth)
32280 return SDValue();
32281
32282 // Directly rip through bitcasts to find the underlying operand.
32283 SDValue Op = SrcOps[SrcOpIndex];
32284 Op = peekThroughOneUseBitcasts(Op);
32285
32286 MVT VT = Op.getSimpleValueType();
32287 if (!VT.isVector())
32288 return SDValue(); // Bail if we hit a non-vector.
32289
32290 assert(Root.getSimpleValueType().isVector() &&((Root.getSimpleValueType().isVector() && "Shuffles operate on vector types!"
) ? static_cast<void> (0) : __assert_fail ("Root.getSimpleValueType().isVector() && \"Shuffles operate on vector types!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 32291, __PRETTY_FUNCTION__))
32291 "Shuffles operate on vector types!")((Root.getSimpleValueType().isVector() && "Shuffles operate on vector types!"
) ? static_cast<void> (0) : __assert_fail ("Root.getSimpleValueType().isVector() && \"Shuffles operate on vector types!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 32291, __PRETTY_FUNCTION__))
;
32292 assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&((VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits
() && "Can only combine shuffles of the same vector register size."
) ? static_cast<void> (0) : __assert_fail ("VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() && \"Can only combine shuffles of the same vector register size.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 32293, __PRETTY_FUNCTION__))
32293 "Can only combine shuffles of the same vector register size.")((VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits
() && "Can only combine shuffles of the same vector register size."
) ? static_cast<void> (0) : __assert_fail ("VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() && \"Can only combine shuffles of the same vector register size.\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 32293, __PRETTY_FUNCTION__))
;
32294
32295 // Extract target shuffle mask and resolve sentinels and inputs.
32296 SmallVector<int, 64> OpMask;
32297 SmallVector<SDValue, 2> OpInputs;
32298 if (!resolveTargetShuffleInputs(Op, OpInputs, OpMask, DAG))
32299 return SDValue();
32300
32301 // TODO - Add support for more than 2 inputs.
32302 if (2 < OpInputs.size())
32303 return SDValue();
32304
32305 // Add the inputs to the Ops list, avoiding duplicates.
32306 SmallVector<SDValue, 16> Ops(SrcOps.begin(), SrcOps.end());
32307
32308 auto AddOp = [&Ops](SDValue Input, int InsertionPoint) -> int {
32309 // Attempt to find an existing match.
32310 SDValue InputBC = peekThroughBitcasts(Input);
32311 for (int i = 0, e = Ops.size(); i < e; ++i)
32312 if (InputBC == peekThroughBitcasts(Ops[i]))
32313 return i;
32314 // Match failed - should we replace an existing Op?
32315 if (InsertionPoint >= 0) {
32316 Ops[InsertionPoint] = Input;
32317 return InsertionPoint;
32318 }
32319 // Add to the end of the Ops list.
32320 Ops.push_back(Input);
32321 return Ops.size() - 1;
32322 };
32323
32324 SmallVector<int, 2> OpInputIdx;
32325 for (SDValue OpInput : OpInputs)
32326 OpInputIdx.push_back(AddOp(OpInput, OpInputIdx.empty() ? SrcOpIndex : -1));
32327
32328 assert(((RootMask.size() > OpMask.size() &&((((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."
) ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 32333, __PRETTY_FUNCTION__))
32329 RootMask.size() % OpMask.size() == 0) ||((((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."
) ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 32333, __PRETTY_FUNCTION__))
32330 (OpMask.size() > RootMask.size() &&((((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."
) ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 32333, __PRETTY_FUNCTION__))
32331 OpMask.size() % RootMask.size() == 0) ||((((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."
) ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 32333, __PRETTY_FUNCTION__))
32332 OpMask.size() == RootMask.size()) &&((((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."
) ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 32333, __PRETTY_FUNCTION__))
32333 "The smaller number of elements must divide the larger.")((((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."
) ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 32333, __PRETTY_FUNCTION__))
;
32334
32335 // This function can be performance-critical, so we rely on the power-of-2
32336 // knowledge that we have about the mask sizes to replace div/rem ops with
32337 // bit-masks and shifts.
32338 assert(isPowerOf2_32(RootMask.size()) && "Non-power-of-2 shuffle mask sizes")((isPowerOf2_32(RootMask.size()) && "Non-power-of-2 shuffle mask sizes"
) ? static_cast<void> (0) : __assert_fail ("isPowerOf2_32(RootMask.size()) && \"Non-power-of-2 shuffle mask sizes\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 32338, __PRETTY_FUNCTION__))
;
32339 assert(isPowerOf2_32(OpMask.size()) && "Non-power-of-2 shuffle mask sizes")((isPowerOf2_32(OpMask.size()) && "Non-power-of-2 shuffle mask sizes"
) ? static_cast<void> (0) : __assert_fail ("isPowerOf2_32(OpMask.size()) && \"Non-power-of-2 shuffle mask sizes\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 32339, __PRETTY_FUNCTION__))
;
32340 unsigned RootMaskSizeLog2 = countTrailingZeros(RootMask.size());
32341 unsigned OpMaskSizeLog2 = countTrailingZeros(OpMask.size());
32342
32343 unsigned MaskWidth = std::max<unsigned>(OpMask.size(), RootMask.size());
32344 unsigned RootRatio = std::max<unsigned>(1, OpMask.size() >> RootMaskSizeLog2);
32345 unsigned OpRatio = std::max<unsigned>(1, RootMask.size() >> OpMaskSizeLog2);
32346 assert((RootRatio == 1 || OpRatio == 1) &&(((RootRatio == 1 || OpRatio == 1) && "Must not have a ratio for both incoming and op masks!"
) ? static_cast<void> (0) : __assert_fail ("(RootRatio == 1 || OpRatio == 1) && \"Must not have a ratio for both incoming and op masks!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 32347, __PRETTY_FUNCTION__))
32347 "Must not have a ratio for both incoming and op masks!")(((RootRatio == 1 || OpRatio == 1) && "Must not have a ratio for both incoming and op masks!"
) ? static_cast<void> (0) : __assert_fail ("(RootRatio == 1 || OpRatio == 1) && \"Must not have a ratio for both incoming and op masks!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 32347, __PRETTY_FUNCTION__))
;
32348
32349 assert(isPowerOf2_32(MaskWidth) && "Non-power-of-2 shuffle mask sizes")((isPowerOf2_32(MaskWidth) && "Non-power-of-2 shuffle mask sizes"
) ? static_cast<void> (0) : __assert_fail ("isPowerOf2_32(MaskWidth) && \"Non-power-of-2 shuffle mask sizes\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 32349, __PRETTY_FUNCTION__))
;
32350 assert(isPowerOf2_32(RootRatio) && "Non-power-of-2 shuffle mask sizes")((isPowerOf2_32(RootRatio) && "Non-power-of-2 shuffle mask sizes"
) ? static_cast<void> (0) : __assert_fail ("isPowerOf2_32(RootRatio) && \"Non-power-of-2 shuffle mask sizes\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 32350, __PRETTY_FUNCTION__))
;
32351 assert(isPowerOf2_32(OpRatio) && "Non-power-of-2 shuffle mask sizes")((isPowerOf2_32(OpRatio) && "Non-power-of-2 shuffle mask sizes"
) ? static_cast<void> (0) : __assert_fail ("isPowerOf2_32(OpRatio) && \"Non-power-of-2 shuffle mask sizes\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 32351, __PRETTY_FUNCTION__))
;
32352 unsigned RootRatioLog2 = countTrailingZeros(RootRatio);
32353 unsigned OpRatioLog2 = countTrailingZeros(OpRatio);
32354
32355 SmallVector<int, 64> Mask(MaskWidth, SM_SentinelUndef);
32356
32357 // Merge this shuffle operation's mask into our accumulated mask. Note that
32358 // this shuffle's mask will be the first applied to the input, followed by the
32359 // root mask to get us all the way to the root value arrangement. The reason
32360 // for this order is that we are recursing up the operation chain.
32361 for (unsigned i = 0; i < MaskWidth; ++i) {
32362 unsigned RootIdx = i >> RootRatioLog2;
32363 if (RootMask[RootIdx] < 0) {
32364 // This is a zero or undef lane, we're done.
32365 Mask[i] = RootMask[RootIdx];
32366 continue;
32367 }
32368
32369 unsigned RootMaskedIdx =
32370 RootRatio == 1
32371 ? RootMask[RootIdx]
32372 : (RootMask[RootIdx] << RootRatioLog2) + (i & (RootRatio - 1));
32373
32374 // Just insert the scaled root mask value if it references an input other
32375 // than the SrcOp we're currently inserting.
32376 if ((RootMaskedIdx < (SrcOpIndex * MaskWidth)) ||
32377 (((SrcOpIndex + 1) * MaskWidth) <= RootMaskedIdx)) {
32378 Mask[i] = RootMaskedIdx;
32379 continue;
32380 }
32381
32382 RootMaskedIdx = RootMaskedIdx & (MaskWidth - 1);
32383 unsigned OpIdx = RootMaskedIdx >> OpRatioLog2;
32384 if (OpMask[OpIdx] < 0) {
32385 // The incoming lanes are zero or undef, it doesn't matter which ones we
32386 // are using.
32387 Mask[i] = OpMask[OpIdx];
32388 continue;
32389 }
32390
32391 // Ok, we have non-zero lanes, map them through to one of the Op's inputs.
32392 unsigned OpMaskedIdx =
32393 OpRatio == 1
32394 ? OpMask[OpIdx]
32395 : (OpMask[OpIdx] << OpRatioLog2) + (RootMaskedIdx & (OpRatio - 1));
32396
32397 OpMaskedIdx = OpMaskedIdx & (MaskWidth - 1);
32398 int InputIdx = OpMask[OpIdx] / (int)OpMask.size();
32399 assert(0 <= OpInputIdx[InputIdx] && "Unknown target shuffle input")((0 <= OpInputIdx[InputIdx] && "Unknown target shuffle input"
) ? static_cast<void> (0) : __assert_fail ("0 <= OpInputIdx[InputIdx] && \"Unknown target shuffle input\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 32399, __PRETTY_FUNCTION__))
;
32400 OpMaskedIdx += OpInputIdx[InputIdx] * MaskWidth;
32401
32402 Mask[i] = OpMaskedIdx;
32403 }
32404
32405 // Handle the all undef/zero cases early.
32406 if (all_of(Mask, [](int Idx) { return Idx == SM_SentinelUndef; }))
32407 return DAG.getUNDEF(Root.getValueType());
32408
32409 // TODO - should we handle the mixed zero/undef case as well? Just returning
32410 // a zero mask will lose information on undef elements possibly reducing
32411 // future combine possibilities.
32412 if (all_of(Mask, [](int Idx) { return Idx < 0; }))
32413 return getZeroVector(Root.getSimpleValueType(), Subtarget, DAG,
32414 SDLoc(Root));
32415
32416 // Remove unused shuffle source ops.
32417 resolveTargetShuffleInputsAndMask(Ops, Mask);
32418 assert(!Ops.empty() && "Shuffle with no inputs detected")((!Ops.empty() && "Shuffle with no inputs detected") ?
static_cast<void> (0) : __assert_fail ("!Ops.empty() && \"Shuffle with no inputs detected\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 32418, __PRETTY_FUNCTION__))
;
32419
32420 HasVariableMask |= isTargetShuffleVariableMask(Op.getOpcode());
32421
32422 // Update the list of shuffle nodes that have been combined so far.
32423 SmallVector<const SDNode *, 16> CombinedNodes(SrcNodes.begin(),
32424 SrcNodes.end());
32425 CombinedNodes.push_back(Op.getNode());
32426
32427 // See if we can recurse into each shuffle source op (if it's a target
32428 // shuffle). The source op should only be generally combined if it either has
32429 // a single use (i.e. current Op) or all its users have already been combined,
32430 // if not then we can still combine but should prevent generation of variable
32431 // shuffles to avoid constant pool bloat.
32432 // Don't recurse if we already have more source ops than we can combine in
32433 // the remaining recursion depth.
32434 if (Ops.size() < (MaxRecursionDepth - Depth)) {
32435 for (int i = 0, e = Ops.size(); i < e; ++i) {
32436 bool AllowVar = false;
32437 if (Ops[i].getNode()->hasOneUse() ||
32438 SDNode::areOnlyUsersOf(CombinedNodes, Ops[i].getNode()))
32439 AllowVar = AllowVariableMask;
32440 if (SDValue Res = combineX86ShufflesRecursively(
32441 Ops, i, Root, Mask, CombinedNodes, Depth + 1, HasVariableMask,
32442 AllowVar, DAG, Subtarget))
32443 return Res;
32444 }
32445 }
32446
32447 // Attempt to constant fold all of the constant source ops.
32448 if (SDValue Cst = combineX86ShufflesConstants(
32449 Ops, Mask, Root, HasVariableMask, DAG, Subtarget))
32450 return Cst;
32451
32452 // We can only combine unary and binary shuffle mask cases.
32453 if (Ops.size() > 2)
32454 return SDValue();
32455
32456 // Minor canonicalization of the accumulated shuffle mask to make it easier
32457 // to match below. All this does is detect masks with sequential pairs of
32458 // elements, and shrink them to the half-width mask. It does this in a loop
32459 // so it will reduce the size of the mask to the minimal width mask which
32460 // performs an equivalent shuffle.
32461 SmallVector<int, 64> WidenedMask;
32462 while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
32463 Mask = std::move(WidenedMask);
32464 }
32465
32466 // Canonicalization of binary shuffle masks to improve pattern matching by
32467 // commuting the inputs.
32468 if (Ops.size() == 2 && canonicalizeShuffleMaskWithCommute(Mask)) {
32469 ShuffleVectorSDNode::commuteMask(Mask);
32470 std::swap(Ops[0], Ops[1]);
32471 }
32472
32473 // Finally, try to combine into a single shuffle instruction.
32474 return combineX86ShuffleChain(Ops, Root, Mask, Depth, HasVariableMask,
32475 AllowVariableMask, DAG, Subtarget);
32476}
32477
32478/// Helper entry wrapper to combineX86ShufflesRecursively.
32479static SDValue combineX86ShufflesRecursively(SDValue Op, SelectionDAG &DAG,
32480 const X86Subtarget &Subtarget) {
32481 return combineX86ShufflesRecursively({Op}, 0, Op, {0}, {}, /*Depth*/ 1,
32482 /*HasVarMask*/ false,
32483 /*AllowVarMask*/ true, DAG, Subtarget);
32484}
32485
32486/// Get the PSHUF-style mask from PSHUF node.
32487///
32488/// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
32489/// PSHUF-style masks that can be reused with such instructions.
32490static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
32491 MVT VT = N.getSimpleValueType();
32492 SmallVector<int, 4> Mask;
32493 SmallVector<SDValue, 2> Ops;
32494 bool IsUnary;
32495 bool HaveMask =
32496 getTargetShuffleMask(N.getNode(), VT, false, Ops, Mask, IsUnary);
32497 (void)HaveMask;
32498 assert(HaveMask)((HaveMask) ? static_cast<void> (0) : __assert_fail ("HaveMask"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 32498, __PRETTY_FUNCTION__))
;
32499
32500 // If we have more than 128-bits, only the low 128-bits of shuffle mask
32501 // matter. Check that the upper masks are repeats and remove them.
32502 if (VT.getSizeInBits() > 128) {
32503 int LaneElts = 128 / VT.getScalarSizeInBits();
32504#ifndef NDEBUG
32505 for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
32506 for (int j = 0; j < LaneElts; ++j)
32507 assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&((Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
"Mask doesn't repeat in high 128-bit lanes!") ? static_cast<
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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 32508, __PRETTY_FUNCTION__))
32508 "Mask doesn't repeat in high 128-bit lanes!")((Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
"Mask doesn't repeat in high 128-bit lanes!") ? static_cast<
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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 32508, __PRETTY_FUNCTION__))
;
32509#endif
32510 Mask.resize(LaneElts);
32511 }
32512
32513 switch (N.getOpcode()) {
32514 case X86ISD::PSHUFD:
32515 return Mask;
32516 case X86ISD::PSHUFLW:
32517 Mask.resize(4);
32518 return Mask;
32519 case X86ISD::PSHUFHW:
32520 Mask.erase(Mask.begin(), Mask.begin() + 4);
32521 for (int &M : Mask)
32522 M -= 4;
32523 return Mask;
32524 default:
32525 llvm_unreachable("No valid shuffle instruction found!")::llvm::llvm_unreachable_internal("No valid shuffle instruction found!"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 32525)
;
32526 }
32527}
32528
32529/// Search for a combinable shuffle across a chain ending in pshufd.
32530///
32531/// We walk up the chain and look for a combinable shuffle, skipping over
32532/// shuffles that we could hoist this shuffle's transformation past without
32533/// altering anything.
32534static SDValue
32535combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
32536 SelectionDAG &DAG) {
32537 assert(N.getOpcode() == X86ISD::PSHUFD &&((N.getOpcode() == X86ISD::PSHUFD && "Called with something other than an x86 128-bit half shuffle!"
) ? static_cast<void> (0) : __assert_fail ("N.getOpcode() == X86ISD::PSHUFD && \"Called with something other than an x86 128-bit half shuffle!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 32538, __PRETTY_FUNCTION__))
32538 "Called with something other than an x86 128-bit half shuffle!")((N.getOpcode() == X86ISD::PSHUFD && "Called with something other than an x86 128-bit half shuffle!"
) ? static_cast<void> (0) : __assert_fail ("N.getOpcode() == X86ISD::PSHUFD && \"Called with something other than an x86 128-bit half shuffle!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 32538, __PRETTY_FUNCTION__))
;
32539 SDLoc DL(N);
32540
32541 // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
32542 // of the shuffles in the chain so that we can form a fresh chain to replace
32543 // this one.
32544 SmallVector<SDValue, 8> Chain;
32545 SDValue V = N.getOperand(0);
32546 for (; V.hasOneUse(); V = V.getOperand(0)) {
32547 switch (V.getOpcode()) {
32548 default:
32549 return SDValue(); // Nothing combined!
32550
32551 case ISD::BITCAST:
32552 // Skip bitcasts as we always know the type for the target specific
32553 // instructions.
32554 continue;
32555
32556 case X86ISD::PSHUFD:
32557 // Found another dword shuffle.
32558 break;
32559
32560 case X86ISD::PSHUFLW:
32561 // Check that the low words (being shuffled) are the identity in the
32562 // dword shuffle, and the high words are self-contained.
32563 if (Mask[0] != 0 || Mask[1] != 1 ||
32564 !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
32565 return SDValue();
32566
32567 Chain.push_back(V);
32568 continue;
32569
32570 case X86ISD::PSHUFHW:
32571 // Check that the high words (being shuffled) are the identity in the
32572 // dword shuffle, and the low words are self-contained.
32573 if (Mask[2] != 2 || Mask[3] != 3 ||
32574 !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
32575 return SDValue();
32576
32577 Chain.push_back(V);
32578 continue;
32579
32580 case X86ISD::UNPCKL:
32581 case X86ISD::UNPCKH:
32582 // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
32583 // shuffle into a preceding word shuffle.
32584 if (V.getSimpleValueType().getVectorElementType() != MVT::i8 &&
32585 V.getSimpleValueType().getVectorElementType() != MVT::i16)
32586 return SDValue();
32587
32588 // Search for a half-shuffle which we can combine with.
32589 unsigned CombineOp =
32590 V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
32591 if (V.getOperand(0) != V.getOperand(1) ||
32592 !V->isOnlyUserOf(V.getOperand(0).getNode()))
32593 return SDValue();
32594 Chain.push_back(V);
32595 V = V.getOperand(0);
32596 do {
32597 switch (V.getOpcode()) {
32598 default:
32599 return SDValue(); // Nothing to combine.
32600
32601 case X86ISD::PSHUFLW:
32602 case X86ISD::PSHUFHW:
32603 if (V.getOpcode() == CombineOp)
32604 break;
32605
32606 Chain.push_back(V);
32607
32608 LLVM_FALLTHROUGH[[clang::fallthrough]];
32609 case ISD::BITCAST:
32610 V = V.getOperand(0);
32611 continue;
32612 }
32613 break;
32614 } while (V.hasOneUse());
32615 break;
32616 }
32617 // Break out of the loop if we break out of the switch.
32618 break;
32619 }
32620
32621 if (!V.hasOneUse())
32622 // We fell out of the loop without finding a viable combining instruction.
32623 return SDValue();
32624
32625 // Merge this node's mask and our incoming mask.
32626 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
32627 for (int &M : Mask)
32628 M = VMask[M];
32629 V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
32630 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
32631
32632 // Rebuild the chain around this new shuffle.
32633 while (!Chain.empty()) {
32634 SDValue W = Chain.pop_back_val();
32635
32636 if (V.getValueType() != W.getOperand(0).getValueType())
32637 V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
32638
32639 switch (W.getOpcode()) {
32640 default:
32641 llvm_unreachable("Only PSHUF and UNPCK instructions get here!")::llvm::llvm_unreachable_internal("Only PSHUF and UNPCK instructions get here!"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 32641)
;
32642
32643 case X86ISD::UNPCKL:
32644 case X86ISD::UNPCKH:
32645 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
32646 break;
32647
32648 case X86ISD::PSHUFD:
32649 case X86ISD::PSHUFLW:
32650 case X86ISD::PSHUFHW:
32651 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
32652 break;
32653 }
32654 }
32655 if (V.getValueType() != N.getValueType())
32656 V = DAG.getBitcast(N.getValueType(), V);
32657
32658 // Return the new chain to replace N.
32659 return V;
32660}
32661
32662/// Try to combine x86 target specific shuffles.
32663static SDValue combineTargetShuffle(SDValue N, SelectionDAG &DAG,
32664 TargetLowering::DAGCombinerInfo &DCI,
32665 const X86Subtarget &Subtarget) {
32666 SDLoc DL(N);
32667 MVT VT = N.getSimpleValueType();
32668 SmallVector<int, 4> Mask;
32669 unsigned Opcode = N.getOpcode();
32670
32671 // Combine binary shuffle of 2 similar 'Horizontal' instructions into a
32672 // single instruction.
32673 if (VT.getScalarSizeInBits() == 64 &&
32674 (Opcode == X86ISD::MOVSD || Opcode == X86ISD::UNPCKH ||
32675 Opcode == X86ISD::UNPCKL)) {
32676 auto BC0 = peekThroughBitcasts(N.getOperand(0));
32677 auto BC1 = peekThroughBitcasts(N.getOperand(1));
32678 EVT VT0 = BC0.getValueType();
32679 EVT VT1 = BC1.getValueType();
32680 unsigned Opcode0 = BC0.getOpcode();
32681 unsigned Opcode1 = BC1.getOpcode();
32682 if (Opcode0 == Opcode1 && VT0 == VT1 &&
32683 (Opcode0 == X86ISD::FHADD || Opcode0 == X86ISD::HADD ||
32684 Opcode0 == X86ISD::FHSUB || Opcode0 == X86ISD::HSUB ||
32685 Opcode0 == X86ISD::PACKSS || Opcode0 == X86ISD::PACKUS)) {
32686 SDValue Lo, Hi;
32687 if (Opcode == X86ISD::MOVSD) {
32688 Lo = BC1.getOperand(0);
32689 Hi = BC0.getOperand(1);
32690 } else {
32691 Lo = BC0.getOperand(Opcode == X86ISD::UNPCKH ? 1 : 0);
32692 Hi = BC1.getOperand(Opcode == X86ISD::UNPCKH ? 1 : 0);
32693 }
32694 SDValue Horiz = DAG.getNode(Opcode0, DL, VT0, Lo, Hi);
32695 return DAG.getBitcast(VT, Horiz);
32696 }
32697 }
32698
32699 switch (Opcode) {
32700 case X86ISD::VBROADCAST: {
32701 SDValue Src = N.getOperand(0);
32702 SDValue BC = peekThroughBitcasts(Src);
32703 EVT SrcVT = Src.getValueType();
32704 EVT BCVT = BC.getValueType();
32705
32706 // If broadcasting from another shuffle, attempt to simplify it.
32707 // TODO - we really need a general SimplifyDemandedVectorElts mechanism.
32708 if (isTargetShuffle(BC.getOpcode()) &&
32709 VT.getScalarSizeInBits() % BCVT.getScalarSizeInBits() == 0) {
32710 unsigned Scale = VT.getScalarSizeInBits() / BCVT.getScalarSizeInBits();
32711 SmallVector<int, 16> DemandedMask(BCVT.getVectorNumElements(),
32712 SM_SentinelUndef);
32713 for (unsigned i = 0; i != Scale; ++i)
32714 DemandedMask[i] = i;
32715 if (SDValue Res = combineX86ShufflesRecursively(
32716 {BC}, 0, BC, DemandedMask, {}, /*Depth*/ 1,
32717 /*HasVarMask*/ false, /*AllowVarMask*/ true, DAG, Subtarget))
32718 return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
32719 DAG.getBitcast(SrcVT, Res));
32720 }
32721
32722 // broadcast(bitcast(src)) -> bitcast(broadcast(src))
32723 // 32-bit targets have to bitcast i64 to f64, so better to bitcast upward.
32724 if (Src.getOpcode() == ISD::BITCAST &&
32725 SrcVT.getScalarSizeInBits() == BCVT.getScalarSizeInBits()) {
32726 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), BCVT.getScalarType(),
32727 VT.getVectorNumElements());
32728 return DAG.getBitcast(VT, DAG.getNode(X86ISD::VBROADCAST, DL, NewVT, BC));
32729 }
32730
32731 // Reduce broadcast source vector to lowest 128-bits.
32732 if (SrcVT.getSizeInBits() > 128)
32733 return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
32734 extract128BitVector(Src, 0, DAG, DL));
32735
32736 // broadcast(scalar_to_vector(x)) -> broadcast(x).
32737 if (Src.getOpcode() == ISD::SCALAR_TO_VECTOR)
32738 return DAG.getNode(X86ISD::VBROADCAST, DL, VT, Src.getOperand(0));
32739
32740 // Share broadcast with the longest vector and extract low subvector (free).
32741 for (SDNode *User : Src->uses())
32742 if (User != N.getNode() && User->getOpcode() == X86ISD::VBROADCAST &&
32743 User->getValueSizeInBits(0) > VT.getSizeInBits()) {
32744 return extractSubVector(SDValue(User, 0), 0, DAG, DL,
32745 VT.getSizeInBits());
32746 }
32747
32748 return SDValue();
32749 }
32750 case X86ISD::BLENDI: {
32751 SDValue N0 = N.getOperand(0);
32752 SDValue N1 = N.getOperand(1);
32753
32754 // blend(bitcast(x),bitcast(y)) -> bitcast(blend(x,y)) to narrower types.
32755 // TODO: Handle MVT::v16i16 repeated blend mask.
32756 if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST &&
32757 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()) {
32758 MVT SrcVT = N0.getOperand(0).getSimpleValueType();
32759 if ((VT.getScalarSizeInBits() % SrcVT.getScalarSizeInBits()) == 0 &&
32760 SrcVT.getScalarSizeInBits() >= 32) {
32761 unsigned Mask = N.getConstantOperandVal(2);
32762 unsigned Size = VT.getVectorNumElements();
32763 unsigned Scale = VT.getScalarSizeInBits() / SrcVT.getScalarSizeInBits();
32764 unsigned ScaleMask = scaleVectorShuffleBlendMask(Mask, Size, Scale);
32765 return DAG.getBitcast(
32766 VT, DAG.getNode(X86ISD::BLENDI, DL, SrcVT, N0.getOperand(0),
32767 N1.getOperand(0),
32768 DAG.getConstant(ScaleMask, DL, MVT::i8)));
32769 }
32770 }
32771 return SDValue();
32772 }
32773 case X86ISD::PSHUFD:
32774 case X86ISD::PSHUFLW:
32775 case X86ISD::PSHUFHW:
32776 Mask = getPSHUFShuffleMask(N);
32777 assert(Mask.size() == 4)((Mask.size() == 4) ? static_cast<void> (0) : __assert_fail
("Mask.size() == 4", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 32777, __PRETTY_FUNCTION__))
;
32778 break;
32779 case X86ISD::MOVSD:
32780 case X86ISD::MOVSS: {
32781 SDValue N0 = N.getOperand(0);
32782 SDValue N1 = N.getOperand(1);
32783
32784 // Canonicalize scalar FPOps:
32785 // MOVS*(N0, OP(N0, N1)) --> MOVS*(N0, SCALAR_TO_VECTOR(OP(N0[0], N1[0])))
32786 // If commutable, allow OP(N1[0], N0[0]).
32787 unsigned Opcode1 = N1.getOpcode();
32788 if (Opcode1 == ISD::FADD || Opcode1 == ISD::FMUL || Opcode1 == ISD::FSUB ||
32789 Opcode1 == ISD::FDIV) {
32790 SDValue N10 = N1.getOperand(0);
32791 SDValue N11 = N1.getOperand(1);
32792 if (N10 == N0 ||
32793 (N11 == N0 && (Opcode1 == ISD::FADD || Opcode1 == ISD::FMUL))) {
32794 if (N10 != N0)
32795 std::swap(N10, N11);
32796 MVT SVT = VT.getVectorElementType();
32797 SDValue ZeroIdx = DAG.getIntPtrConstant(0, DL);
32798 N10 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SVT, N10, ZeroIdx);
32799 N11 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SVT, N11, ZeroIdx);
32800 SDValue Scl = DAG.getNode(Opcode1, DL, SVT, N10, N11);
32801 SDValue SclVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, Scl);
32802 return DAG.getNode(Opcode, DL, VT, N0, SclVec);
32803 }
32804 }
32805
32806 return SDValue();
32807 }
32808 case X86ISD::INSERTPS: {
32809 assert(VT == MVT::v4f32 && "INSERTPS ValueType must be MVT::v4f32")((VT == MVT::v4f32 && "INSERTPS ValueType must be MVT::v4f32"
) ? static_cast<void> (0) : __assert_fail ("VT == MVT::v4f32 && \"INSERTPS ValueType must be MVT::v4f32\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 32809, __PRETTY_FUNCTION__))
;
32810 SDValue Op0 = N.getOperand(0);
32811 SDValue Op1 = N.getOperand(1);
32812 SDValue Op2 = N.getOperand(2);
32813 unsigned InsertPSMask = cast<ConstantSDNode>(Op2)->getZExtValue();
32814 unsigned SrcIdx = (InsertPSMask >> 6) & 0x3;
32815 unsigned DstIdx = (InsertPSMask >> 4) & 0x3;
32816 unsigned ZeroMask = InsertPSMask & 0xF;
32817
32818 // If we zero out all elements from Op0 then we don't need to reference it.
32819 if (((ZeroMask | (1u << DstIdx)) == 0xF) && !Op0.isUndef())
32820 return DAG.getNode(X86ISD::INSERTPS, DL, VT, DAG.getUNDEF(VT), Op1,
32821 DAG.getConstant(InsertPSMask, DL, MVT::i8));
32822
32823 // If we zero out the element from Op1 then we don't need to reference it.
32824 if ((ZeroMask & (1u << DstIdx)) && !Op1.isUndef())
32825 return DAG.getNode(X86ISD::INSERTPS, DL, VT, Op0, DAG.getUNDEF(VT),
32826 DAG.getConstant(InsertPSMask, DL, MVT::i8));
32827
32828 // Attempt to merge insertps Op1 with an inner target shuffle node.
32829 SmallVector<int, 8> TargetMask1;
32830 SmallVector<SDValue, 2> Ops1;
32831 if (setTargetShuffleZeroElements(Op1, TargetMask1, Ops1)) {
32832 int M = TargetMask1[SrcIdx];
32833 if (isUndefOrZero(M)) {
32834 // Zero/UNDEF insertion - zero out element and remove dependency.
32835 InsertPSMask |= (1u << DstIdx);
32836 return DAG.getNode(X86ISD::INSERTPS, DL, VT, Op0, DAG.getUNDEF(VT),
32837 DAG.getConstant(InsertPSMask, DL, MVT::i8));
32838 }
32839 // Update insertps mask srcidx and reference the source input directly.
32840 assert(0 <= M && M < 8 && "Shuffle index out of range")((0 <= M && M < 8 && "Shuffle index out of range"
) ? static_cast<void> (0) : __assert_fail ("0 <= M && M < 8 && \"Shuffle index out of range\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 32840, __PRETTY_FUNCTION__))
;
32841 InsertPSMask = (InsertPSMask & 0x3f) | ((M & 0x3) << 6);
32842 Op1 = Ops1[M < 4 ? 0 : 1];
32843 return DAG.getNode(X86ISD::INSERTPS, DL, VT, Op0, Op1,
32844 DAG.getConstant(InsertPSMask, DL, MVT::i8));
32845 }
32846
32847 // Attempt to merge insertps Op0 with an inner target shuffle node.
32848 SmallVector<int, 8> TargetMask0;
32849 SmallVector<SDValue, 2> Ops0;
32850 if (!setTargetShuffleZeroElements(Op0, TargetMask0, Ops0))
32851 return SDValue();
32852
32853 bool Updated = false;
32854 bool UseInput00 = false;
32855 bool UseInput01 = false;
32856 for (int i = 0; i != 4; ++i) {
32857 int M = TargetMask0[i];
32858 if ((InsertPSMask & (1u << i)) || (i == (int)DstIdx)) {
32859 // No change if element is already zero or the inserted element.
32860 continue;
32861 } else if (isUndefOrZero(M)) {
32862 // If the target mask is undef/zero then we must zero the element.
32863 InsertPSMask |= (1u << i);
32864 Updated = true;
32865 continue;
32866 }
32867
32868 // The input vector element must be inline.
32869 if (M != i && M != (i + 4))
32870 return SDValue();
32871
32872 // Determine which inputs of the target shuffle we're using.
32873 UseInput00 |= (0 <= M && M < 4);
32874 UseInput01 |= (4 <= M);
32875 }
32876
32877 // If we're not using both inputs of the target shuffle then use the
32878 // referenced input directly.
32879 if (UseInput00 && !UseInput01) {
32880 Updated = true;
32881 Op0 = Ops0[0];
32882 } else if (!UseInput00 && UseInput01) {
32883 Updated = true;
32884 Op0 = Ops0[1];
32885 }
32886
32887 if (Updated)
32888 return DAG.getNode(X86ISD::INSERTPS, DL, VT, Op0, Op1,
32889 DAG.getConstant(InsertPSMask, DL, MVT::i8));
32890
32891 return SDValue();
32892 }
32893 default:
32894 return SDValue();
32895 }
32896
32897 // Nuke no-op shuffles that show up after combining.
32898 if (isNoopShuffleMask(Mask))
32899 return N.getOperand(0);
32900
32901 // Look for simplifications involving one or two shuffle instructions.
32902 SDValue V = N.getOperand(0);
32903 switch (N.getOpcode()) {
32904 default:
32905 break;
32906 case X86ISD::PSHUFLW:
32907 case X86ISD::PSHUFHW:
32908 assert(VT.getVectorElementType() == MVT::i16 && "Bad word shuffle type!")((VT.getVectorElementType() == MVT::i16 && "Bad word shuffle type!"
) ? static_cast<void> (0) : __assert_fail ("VT.getVectorElementType() == MVT::i16 && \"Bad word shuffle type!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 32908, __PRETTY_FUNCTION__))
;
32909
32910 // See if this reduces to a PSHUFD which is no more expensive and can
32911 // combine with more operations. Note that it has to at least flip the
32912 // dwords as otherwise it would have been removed as a no-op.
32913 if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
32914 int DMask[] = {0, 1, 2, 3};
32915 int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
32916 DMask[DOffset + 0] = DOffset + 1;
32917 DMask[DOffset + 1] = DOffset + 0;
32918 MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
32919 V = DAG.getBitcast(DVT, V);
32920 V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
32921 getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
32922 return DAG.getBitcast(VT, V);
32923 }
32924
32925 // Look for shuffle patterns which can be implemented as a single unpack.
32926 // FIXME: This doesn't handle the location of the PSHUFD generically, and
32927 // only works when we have a PSHUFD followed by two half-shuffles.
32928 if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
32929 (V.getOpcode() == X86ISD::PSHUFLW ||
32930 V.getOpcode() == X86ISD::PSHUFHW) &&
32931 V.getOpcode() != N.getOpcode() &&
32932 V.hasOneUse()) {
32933 SDValue D = peekThroughOneUseBitcasts(V.getOperand(0));
32934 if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
32935 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
32936 SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
32937 int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
32938 int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
32939 int WordMask[8];
32940 for (int i = 0; i < 4; ++i) {
32941 WordMask[i + NOffset] = Mask[i] + NOffset;
32942 WordMask[i + VOffset] = VMask[i] + VOffset;
32943 }
32944 // Map the word mask through the DWord mask.
32945 int MappedMask[8];
32946 for (int i = 0; i < 8; ++i)
32947 MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
32948 if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
32949 makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
32950 // We can replace all three shuffles with an unpack.
32951 V = DAG.getBitcast(VT, D.getOperand(0));
32952 return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
32953 : X86ISD::UNPCKH,
32954 DL, VT, V, V);
32955 }
32956 }
32957 }
32958
32959 break;
32960
32961 case X86ISD::PSHUFD:
32962 if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG))
32963 return NewN;
32964
32965 break;
32966 }
32967
32968 return SDValue();
32969}
32970
32971/// Checks if the shuffle mask takes subsequent elements
32972/// alternately from two vectors.
32973/// For example <0, 5, 2, 7> or <8, 1, 10, 3, 12, 5, 14, 7> are both correct.
32974static bool isAddSubOrSubAddMask(ArrayRef<int> Mask, bool &Op0Even) {
32975
32976 int ParitySrc[2] = {-1, -1};
32977 unsigned Size = Mask.size();
32978 for (unsigned i = 0; i != Size; ++i) {
32979 int M = Mask[i];
32980 if (M < 0)
32981 continue;
32982
32983 // Make sure we are using the matching element from the input.
32984 if ((M % Size) != i)
32985 return false;
32986
32987 // Make sure we use the same input for all elements of the same parity.
32988 int Src = M / Size;
32989 if (ParitySrc[i % 2] >= 0 && ParitySrc[i % 2] != Src)
32990 return false;
32991 ParitySrc[i % 2] = Src;
32992 }
32993
32994 // Make sure each input is used.
32995 if (ParitySrc[0] < 0 || ParitySrc[1] < 0 || ParitySrc[0] == ParitySrc[1])
32996 return false;
32997
32998 Op0Even = ParitySrc[0] == 0;
32999 return true;
33000}
33001
33002/// Returns true iff the shuffle node \p N can be replaced with ADDSUB(SUBADD)
33003/// operation. If true is returned then the operands of ADDSUB(SUBADD) operation
33004/// are written to the parameters \p Opnd0 and \p Opnd1.
33005///
33006/// We combine shuffle to ADDSUB(SUBADD) directly on the abstract vector shuffle nodes
33007/// so it is easier to generically match. We also insert dummy vector shuffle
33008/// nodes for the operands which explicitly discard the lanes which are unused
33009/// by this operation to try to flow through the rest of the combiner
33010/// the fact that they're unused.
33011static bool isAddSubOrSubAdd(SDNode *N, const X86Subtarget &Subtarget,
33012 SelectionDAG &DAG, SDValue &Opnd0, SDValue &Opnd1,
33013 bool &IsSubAdd) {
33014
33015 EVT VT = N->getValueType(0);
33016 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
33017 if (!Subtarget.hasSSE3() || !TLI.isTypeLegal(VT) ||
33018 !VT.getSimpleVT().isFloatingPoint())
33019 return false;
33020
33021 // We only handle target-independent shuffles.
33022 // FIXME: It would be easy and harmless to use the target shuffle mask
33023 // extraction tool to support more.
33024 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
33025 return false;
33026
33027 SDValue V1 = N->getOperand(0);
33028 SDValue V2 = N->getOperand(1);
33029
33030 // Make sure we have an FADD and an FSUB.
33031 if ((V1.getOpcode() != ISD::FADD && V1.getOpcode() != ISD::FSUB) ||
33032 (V2.getOpcode() != ISD::FADD && V2.getOpcode() != ISD::FSUB) ||
33033 V1.getOpcode() == V2.getOpcode())
33034 return false;
33035
33036 // If there are other uses of these operations we can't fold them.
33037 if (!V1->hasOneUse() || !V2->hasOneUse())
33038 return false;
33039
33040 // Ensure that both operations have the same operands. Note that we can
33041 // commute the FADD operands.
33042 SDValue LHS, RHS;
33043 if (V1.getOpcode() == ISD::FSUB) {
33044 LHS = V1->getOperand(0); RHS = V1->getOperand(1);
33045 if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
33046 (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
33047 return false;
33048 } else {
33049 assert(V2.getOpcode() == ISD::FSUB && "Unexpected opcode")((V2.getOpcode() == ISD::FSUB && "Unexpected opcode")
? static_cast<void> (0) : __assert_fail ("V2.getOpcode() == ISD::FSUB && \"Unexpected opcode\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 33049, __PRETTY_FUNCTION__))
;
33050 LHS = V2->getOperand(0); RHS = V2->getOperand(1);
33051 if ((V1->getOperand(0) != LHS || V1->getOperand(1) != RHS) &&
33052 (V1->getOperand(0) != RHS || V1->getOperand(1) != LHS))
33053 return false;
33054 }
33055
33056 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(N)->getMask();
33057 bool Op0Even;
33058 if (!isAddSubOrSubAddMask(Mask, Op0Even))
33059 return false;
33060
33061 // It's a subadd if the vector in the even parity is an FADD.
33062 IsSubAdd = Op0Even ? V1->getOpcode() == ISD::FADD
33063 : V2->getOpcode() == ISD::FADD;
33064
33065 Opnd0 = LHS;
33066 Opnd1 = RHS;
33067 return true;
33068}
33069
33070/// Combine shuffle of two fma nodes into FMAddSub or FMSubAdd.
33071static SDValue combineShuffleToFMAddSub(SDNode *N,
33072 const X86Subtarget &Subtarget,
33073 SelectionDAG &DAG) {
33074 // We only handle target-independent shuffles.
33075 // FIXME: It would be easy and harmless to use the target shuffle mask
33076 // extraction tool to support more.
33077 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
33078 return SDValue();
33079
33080 MVT VT = N->getSimpleValueType(0);
33081 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
33082 if (!Subtarget.hasAnyFMA() || !TLI.isTypeLegal(VT))
33083 return SDValue();
33084
33085 // We're trying to match (shuffle fma(a, b, c), X86Fmsub(a, b, c).
33086 SDValue Op0 = N->getOperand(0);
33087 SDValue Op1 = N->getOperand(1);
33088 SDValue FMAdd = Op0, FMSub = Op1;
33089 if (FMSub.getOpcode() != X86ISD::FMSUB)
33090 std::swap(FMAdd, FMSub);
33091
33092 if (FMAdd.getOpcode() != ISD::FMA || FMSub.getOpcode() != X86ISD::FMSUB ||
33093 FMAdd.getOperand(0) != FMSub.getOperand(0) || !FMAdd.hasOneUse() ||
33094 FMAdd.getOperand(1) != FMSub.getOperand(1) || !FMSub.hasOneUse() ||
33095 FMAdd.getOperand(2) != FMSub.getOperand(2))
33096 return SDValue();
33097
33098 // Check for correct shuffle mask.
33099 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(N)->getMask();
33100 bool Op0Even;
33101 if (!isAddSubOrSubAddMask(Mask, Op0Even))
33102 return SDValue();
33103
33104 // FMAddSub takes zeroth operand from FMSub node.
33105 SDLoc DL(N);
33106 bool IsSubAdd = Op0Even ? Op0 == FMAdd : Op1 == FMAdd;
33107 unsigned Opcode = IsSubAdd ? X86ISD::FMSUBADD : X86ISD::FMADDSUB;
33108 return DAG.getNode(Opcode, DL, VT, FMAdd.getOperand(0), FMAdd.getOperand(1),
33109 FMAdd.getOperand(2));
33110}
33111
33112/// Try to combine a shuffle into a target-specific add-sub or
33113/// mul-add-sub node.
33114static SDValue combineShuffleToAddSubOrFMAddSub(SDNode *N,
33115 const X86Subtarget &Subtarget,
33116 SelectionDAG &DAG) {
33117 if (SDValue V = combineShuffleToFMAddSub(N, Subtarget, DAG))
33118 return V;
33119
33120 SDValue Opnd0, Opnd1;
33121 bool IsSubAdd;
33122 if (!isAddSubOrSubAdd(N, Subtarget, DAG, Opnd0, Opnd1, IsSubAdd))
33123 return SDValue();
33124
33125 MVT VT = N->getSimpleValueType(0);
33126 SDLoc DL(N);
33127
33128 // Try to generate X86ISD::FMADDSUB node here.
33129 SDValue Opnd2;
33130 if (isFMAddSubOrFMSubAdd(Subtarget, DAG, Opnd0, Opnd1, Opnd2, 2)) {
33131 unsigned Opc = IsSubAdd ? X86ISD::FMSUBADD : X86ISD::FMADDSUB;
33132 return DAG.getNode(Opc, DL, VT, Opnd0, Opnd1, Opnd2);
33133 }
33134
33135 if (IsSubAdd)
33136 return SDValue();
33137
33138 // Do not generate X86ISD::ADDSUB node for 512-bit types even though
33139 // the ADDSUB idiom has been successfully recognized. There are no known
33140 // X86 targets with 512-bit ADDSUB instructions!
33141 if (VT.is512BitVector())
33142 return SDValue();
33143
33144 return DAG.getNode(X86ISD::ADDSUB, DL, VT, Opnd0, Opnd1);
33145}
33146
33147// We are looking for a shuffle where both sources are concatenated with undef
33148// and have a width that is half of the output's width. AVX2 has VPERMD/Q, so
33149// if we can express this as a single-source shuffle, that's preferable.
33150static SDValue combineShuffleOfConcatUndef(SDNode *N, SelectionDAG &DAG,
33151 const X86Subtarget &Subtarget) {
33152 if (!Subtarget.hasAVX2() || !isa<ShuffleVectorSDNode>(N))
33153 return SDValue();
33154
33155 EVT VT = N->getValueType(0);
33156
33157 // We only care about shuffles of 128/256-bit vectors of 32/64-bit values.
33158 if (!VT.is128BitVector() && !VT.is256BitVector())
33159 return SDValue();
33160
33161 if (VT.getVectorElementType() != MVT::i32 &&
33162 VT.getVectorElementType() != MVT::i64 &&
33163 VT.getVectorElementType() != MVT::f32 &&
33164 VT.getVectorElementType() != MVT::f64)
33165 return SDValue();
33166
33167 SDValue N0 = N->getOperand(0);
33168 SDValue N1 = N->getOperand(1);
33169
33170 // Check that both sources are concats with undef.
33171 if (N0.getOpcode() != ISD::CONCAT_VECTORS ||
33172 N1.getOpcode() != ISD::CONCAT_VECTORS || N0.getNumOperands() != 2 ||
33173 N1.getNumOperands() != 2 || !N0.getOperand(1).isUndef() ||
33174 !N1.getOperand(1).isUndef())
33175 return SDValue();
33176
33177 // Construct the new shuffle mask. Elements from the first source retain their
33178 // index, but elements from the second source no longer need to skip an undef.
33179 SmallVector<int, 8> Mask;
33180 int NumElts = VT.getVectorNumElements();
33181
33182 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
33183 for (int Elt : SVOp->getMask())
33184 Mask.push_back(Elt < NumElts ? Elt : (Elt - NumElts / 2));
33185
33186 SDLoc DL(N);
33187 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, N0.getOperand(0),
33188 N1.getOperand(0));
33189 return DAG.getVectorShuffle(VT, DL, Concat, DAG.getUNDEF(VT), Mask);
33190}
33191
33192/// Eliminate a redundant shuffle of a horizontal math op.
33193static SDValue foldShuffleOfHorizOp(SDNode *N) {
33194 unsigned Opcode = N->getOpcode();
33195 if (Opcode != X86ISD::MOVDDUP && Opcode != X86ISD::VBROADCAST)
33196 if (Opcode != ISD::VECTOR_SHUFFLE || !N->getOperand(1).isUndef())
33197 return SDValue();
33198
33199 // For a broadcast, peek through an extract element of index 0 to find the
33200 // horizontal op: broadcast (ext_vec_elt HOp, 0)
33201 EVT VT = N->getValueType(0);
33202 if (Opcode == X86ISD::VBROADCAST) {
33203 SDValue SrcOp = N->getOperand(0);
33204 if (SrcOp.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
33205 SrcOp.getValueType() == MVT::f64 &&
33206 SrcOp.getOperand(0).getValueType() == VT &&
33207 isNullConstant(SrcOp.getOperand(1)))
33208 N = SrcOp.getNode();
33209 }
33210
33211 SDValue HOp = N->getOperand(0);
33212 if (HOp.getOpcode() != X86ISD::HADD && HOp.getOpcode() != X86ISD::FHADD &&
33213 HOp.getOpcode() != X86ISD::HSUB && HOp.getOpcode() != X86ISD::FHSUB)
33214 return SDValue();
33215
33216 // 128-bit horizontal math instructions are defined to operate on adjacent
33217 // lanes of each operand as:
33218 // v4X32: A[0] + A[1] , A[2] + A[3] , B[0] + B[1] , B[2] + B[3]
33219 // ...similarly for v2f64 and v8i16.
33220 if (!HOp.getOperand(0).isUndef() && !HOp.getOperand(1).isUndef() &&
33221 HOp.getOperand(0) != HOp.getOperand(1))
33222 return SDValue();
33223
33224 // When the operands of a horizontal math op are identical, the low half of
33225 // the result is the same as the high half. If a target shuffle is also
33226 // replicating low and high halves, we don't need the shuffle.
33227 if (Opcode == X86ISD::MOVDDUP || Opcode == X86ISD::VBROADCAST) {
33228 // movddup (hadd X, X) --> hadd X, X
33229 // broadcast (extract_vec_elt (hadd X, X), 0) --> hadd X, X
33230 assert((HOp.getValueType() == MVT::v2f64 ||(((HOp.getValueType() == MVT::v2f64 || HOp.getValueType() == MVT
::v4f64) && HOp.getValueType() == VT && "Unexpected type for h-op"
) ? static_cast<void> (0) : __assert_fail ("(HOp.getValueType() == MVT::v2f64 || HOp.getValueType() == MVT::v4f64) && HOp.getValueType() == VT && \"Unexpected type for h-op\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 33232, __PRETTY_FUNCTION__))
33231 HOp.getValueType() == MVT::v4f64) && HOp.getValueType() == VT &&(((HOp.getValueType() == MVT::v2f64 || HOp.getValueType() == MVT
::v4f64) && HOp.getValueType() == VT && "Unexpected type for h-op"
) ? static_cast<void> (0) : __assert_fail ("(HOp.getValueType() == MVT::v2f64 || HOp.getValueType() == MVT::v4f64) && HOp.getValueType() == VT && \"Unexpected type for h-op\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 33232, __PRETTY_FUNCTION__))
33232 "Unexpected type for h-op")(((HOp.getValueType() == MVT::v2f64 || HOp.getValueType() == MVT
::v4f64) && HOp.getValueType() == VT && "Unexpected type for h-op"
) ? static_cast<void> (0) : __assert_fail ("(HOp.getValueType() == MVT::v2f64 || HOp.getValueType() == MVT::v4f64) && HOp.getValueType() == VT && \"Unexpected type for h-op\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 33232, __PRETTY_FUNCTION__))
;
33233 return HOp;
33234 }
33235
33236 // shuffle (hadd X, X), undef, [low half...high half] --> hadd X, X
33237 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(N)->getMask();
33238 // TODO: Other mask possibilities like {1,1} and {1,0} could be added here,
33239 // but this should be tied to whatever horizontal op matching and shuffle
33240 // canonicalization are producing.
33241 if (HOp.getValueSizeInBits() == 128 &&
33242 (isTargetShuffleEquivalent(Mask, {0, 0}) ||
33243 isTargetShuffleEquivalent(Mask, {0, 1, 0, 1}) ||
33244 isTargetShuffleEquivalent(Mask, {0, 1, 2, 3, 0, 1, 2, 3})))
33245 return HOp;
33246
33247 if (HOp.getValueSizeInBits() == 256 &&
33248 (isTargetShuffleEquivalent(Mask, {0, 0, 2, 2}) ||
33249 isTargetShuffleEquivalent(Mask, {0, 1, 0, 1, 4, 5, 4, 5}) ||
33250 isTargetShuffleEquivalent(
33251 Mask, {0, 1, 2, 3, 0, 1, 2, 3, 8, 9, 10, 11, 8, 9, 10, 11})))
33252 return HOp;
33253
33254 return SDValue();
33255}
33256
33257/// If we have a shuffle of AVX/AVX512 (256/512 bit) vectors that only uses the
33258/// low half of each source vector and does not set any high half elements in
33259/// the destination vector, narrow the shuffle to half its original size.
33260static SDValue narrowShuffle(ShuffleVectorSDNode *Shuf, SelectionDAG &DAG) {
33261 if (!Shuf->getValueType(0).isSimple())
33262 return SDValue();
33263 MVT VT = Shuf->getSimpleValueType(0);
33264 if (!VT.is256BitVector() && !VT.is512BitVector())
33265 return SDValue();
33266
33267 // See if we can ignore all of the high elements of the shuffle.
33268 ArrayRef<int> Mask = Shuf->getMask();
33269 if (!isUndefUpperHalf(Mask))
33270 return SDValue();
33271
33272 // Check if the shuffle mask accesses only the low half of each input vector
33273 // (half-index output is 0 or 2).
33274 int HalfIdx1, HalfIdx2;
33275 SmallVector<int, 8> HalfMask(Mask.size() / 2);
33276 if (!getHalfShuffleMask(Mask, HalfMask, HalfIdx1, HalfIdx2) ||
33277 (HalfIdx1 % 2 == 1) || (HalfIdx2 % 2 == 1))
33278 return SDValue();
33279
33280 // Create a half-width shuffle to replace the unnecessarily wide shuffle.
33281 // The trick is knowing that all of the insert/extract are actually free
33282 // subregister (zmm<->ymm or ymm<->xmm) ops. That leaves us with a shuffle
33283 // of narrow inputs into a narrow output, and that is always cheaper than
33284 // the wide shuffle that we started with.
33285 return getShuffleHalfVectors(SDLoc(Shuf), Shuf->getOperand(0),
33286 Shuf->getOperand(1), HalfMask, HalfIdx1,
33287 HalfIdx2, false, DAG);
33288}
33289
33290static SDValue combineShuffle(SDNode *N, SelectionDAG &DAG,
33291 TargetLowering::DAGCombinerInfo &DCI,
33292 const X86Subtarget &Subtarget) {
33293 if (auto *Shuf = dyn_cast<ShuffleVectorSDNode>(N))
33294 if (SDValue V = narrowShuffle(Shuf, DAG))
33295 return V;
33296
33297 // If we have legalized the vector types, look for blends of FADD and FSUB
33298 // nodes that we can fuse into an ADDSUB, FMADDSUB, or FMSUBADD node.
33299 SDLoc dl(N);
33300 EVT VT = N->getValueType(0);
33301 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
33302 if (TLI.isTypeLegal(VT)) {
33303 if (SDValue AddSub = combineShuffleToAddSubOrFMAddSub(N, Subtarget, DAG))
33304 return AddSub;
33305
33306 if (SDValue HAddSub = foldShuffleOfHorizOp(N))
33307 return HAddSub;
33308 }
33309
33310 // During Type Legalization, when promoting illegal vector types,
33311 // the backend might introduce new shuffle dag nodes and bitcasts.
33312 //
33313 // This code performs the following transformation:
33314 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
33315 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
33316 //
33317 // We do this only if both the bitcast and the BINOP dag nodes have
33318 // one use. Also, perform this transformation only if the new binary
33319 // operation is legal. This is to avoid introducing dag nodes that
33320 // potentially need to be further expanded (or custom lowered) into a
33321 // less optimal sequence of dag nodes.
33322 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
33323 N->getOpcode() == ISD::VECTOR_SHUFFLE &&
33324 N->getOperand(0).getOpcode() == ISD::BITCAST &&
33325 N->getOperand(1).isUndef() && N->getOperand(0).hasOneUse()) {
33326 SDValue N0 = N->getOperand(0);
33327 SDValue N1 = N->getOperand(1);
33328
33329 SDValue BC0 = N0.getOperand(0);
33330 EVT SVT = BC0.getValueType();
33331 unsigned Opcode = BC0.getOpcode();
33332 unsigned NumElts = VT.getVectorNumElements();
33333
33334 if (BC0.hasOneUse() && SVT.isVector() &&
33335 SVT.getVectorNumElements() * 2 == NumElts &&
33336 TLI.isOperationLegal(Opcode, VT)) {
33337 bool CanFold = false;
33338 switch (Opcode) {
33339 default : break;
33340 case ISD::ADD:
33341 case ISD::SUB:
33342 case ISD::MUL:
33343 // isOperationLegal lies for integer ops on floating point types.
33344 CanFold = VT.isInteger();
33345 break;
33346 case ISD::FADD:
33347 case ISD::FSUB:
33348 case ISD::FMUL:
33349 // isOperationLegal lies for floating point ops on integer types.
33350 CanFold = VT.isFloatingPoint();
33351 break;
33352 }
33353
33354 unsigned SVTNumElts = SVT.getVectorNumElements();
33355 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
33356 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
33357 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
33358 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
33359 CanFold = SVOp->getMaskElt(i) < 0;
33360
33361 if (CanFold) {
33362 SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
33363 SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
33364 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
33365 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, SVOp->getMask());
33366 }
33367 }
33368 }
33369
33370 // Attempt to combine into a vector load/broadcast.
33371 if (SDValue LD = combineToConsecutiveLoads(VT, N, dl, DAG, Subtarget, true))
33372 return LD;
33373
33374 // For AVX2, we sometimes want to combine
33375 // (vector_shuffle <mask> (concat_vectors t1, undef)
33376 // (concat_vectors t2, undef))
33377 // Into:
33378 // (vector_shuffle <mask> (concat_vectors t1, t2), undef)
33379 // Since the latter can be efficiently lowered with VPERMD/VPERMQ
33380 if (SDValue ShufConcat = combineShuffleOfConcatUndef(N, DAG, Subtarget))
33381 return ShufConcat;
33382
33383 if (isTargetShuffle(N->getOpcode())) {
33384 SDValue Op(N, 0);
33385 if (SDValue Shuffle = combineTargetShuffle(Op, DAG, DCI, Subtarget))
33386 return Shuffle;
33387
33388 // Try recursively combining arbitrary sequences of x86 shuffle
33389 // instructions into higher-order shuffles. We do this after combining
33390 // specific PSHUF instruction sequences into their minimal form so that we
33391 // can evaluate how many specialized shuffle instructions are involved in
33392 // a particular chain.
33393 if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
33394 return Res;
33395
33396 // Simplify source operands based on shuffle mask.
33397 // TODO - merge this into combineX86ShufflesRecursively.
33398 APInt KnownUndef, KnownZero;
33399 APInt DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements());
33400 if (TLI.SimplifyDemandedVectorElts(Op, DemandedElts, KnownUndef, KnownZero, DCI))
33401 return SDValue(N, 0);
33402 }
33403
33404 // Look for a v2i64/v2f64 VZEXT_MOVL of a node that already produces zeros
33405 // in the upper 64 bits.
33406 // TODO: Can we generalize this using computeKnownBits.
33407 if (N->getOpcode() == X86ISD::VZEXT_MOVL &&
33408 (VT == MVT::v2f64 || VT == MVT::v2i64) &&
33409 N->getOperand(0).getOpcode() == ISD::BITCAST &&
33410 (N->getOperand(0).getOperand(0).getValueType() == MVT::v4f32 ||
33411 N->getOperand(0).getOperand(0).getValueType() == MVT::v4i32)) {
33412 SDValue In = N->getOperand(0).getOperand(0);
33413 switch (In.getOpcode()) {
33414 default:
33415 break;
33416 case X86ISD::CVTP2SI: case X86ISD::CVTP2UI:
33417 case X86ISD::MCVTP2SI: case X86ISD::MCVTP2UI:
33418 case X86ISD::CVTTP2SI: case X86ISD::CVTTP2UI:
33419 case X86ISD::MCVTTP2SI: case X86ISD::MCVTTP2UI:
33420 case X86ISD::CVTSI2P: case X86ISD::CVTUI2P:
33421 case X86ISD::MCVTSI2P: case X86ISD::MCVTUI2P:
33422 case X86ISD::VFPROUND: case X86ISD::VMFPROUND:
33423 if (In.getOperand(0).getValueType() == MVT::v2f64 ||
33424 In.getOperand(0).getValueType() == MVT::v2i64)
33425 return N->getOperand(0); // return the bitcast
33426 break;
33427 }
33428 }
33429
33430 // Look for a truncating shuffle to v2i32 of a PMULUDQ where one of the
33431 // operands is an extend from v2i32 to v2i64. Turn it into a pmulld.
33432 // FIXME: This can probably go away once we default to widening legalization.
33433 if (Subtarget.hasSSE41() && VT == MVT::v4i32 &&
33434 N->getOpcode() == ISD::VECTOR_SHUFFLE &&
33435 N->getOperand(0).getOpcode() == ISD::BITCAST &&
33436 N->getOperand(0).getOperand(0).getOpcode() == X86ISD::PMULUDQ) {
33437 SDValue BC = N->getOperand(0);
33438 SDValue MULUDQ = BC.getOperand(0);
33439 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
33440 ArrayRef<int> Mask = SVOp->getMask();
33441 if (BC.hasOneUse() && MULUDQ.hasOneUse() &&
33442 Mask[0] == 0 && Mask[1] == 2 && Mask[2] == -1 && Mask[3] == -1) {
33443 SDValue Op0 = MULUDQ.getOperand(0);
33444 SDValue Op1 = MULUDQ.getOperand(1);
33445 if (Op0.getOpcode() == ISD::BITCAST &&
33446 Op0.getOperand(0).getOpcode() == ISD::VECTOR_SHUFFLE &&
33447 Op0.getOperand(0).getValueType() == MVT::v4i32) {
33448 ShuffleVectorSDNode *SVOp0 =
33449 cast<ShuffleVectorSDNode>(Op0.getOperand(0));
33450 ArrayRef<int> Mask2 = SVOp0->getMask();
33451 if (Mask2[0] == 0 && Mask2[1] == -1 &&
33452 Mask2[2] == 1 && Mask2[3] == -1) {
33453 Op0 = SVOp0->getOperand(0);
33454 Op1 = DAG.getBitcast(MVT::v4i32, Op1);
33455 Op1 = DAG.getVectorShuffle(MVT::v4i32, dl, Op1, Op1, Mask);
33456 return DAG.getNode(ISD::MUL, dl, MVT::v4i32, Op0, Op1);
33457 }
33458 }
33459 if (Op1.getOpcode() == ISD::BITCAST &&
33460 Op1.getOperand(0).getOpcode() == ISD::VECTOR_SHUFFLE &&
33461 Op1.getOperand(0).getValueType() == MVT::v4i32) {
33462 ShuffleVectorSDNode *SVOp1 =
33463 cast<ShuffleVectorSDNode>(Op1.getOperand(0));
33464 ArrayRef<int> Mask2 = SVOp1->getMask();
33465 if (Mask2[0] == 0 && Mask2[1] == -1 &&
33466 Mask2[2] == 1 && Mask2[3] == -1) {
33467 Op0 = DAG.getBitcast(MVT::v4i32, Op0);
33468 Op0 = DAG.getVectorShuffle(MVT::v4i32, dl, Op0, Op0, Mask);
33469 Op1 = SVOp1->getOperand(0);
33470 return DAG.getNode(ISD::MUL, dl, MVT::v4i32, Op0, Op1);
33471 }
33472 }
33473 }
33474 }
33475
33476 return SDValue();
33477}
33478
33479bool X86TargetLowering::SimplifyDemandedVectorEltsForTargetNode(
33480 SDValue Op, const APInt &DemandedElts, APInt &KnownUndef, APInt &KnownZero,
33481 TargetLoweringOpt &TLO, unsigned Depth) const {
33482 int NumElts = DemandedElts.getBitWidth();
33483 unsigned Opc = Op.getOpcode();
33484 EVT VT = Op.getValueType();
33485
33486 // Handle special case opcodes.
33487 switch (Opc) {
33488 case X86ISD::PMULDQ:
33489 case X86ISD::PMULUDQ: {
33490 APInt LHSUndef, LHSZero;
33491 APInt RHSUndef, RHSZero;
33492 SDValue LHS = Op.getOperand(0);
33493 SDValue RHS = Op.getOperand(1);
33494 if (SimplifyDemandedVectorElts(LHS, DemandedElts, LHSUndef, LHSZero, TLO,
33495 Depth + 1))
33496 return true;
33497 if (SimplifyDemandedVectorElts(RHS, DemandedElts, RHSUndef, RHSZero, TLO,
33498 Depth + 1))
33499 return true;
33500 // Multiply by zero.
33501 KnownZero = LHSZero | RHSZero;
33502 break;
33503 }
33504 case X86ISD::VSHL:
33505 case X86ISD::VSRL:
33506 case X86ISD::VSRA: {
33507 // We only need the bottom 64-bits of the (128-bit) shift amount.
33508 SDValue Amt = Op.getOperand(1);
33509 MVT AmtVT = Amt.getSimpleValueType();
33510 assert(AmtVT.is128BitVector() && "Unexpected value type")((AmtVT.is128BitVector() && "Unexpected value type") ?
static_cast<void> (0) : __assert_fail ("AmtVT.is128BitVector() && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 33510, __PRETTY_FUNCTION__))
;
33511
33512 // If we reuse the shift amount just for sse shift amounts then we know that
33513 // only the bottom 64-bits are only ever used.
33514 bool AssumeSingleUse = llvm::all_of(Amt->uses(), [&Amt](SDNode *Use) {
33515 unsigned Opc = Use->getOpcode();
33516 return (Opc == X86ISD::VSHL || Opc == X86ISD::VSRL ||
33517 Opc == X86ISD::VSRA) &&
33518 Use->getOperand(0) != Amt;
33519 });
33520
33521 APInt AmtUndef, AmtZero;
33522 unsigned NumAmtElts = AmtVT.getVectorNumElements();
33523 APInt AmtElts = APInt::getLowBitsSet(NumAmtElts, NumAmtElts / 2);
33524 if (SimplifyDemandedVectorElts(Amt, AmtElts, AmtUndef, AmtZero, TLO,
33525 Depth + 1, AssumeSingleUse))
33526 return true;
33527 LLVM_FALLTHROUGH[[clang::fallthrough]];
33528 }
33529 case X86ISD::VSHLI:
33530 case X86ISD::VSRLI:
33531 case X86ISD::VSRAI: {
33532 SDValue Src = Op.getOperand(0);
33533 APInt SrcUndef;
33534 if (SimplifyDemandedVectorElts(Src, DemandedElts, SrcUndef, KnownZero, TLO,
33535 Depth + 1))
33536 return true;
33537 // TODO convert SrcUndef to KnownUndef.
33538 break;
33539 }
33540 case X86ISD::CVTSI2P:
33541 case X86ISD::CVTUI2P: {
33542 SDValue Src = Op.getOperand(0);
33543 MVT SrcVT = Src.getSimpleValueType();
33544 APInt SrcUndef, SrcZero;
33545 APInt SrcElts = DemandedElts.zextOrTrunc(SrcVT.getVectorNumElements());
33546 if (SimplifyDemandedVectorElts(Src, SrcElts, SrcUndef, SrcZero, TLO,
33547 Depth + 1))
33548 return true;
33549 break;
33550 }
33551 case X86ISD::PACKSS:
33552 case X86ISD::PACKUS: {
33553 APInt DemandedLHS, DemandedRHS;
33554 getPackDemandedElts(VT, DemandedElts, DemandedLHS, DemandedRHS);
33555
33556 APInt SrcUndef, SrcZero;
33557 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedLHS, SrcUndef,
33558 SrcZero, TLO, Depth + 1))
33559 return true;
33560 if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedRHS, SrcUndef,
33561 SrcZero, TLO, Depth + 1))
33562 return true;
33563 break;
33564 }
33565 case X86ISD::HADD:
33566 case X86ISD::HSUB:
33567 case X86ISD::FHADD:
33568 case X86ISD::FHSUB: {
33569 APInt DemandedLHS, DemandedRHS;
33570 getHorizDemandedElts(VT, DemandedElts, DemandedLHS, DemandedRHS);
33571
33572 APInt LHSUndef, LHSZero;
33573 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedLHS, LHSUndef,
33574 LHSZero, TLO, Depth + 1))
33575 return true;
33576 APInt RHSUndef, RHSZero;
33577 if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedRHS, RHSUndef,
33578 RHSZero, TLO, Depth + 1))
33579 return true;
33580 break;
33581 }
33582 case X86ISD::VTRUNC:
33583 case X86ISD::VTRUNCS:
33584 case X86ISD::VTRUNCUS: {
33585 SDValue Src = Op.getOperand(0);
33586 MVT SrcVT = Src.getSimpleValueType();
33587 APInt DemandedSrc = DemandedElts.zextOrTrunc(SrcVT.getVectorNumElements());
33588 APInt SrcUndef, SrcZero;
33589 if (SimplifyDemandedVectorElts(Src, DemandedSrc, SrcUndef, SrcZero, TLO,
33590 Depth + 1))
33591 return true;
33592 KnownZero = SrcZero.zextOrTrunc(NumElts);
33593 KnownUndef = SrcUndef.zextOrTrunc(NumElts);
33594 break;
33595 }
33596 case X86ISD::BLENDV: {
33597 APInt SelUndef, SelZero;
33598 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, SelUndef,
33599 SelZero, TLO, Depth + 1))
33600 return true;
33601
33602 // TODO: Use SelZero to adjust LHS/RHS DemandedElts.
33603 APInt LHSUndef, LHSZero;
33604 if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedElts, LHSUndef,
33605 LHSZero, TLO, Depth + 1))
33606 return true;
33607
33608 APInt RHSUndef, RHSZero;
33609 if (SimplifyDemandedVectorElts(Op.getOperand(2), DemandedElts, RHSUndef,
33610 RHSZero, TLO, Depth + 1))
33611 return true;
33612
33613 KnownZero = LHSZero & RHSZero;
33614 KnownUndef = LHSUndef & RHSUndef;
33615 break;
33616 }
33617 case X86ISD::VBROADCAST: {
33618 SDValue Src = Op.getOperand(0);
33619 MVT SrcVT = Src.getSimpleValueType();
33620 if (!SrcVT.isVector())
33621 return false;
33622 // Don't bother broadcasting if we just need the 0'th element.
33623 if (DemandedElts == 1) {
33624 if (Src.getValueType() != VT)
33625 Src = widenSubVector(VT.getSimpleVT(), Src, false, Subtarget, TLO.DAG,
33626 SDLoc(Op));
33627 return TLO.CombineTo(Op, Src);
33628 }
33629 APInt SrcUndef, SrcZero;
33630 APInt SrcElts = APInt::getOneBitSet(SrcVT.getVectorNumElements(), 0);
33631 if (SimplifyDemandedVectorElts(Src, SrcElts, SrcUndef, SrcZero, TLO,
33632 Depth + 1))
33633 return true;
33634 break;
33635 }
33636 case X86ISD::SUBV_BROADCAST: {
33637 // Reduce size of broadcast if we don't need the upper half.
33638 unsigned HalfElts = NumElts / 2;
33639 if (DemandedElts.extractBits(HalfElts, HalfElts).isNullValue()) {
33640 SDValue Src = Op.getOperand(0);
33641 MVT SrcVT = Src.getSimpleValueType();
33642
33643 SDValue Half = Src;
33644 if (SrcVT.getVectorNumElements() != HalfElts) {
33645 MVT HalfVT = MVT::getVectorVT(SrcVT.getScalarType(), HalfElts);
33646 Half = TLO.DAG.getNode(X86ISD::SUBV_BROADCAST, SDLoc(Op), HalfVT, Src);
33647 }
33648
33649 return TLO.CombineTo(Op, insertSubVector(TLO.DAG.getUNDEF(VT), Half, 0,
33650 TLO.DAG, SDLoc(Op),
33651 Half.getValueSizeInBits()));
33652 }
33653 break;
33654 }
33655 case X86ISD::VPERMV: {
33656 SDValue Mask = Op.getOperand(0);
33657 APInt MaskUndef, MaskZero;
33658 if (SimplifyDemandedVectorElts(Mask, DemandedElts, MaskUndef, MaskZero, TLO,
33659 Depth + 1))
33660 return true;
33661 break;
33662 }
33663 case X86ISD::PSHUFB:
33664 case X86ISD::VPERMV3:
33665 case X86ISD::VPERMILPV: {
33666 SDValue Mask = Op.getOperand(1);
33667 APInt MaskUndef, MaskZero;
33668 if (SimplifyDemandedVectorElts(Mask, DemandedElts, MaskUndef, MaskZero, TLO,
33669 Depth + 1))
33670 return true;
33671 break;
33672 }
33673 case X86ISD::VPPERM:
33674 case X86ISD::VPERMIL2: {
33675 SDValue Mask = Op.getOperand(2);
33676 APInt MaskUndef, MaskZero;
33677 if (SimplifyDemandedVectorElts(Mask, DemandedElts, MaskUndef, MaskZero, TLO,
33678 Depth + 1))
33679 return true;
33680 break;
33681 }
33682 }
33683
33684 // For 256/512-bit ops that are 128/256-bit ops glued together, if we do not
33685 // demand any of the high elements, then narrow the op to 128/256-bits: e.g.
33686 // (op ymm0, ymm1) --> insert undef, (op xmm0, xmm1), 0
33687 if ((VT.is256BitVector() || VT.is512BitVector()) &&
33688 DemandedElts.lshr(NumElts / 2) == 0) {
33689 unsigned SizeInBits = VT.getSizeInBits();
33690 unsigned ExtSizeInBits = SizeInBits / 2;
33691
33692 // See if 512-bit ops only use the bottom 128-bits.
33693 if (VT.is512BitVector() && DemandedElts.lshr(NumElts / 4) == 0)
33694 ExtSizeInBits = SizeInBits / 4;
33695
33696 switch (Opc) {
33697 // Zero upper elements.
33698 case X86ISD::VZEXT_MOVL: {
33699 SDLoc DL(Op);
33700 SDValue Ext0 =
33701 extractSubVector(Op.getOperand(0), 0, TLO.DAG, DL, ExtSizeInBits);
33702 SDValue ExtOp =
33703 TLO.DAG.getNode(Opc, DL, Ext0.getValueType(), Ext0);
33704 SDValue UndefVec = TLO.DAG.getUNDEF(VT);
33705 SDValue Insert =
33706 insertSubVector(UndefVec, ExtOp, 0, TLO.DAG, DL, ExtSizeInBits);
33707 return TLO.CombineTo(Op, Insert);
33708 }
33709 // Byte shifts by immediate.
33710 case X86ISD::VSHLDQ:
33711 case X86ISD::VSRLDQ:
33712 // Shift by uniform.
33713 case X86ISD::VSHL:
33714 case X86ISD::VSRL:
33715 case X86ISD::VSRA:
33716 // Shift by immediate.
33717 case X86ISD::VSHLI:
33718 case X86ISD::VSRLI:
33719 case X86ISD::VSRAI: {
33720 SDLoc DL(Op);
33721 SDValue Ext0 =
33722 extractSubVector(Op.getOperand(0), 0, TLO.DAG, DL, ExtSizeInBits);
33723 SDValue ExtOp =
33724 TLO.DAG.getNode(Opc, DL, Ext0.getValueType(), Ext0, Op.getOperand(1));
33725 SDValue UndefVec = TLO.DAG.getUNDEF(VT);
33726 SDValue Insert =
33727 insertSubVector(UndefVec, ExtOp, 0, TLO.DAG, DL, ExtSizeInBits);
33728 return TLO.CombineTo(Op, Insert);
33729 }
33730 // Arithmetic Ops.
33731 case X86ISD::PMULDQ:
33732 case X86ISD::PMULUDQ:
33733 // Target Shuffles.
33734 case X86ISD::PSHUFB:
33735 case X86ISD::UNPCKL:
33736 case X86ISD::UNPCKH:
33737 // Saturated Packs.
33738 case X86ISD::PACKSS:
33739 case X86ISD::PACKUS:
33740 // Horizontal Ops.
33741 case X86ISD::HADD:
33742 case X86ISD::HSUB:
33743 case X86ISD::FHADD:
33744 case X86ISD::FHSUB: {
33745 SDLoc DL(Op);
33746 MVT ExtVT = VT.getSimpleVT();
33747 ExtVT = MVT::getVectorVT(ExtVT.getScalarType(),
33748 ExtSizeInBits / ExtVT.getScalarSizeInBits());
33749 SDValue Ext0 =
33750 extractSubVector(Op.getOperand(0), 0, TLO.DAG, DL, ExtSizeInBits);
33751 SDValue Ext1 =
33752 extractSubVector(Op.getOperand(1), 0, TLO.DAG, DL, ExtSizeInBits);
33753 SDValue ExtOp = TLO.DAG.getNode(Opc, DL, ExtVT, Ext0, Ext1);
33754 SDValue UndefVec = TLO.DAG.getUNDEF(VT);
33755 SDValue Insert =
33756 insertSubVector(UndefVec, ExtOp, 0, TLO.DAG, DL, ExtSizeInBits);
33757 return TLO.CombineTo(Op, Insert);
33758 }
33759 }
33760 }
33761
33762 // Simplify target shuffles.
33763 if (!isTargetShuffle(Opc) || !VT.isSimple())
33764 return false;
33765
33766 // Get target shuffle mask.
33767 bool IsUnary;
33768 SmallVector<int, 64> OpMask;
33769 SmallVector<SDValue, 2> OpInputs;
33770 if (!getTargetShuffleMask(Op.getNode(), VT.getSimpleVT(), true, OpInputs,
33771 OpMask, IsUnary))
33772 return false;
33773
33774 // Shuffle inputs must be the same type as the result.
33775 if (llvm::any_of(OpInputs,
33776 [VT](SDValue V) { return VT != V.getValueType(); }))
33777 return false;
33778
33779 // Clear known elts that might have been set above.
33780 KnownZero.clearAllBits();
33781 KnownUndef.clearAllBits();
33782
33783 // Check if shuffle mask can be simplified to undef/zero/identity.
33784 int NumSrcs = OpInputs.size();
33785 for (int i = 0; i != NumElts; ++i) {
33786 int &M = OpMask[i];
33787 if (!DemandedElts[i])
33788 M = SM_SentinelUndef;
33789 else if (0 <= M && OpInputs[M / NumElts].isUndef())
33790 M = SM_SentinelUndef;
33791 }
33792
33793 if (isUndefInRange(OpMask, 0, NumElts)) {
33794 KnownUndef.setAllBits();
33795 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
33796 }
33797 if (isUndefOrZeroInRange(OpMask, 0, NumElts)) {
33798 KnownZero.setAllBits();
33799 return TLO.CombineTo(
33800 Op, getZeroVector(VT.getSimpleVT(), Subtarget, TLO.DAG, SDLoc(Op)));
33801 }
33802 for (int Src = 0; Src != NumSrcs; ++Src)
33803 if (isSequentialOrUndefInRange(OpMask, 0, NumElts, Src * NumElts))
33804 return TLO.CombineTo(Op, OpInputs[Src]);
33805
33806 // Attempt to simplify inputs.
33807 for (int Src = 0; Src != NumSrcs; ++Src) {
33808 int Lo = Src * NumElts;
33809 APInt SrcElts = APInt::getNullValue(NumElts);
33810 for (int i = 0; i != NumElts; ++i)
33811 if (DemandedElts[i]) {
33812 int M = OpMask[i] - Lo;
33813 if (0 <= M && M < NumElts)
33814 SrcElts.setBit(M);
33815 }
33816
33817 APInt SrcUndef, SrcZero;
33818 if (SimplifyDemandedVectorElts(OpInputs[Src], SrcElts, SrcUndef, SrcZero,
33819 TLO, Depth + 1))
33820 return true;
33821 }
33822
33823 // Extract known zero/undef elements.
33824 // TODO - Propagate input undef/zero elts.
33825 for (int i = 0; i != NumElts; ++i) {
33826 if (OpMask[i] == SM_SentinelUndef)
33827 KnownUndef.setBit(i);
33828 if (OpMask[i] == SM_SentinelZero)
33829 KnownZero.setBit(i);
33830 }
33831
33832 return false;
33833}
33834
33835bool X86TargetLowering::SimplifyDemandedBitsForTargetNode(
33836 SDValue Op, const APInt &OriginalDemandedBits,
33837 const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO,
33838 unsigned Depth) const {
33839 EVT VT = Op.getValueType();
33840 unsigned BitWidth = OriginalDemandedBits.getBitWidth();
33841 unsigned Opc = Op.getOpcode();
33842 switch(Opc) {
33843 case X86ISD::PMULDQ:
33844 case X86ISD::PMULUDQ: {
33845 // PMULDQ/PMULUDQ only uses lower 32 bits from each vector element.
33846 KnownBits KnownOp;
33847 SDValue LHS = Op.getOperand(0);
33848 SDValue RHS = Op.getOperand(1);
33849 // FIXME: Can we bound this better?
33850 APInt DemandedMask = APInt::getLowBitsSet(64, 32);
33851 if (SimplifyDemandedBits(LHS, DemandedMask, OriginalDemandedElts, KnownOp,
33852 TLO, Depth + 1))
33853 return true;
33854 if (SimplifyDemandedBits(RHS, DemandedMask, OriginalDemandedElts, KnownOp,
33855 TLO, Depth + 1))
33856 return true;
33857 break;
33858 }
33859 case X86ISD::VSHLI: {
33860 SDValue Op0 = Op.getOperand(0);
33861 SDValue Op1 = Op.getOperand(1);
33862
33863 if (auto *ShiftImm = dyn_cast<ConstantSDNode>(Op1)) {
33864 if (ShiftImm->getAPIntValue().uge(BitWidth))
33865 break;
33866
33867 unsigned ShAmt = ShiftImm->getZExtValue();
33868 APInt DemandedMask = OriginalDemandedBits.lshr(ShAmt);
33869
33870 // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
33871 // single shift. We can do this if the bottom bits (which are shifted
33872 // out) are never demanded.
33873 if (Op0.getOpcode() == X86ISD::VSRLI &&
33874 OriginalDemandedBits.countTrailingZeros() >= ShAmt) {
33875 if (auto *Shift2Imm = dyn_cast<ConstantSDNode>(Op0.getOperand(1))) {
33876 if (Shift2Imm->getAPIntValue().ult(BitWidth)) {
33877 int Diff = ShAmt - Shift2Imm->getZExtValue();
33878 if (Diff == 0)
33879 return TLO.CombineTo(Op, Op0.getOperand(0));
33880
33881 unsigned NewOpc = Diff < 0 ? X86ISD::VSRLI : X86ISD::VSHLI;
33882 SDValue NewShift = TLO.DAG.getNode(
33883 NewOpc, SDLoc(Op), VT, Op0.getOperand(0),
33884 TLO.DAG.getConstant(std::abs(Diff), SDLoc(Op), MVT::i8));
33885 return TLO.CombineTo(Op, NewShift);
33886 }
33887 }
33888 }
33889
33890 if (SimplifyDemandedBits(Op0, DemandedMask, OriginalDemandedElts, Known,
33891 TLO, Depth + 1))
33892 return true;
33893
33894 assert(!Known.hasConflict() && "Bits known to be one AND zero?")((!Known.hasConflict() && "Bits known to be one AND zero?"
) ? static_cast<void> (0) : __assert_fail ("!Known.hasConflict() && \"Bits known to be one AND zero?\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 33894, __PRETTY_FUNCTION__))
;
33895 Known.Zero <<= ShAmt;
33896 Known.One <<= ShAmt;
33897
33898 // Low bits known zero.
33899 Known.Zero.setLowBits(ShAmt);
33900 }
33901 break;
33902 }
33903 case X86ISD::VSRLI: {
33904 if (auto *ShiftImm = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
33905 if (ShiftImm->getAPIntValue().uge(BitWidth))
33906 break;
33907
33908 unsigned ShAmt = ShiftImm->getZExtValue();
33909 APInt DemandedMask = OriginalDemandedBits << ShAmt;
33910
33911 if (SimplifyDemandedBits(Op.getOperand(0), DemandedMask,
33912 OriginalDemandedElts, Known, TLO, Depth + 1))
33913 return true;
33914
33915 assert(!Known.hasConflict() && "Bits known to be one AND zero?")((!Known.hasConflict() && "Bits known to be one AND zero?"
) ? static_cast<void> (0) : __assert_fail ("!Known.hasConflict() && \"Bits known to be one AND zero?\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 33915, __PRETTY_FUNCTION__))
;
33916 Known.Zero.lshrInPlace(ShAmt);
33917 Known.One.lshrInPlace(ShAmt);
33918
33919 // High bits known zero.
33920 Known.Zero.setHighBits(ShAmt);
33921 }
33922 break;
33923 }
33924 case X86ISD::VSRAI: {
33925 SDValue Op0 = Op.getOperand(0);
33926 SDValue Op1 = Op.getOperand(1);
33927
33928 if (auto *ShiftImm = dyn_cast<ConstantSDNode>(Op1)) {
33929 if (ShiftImm->getAPIntValue().uge(BitWidth))
33930 break;
33931
33932 unsigned ShAmt = ShiftImm->getZExtValue();
33933 APInt DemandedMask = OriginalDemandedBits << ShAmt;
33934
33935 // If we just want the sign bit then we don't need to shift it.
33936 if (OriginalDemandedBits.isSignMask())
33937 return TLO.CombineTo(Op, Op0);
33938
33939 // fold (VSRAI (VSHLI X, C1), C1) --> X iff NumSignBits(X) > C1
33940 if (Op0.getOpcode() == X86ISD::VSHLI && Op1 == Op0.getOperand(1)) {
33941 SDValue Op00 = Op0.getOperand(0);
33942 unsigned NumSignBits =
33943 TLO.DAG.ComputeNumSignBits(Op00, OriginalDemandedElts);
33944 if (ShAmt < NumSignBits)
33945 return TLO.CombineTo(Op, Op00);
33946 }
33947
33948 // If any of the demanded bits are produced by the sign extension, we also
33949 // demand the input sign bit.
33950 if (OriginalDemandedBits.countLeadingZeros() < ShAmt)
33951 DemandedMask.setSignBit();
33952
33953 if (SimplifyDemandedBits(Op0, DemandedMask, OriginalDemandedElts, Known,
33954 TLO, Depth + 1))
33955 return true;
33956
33957 assert(!Known.hasConflict() && "Bits known to be one AND zero?")((!Known.hasConflict() && "Bits known to be one AND zero?"
) ? static_cast<void> (0) : __assert_fail ("!Known.hasConflict() && \"Bits known to be one AND zero?\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 33957, __PRETTY_FUNCTION__))
;
33958 Known.Zero.lshrInPlace(ShAmt);
33959 Known.One.lshrInPlace(ShAmt);
33960
33961 // If the input sign bit is known to be zero, or if none of the top bits
33962 // are demanded, turn this into an unsigned shift right.
33963 if (Known.Zero[BitWidth - ShAmt - 1] ||
33964 OriginalDemandedBits.countLeadingZeros() >= ShAmt)
33965 return TLO.CombineTo(
33966 Op, TLO.DAG.getNode(X86ISD::VSRLI, SDLoc(Op), VT, Op0, Op1));
33967
33968 // High bits are known one.
33969 if (Known.One[BitWidth - ShAmt - 1])
33970 Known.One.setHighBits(ShAmt);
33971 }
33972 break;
33973 }
33974 case X86ISD::PEXTRB:
33975 case X86ISD::PEXTRW: {
33976 SDValue Vec = Op.getOperand(0);
33977 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
33978 MVT VecVT = Vec.getSimpleValueType();
33979 unsigned NumVecElts = VecVT.getVectorNumElements();
33980
33981 if (CIdx && CIdx->getAPIntValue().ult(NumVecElts)) {
33982 unsigned Idx = CIdx->getZExtValue();
33983 unsigned VecBitWidth = VecVT.getScalarSizeInBits();
33984
33985 // If we demand no bits from the vector then we must have demanded
33986 // bits from the implict zext - simplify to zero.
33987 APInt DemandedVecBits = OriginalDemandedBits.trunc(VecBitWidth);
33988 if (DemandedVecBits == 0)
33989 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
33990
33991 APInt KnownUndef, KnownZero;
33992 APInt DemandedVecElts = APInt::getOneBitSet(NumVecElts, Idx);
33993 if (SimplifyDemandedVectorElts(Vec, DemandedVecElts, KnownUndef,
33994 KnownZero, TLO, Depth + 1))
33995 return true;
33996
33997 KnownBits KnownVec;
33998 if (SimplifyDemandedBits(Vec, DemandedVecBits, DemandedVecElts,
33999 KnownVec, TLO, Depth + 1))
34000 return true;
34001
34002 Known = KnownVec.zext(BitWidth, true);
34003 return false;
34004 }
34005 break;
34006 }
34007 case X86ISD::PINSRB:
34008 case X86ISD::PINSRW: {
34009 SDValue Vec = Op.getOperand(0);
34010 SDValue Scl = Op.getOperand(1);
34011 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
34012 MVT VecVT = Vec.getSimpleValueType();
34013
34014 if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements())) {
34015 unsigned Idx = CIdx->getZExtValue();
34016 if (!OriginalDemandedElts[Idx])
34017 return TLO.CombineTo(Op, Vec);
34018
34019 KnownBits KnownVec;
34020 APInt DemandedVecElts(OriginalDemandedElts);
34021 DemandedVecElts.clearBit(Idx);
34022 if (SimplifyDemandedBits(Vec, OriginalDemandedBits, DemandedVecElts,
34023 KnownVec, TLO, Depth + 1))
34024 return true;
34025
34026 KnownBits KnownScl;
34027 unsigned NumSclBits = Scl.getScalarValueSizeInBits();
34028 APInt DemandedSclBits = OriginalDemandedBits.zext(NumSclBits);
34029 if (SimplifyDemandedBits(Scl, DemandedSclBits, KnownScl, TLO, Depth + 1))
34030 return true;
34031
34032 KnownScl = KnownScl.trunc(VecVT.getScalarSizeInBits());
34033 Known.One = KnownVec.One & KnownScl.One;
34034 Known.Zero = KnownVec.Zero & KnownScl.Zero;
34035 return false;
34036 }
34037 break;
34038 }
34039 case X86ISD::PACKSS:
34040 // PACKSS saturates to MIN/MAX integer values. So if we just want the
34041 // sign bit then we can just ask for the source operands sign bit.
34042 // TODO - add known bits handling.
34043 if (OriginalDemandedBits.isSignMask()) {
34044 APInt DemandedLHS, DemandedRHS;
34045 getPackDemandedElts(VT, OriginalDemandedElts, DemandedLHS, DemandedRHS);
34046
34047 KnownBits KnownLHS, KnownRHS;
34048 APInt SignMask = APInt::getSignMask(BitWidth * 2);
34049 if (SimplifyDemandedBits(Op.getOperand(0), SignMask, DemandedLHS,
34050 KnownLHS, TLO, Depth + 1))
34051 return true;
34052 if (SimplifyDemandedBits(Op.getOperand(1), SignMask, DemandedRHS,
34053 KnownRHS, TLO, Depth + 1))
34054 return true;
34055 }
34056 // TODO - add general PACKSS/PACKUS SimplifyDemandedBits support.
34057 break;
34058 case X86ISD::PCMPGT:
34059 // icmp sgt(0, R) == ashr(R, BitWidth-1).
34060 // iff we only need the sign bit then we can use R directly.
34061 if (OriginalDemandedBits.isSignMask() &&
34062 ISD::isBuildVectorAllZeros(Op.getOperand(0).getNode()))
34063 return TLO.CombineTo(Op, Op.getOperand(1));
34064 break;
34065 case X86ISD::MOVMSK: {
34066 SDValue Src = Op.getOperand(0);
34067 MVT SrcVT = Src.getSimpleValueType();
34068 unsigned SrcBits = SrcVT.getScalarSizeInBits();
34069 unsigned NumElts = SrcVT.getVectorNumElements();
34070
34071 // If we don't need the sign bits at all just return zero.
34072 if (OriginalDemandedBits.countTrailingZeros() >= NumElts)
34073 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
34074
34075 // Only demand the vector elements of the sign bits we need.
34076 APInt KnownUndef, KnownZero;
34077 APInt DemandedElts = OriginalDemandedBits.zextOrTrunc(NumElts);
34078 if (SimplifyDemandedVectorElts(Src, DemandedElts, KnownUndef, KnownZero,
34079 TLO, Depth + 1))
34080 return true;
34081
34082 Known.Zero = KnownZero.zextOrSelf(BitWidth);
34083 Known.Zero.setHighBits(BitWidth - NumElts);
34084
34085 // MOVMSK only uses the MSB from each vector element.
34086 KnownBits KnownSrc;
34087 if (SimplifyDemandedBits(Src, APInt::getSignMask(SrcBits), DemandedElts,
34088 KnownSrc, TLO, Depth + 1))
34089 return true;
34090
34091 if (KnownSrc.One[SrcBits - 1])
34092 Known.One.setLowBits(NumElts);
34093 else if (KnownSrc.Zero[SrcBits - 1])
34094 Known.Zero.setLowBits(NumElts);
34095 return false;
34096 }
34097 }
34098
34099 return TargetLowering::SimplifyDemandedBitsForTargetNode(
34100 Op, OriginalDemandedBits, OriginalDemandedElts, Known, TLO, Depth);
34101}
34102
34103/// Check if a vector extract from a target-specific shuffle of a load can be
34104/// folded into a single element load.
34105/// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
34106/// shuffles have been custom lowered so we need to handle those here.
34107static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
34108 TargetLowering::DAGCombinerInfo &DCI) {
34109 if (DCI.isBeforeLegalizeOps())
34110 return SDValue();
34111
34112 SDValue InVec = N->getOperand(0);
34113 SDValue EltNo = N->getOperand(1);
34114 EVT EltVT = N->getValueType(0);
34115
34116 if (!isa<ConstantSDNode>(EltNo))
34117 return SDValue();
34118
34119 EVT OriginalVT = InVec.getValueType();
34120
34121 // Peek through bitcasts, don't duplicate a load with other uses.
34122 InVec = peekThroughOneUseBitcasts(InVec);
34123
34124 EVT CurrentVT = InVec.getValueType();
34125 if (!CurrentVT.isVector() ||
34126 CurrentVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
34127 return SDValue();
34128
34129 if (!isTargetShuffle(InVec.getOpcode()))
34130 return SDValue();
34131
34132 // Don't duplicate a load with other uses.
34133 if (!InVec.hasOneUse())
34134 return SDValue();
34135
34136 SmallVector<int, 16> ShuffleMask;
34137 SmallVector<SDValue, 2> ShuffleOps;
34138 bool UnaryShuffle;
34139 if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(), true,
34140 ShuffleOps, ShuffleMask, UnaryShuffle))
34141 return SDValue();
34142
34143 // Select the input vector, guarding against out of range extract vector.
34144 unsigned NumElems = CurrentVT.getVectorNumElements();
34145 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
34146 int Idx = (Elt > (int)NumElems) ? SM_SentinelUndef : ShuffleMask[Elt];
34147
34148 if (Idx == SM_SentinelZero)
34149 return EltVT.isInteger() ? DAG.getConstant(0, SDLoc(N), EltVT)
34150 : DAG.getConstantFP(+0.0, SDLoc(N), EltVT);
34151 if (Idx == SM_SentinelUndef)
34152 return DAG.getUNDEF(EltVT);
34153
34154 // Bail if any mask element is SM_SentinelZero - getVectorShuffle below
34155 // won't handle it.
34156 if (llvm::any_of(ShuffleMask, [](int M) { return M == SM_SentinelZero; }))
34157 return SDValue();
34158
34159 assert(0 <= Idx && Idx < (int)(2 * NumElems) && "Shuffle index out of range")((0 <= Idx && Idx < (int)(2 * NumElems) &&
"Shuffle index out of range") ? static_cast<void> (0) :
__assert_fail ("0 <= Idx && Idx < (int)(2 * NumElems) && \"Shuffle index out of range\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 34159, __PRETTY_FUNCTION__))
;
34160 SDValue LdNode = (Idx < (int)NumElems) ? ShuffleOps[0] : ShuffleOps[1];
34161
34162 // If inputs to shuffle are the same for both ops, then allow 2 uses
34163 unsigned AllowedUses =
34164 (ShuffleOps.size() > 1 && ShuffleOps[0] == ShuffleOps[1]) ? 2 : 1;
34165
34166 if (LdNode.getOpcode() == ISD::BITCAST) {
34167 // Don't duplicate a load with other uses.
34168 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
34169 return SDValue();
34170
34171 AllowedUses = 1; // only allow 1 load use if we have a bitcast
34172 LdNode = LdNode.getOperand(0);
34173 }
34174
34175 if (!ISD::isNormalLoad(LdNode.getNode()))
34176 return SDValue();
34177
34178 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
34179
34180 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
34181 return SDValue();
34182
34183 // If there's a bitcast before the shuffle, check if the load type and
34184 // alignment is valid.
34185 unsigned Align = LN0->getAlignment();
34186 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
34187 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
34188 EltVT.getTypeForEVT(*DAG.getContext()));
34189
34190 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
34191 return SDValue();
34192
34193 // All checks match so transform back to vector_shuffle so that DAG combiner
34194 // can finish the job
34195 SDLoc dl(N);
34196
34197 // Create shuffle node taking into account the case that its a unary shuffle
34198 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT) : ShuffleOps[1];
34199 Shuffle = DAG.getVectorShuffle(CurrentVT, dl, ShuffleOps[0], Shuffle,
34200 ShuffleMask);
34201 Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
34202 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
34203 EltNo);
34204}
34205
34206// Helper to peek through bitops/setcc to determine size of source vector.
34207// Allows combineBitcastvxi1 to determine what size vector generated a <X x i1>.
34208static bool checkBitcastSrcVectorSize(SDValue Src, unsigned Size) {
34209 switch (Src.getOpcode()) {
34210 case ISD::SETCC:
34211 return Src.getOperand(0).getValueSizeInBits() == Size;
34212 case ISD::AND:
34213 case ISD::XOR:
34214 case ISD::OR:
34215 return checkBitcastSrcVectorSize(Src.getOperand(0), Size) &&
34216 checkBitcastSrcVectorSize(Src.getOperand(1), Size);
34217 }
34218 return false;
34219}
34220
34221// Try to match patterns such as
34222// (i16 bitcast (v16i1 x))
34223// ->
34224// (i16 movmsk (16i8 sext (v16i1 x)))
34225// before the illegal vector is scalarized on subtargets that don't have legal
34226// vxi1 types.
34227static SDValue combineBitcastvxi1(SelectionDAG &DAG, EVT VT, SDValue Src,
34228 const SDLoc &DL,
34229 const X86Subtarget &Subtarget) {
34230 EVT SrcVT = Src.getValueType();
34231 if (!SrcVT.isSimple() || SrcVT.getScalarType() != MVT::i1)
34232 return SDValue();
34233
34234 // If the input is a truncate from v16i8 or v32i8 go ahead and use a
34235 // movmskb even with avx512. This will be better than truncating to vXi1 and
34236 // using a kmov. This can especially help KNL if the input is a v16i8/v32i8
34237 // vpcmpeqb/vpcmpgtb.
34238 bool IsTruncated = Src.getOpcode() == ISD::TRUNCATE && Src.hasOneUse() &&
34239 (Src.getOperand(0).getValueType() == MVT::v16i8 ||
34240 Src.getOperand(0).getValueType() == MVT::v32i8 ||
34241 Src.getOperand(0).getValueType() == MVT::v64i8);
34242
34243 // With AVX512 vxi1 types are legal and we prefer using k-regs.
34244 // MOVMSK is supported in SSE2 or later.
34245 if (!Subtarget.hasSSE2() || (Subtarget.hasAVX512() && !IsTruncated))
34246 return SDValue();
34247
34248 // There are MOVMSK flavors for types v16i8, v32i8, v4f32, v8f32, v4f64 and
34249 // v8f64. So all legal 128-bit and 256-bit vectors are covered except for
34250 // v8i16 and v16i16.
34251 // For these two cases, we can shuffle the upper element bytes to a
34252 // consecutive sequence at the start of the vector and treat the results as
34253 // v16i8 or v32i8, and for v16i8 this is the preferable solution. However,
34254 // for v16i16 this is not the case, because the shuffle is expensive, so we
34255 // avoid sign-extending to this type entirely.
34256 // For example, t0 := (v8i16 sext(v8i1 x)) needs to be shuffled as:
34257 // (v16i8 shuffle <0,2,4,6,8,10,12,14,u,u,...,u> (v16i8 bitcast t0), undef)
34258 MVT SExtVT;
34259 switch (SrcVT.getSimpleVT().SimpleTy) {
34260 default:
34261 return SDValue();
34262 case MVT::v2i1:
34263 SExtVT = MVT::v2i64;
34264 break;
34265 case MVT::v4i1:
34266 SExtVT = MVT::v4i32;
34267 // For cases such as (i4 bitcast (v4i1 setcc v4i64 v1, v2))
34268 // sign-extend to a 256-bit operation to avoid truncation.
34269 if (Subtarget.hasAVX() && checkBitcastSrcVectorSize(Src, 256))
34270 SExtVT = MVT::v4i64;
34271 break;
34272 case MVT::v8i1:
34273 SExtVT = MVT::v8i16;
34274 // For cases such as (i8 bitcast (v8i1 setcc v8i32 v1, v2)),
34275 // sign-extend to a 256-bit operation to match the compare.
34276 // If the setcc operand is 128-bit, prefer sign-extending to 128-bit over
34277 // 256-bit because the shuffle is cheaper than sign extending the result of
34278 // the compare.
34279 // TODO : use checkBitcastSrcVectorSize
34280 if (Src.getOpcode() == ISD::SETCC && Subtarget.hasAVX() &&
34281 (Src.getOperand(0).getValueType().is256BitVector() ||
34282 Src.getOperand(0).getValueType().is512BitVector())) {
34283 SExtVT = MVT::v8i32;
34284 }
34285 break;
34286 case MVT::v16i1:
34287 SExtVT = MVT::v16i8;
34288 // For the case (i16 bitcast (v16i1 setcc v16i16 v1, v2)),
34289 // it is not profitable to sign-extend to 256-bit because this will
34290 // require an extra cross-lane shuffle which is more expensive than
34291 // truncating the result of the compare to 128-bits.
34292 break;
34293 case MVT::v32i1:
34294 SExtVT = MVT::v32i8;
34295 break;
34296 case MVT::v64i1:
34297 // If we have AVX512F, but not AVX512BW and the input is truncated from
34298 // v64i8 checked earlier. Then split the input and make two pmovmskbs.
34299 if (Subtarget.hasAVX512() && !Subtarget.hasBWI()) {
34300 SExtVT = MVT::v64i8;
34301 break;
34302 }
34303 return SDValue();
34304 };
34305
34306 SDValue V = DAG.getNode(ISD::SIGN_EXTEND, DL, SExtVT, Src);
34307
34308 if (SExtVT == MVT::v64i8) {
34309 SDValue Lo, Hi;
34310 std::tie(Lo, Hi) = DAG.SplitVector(V, DL);
34311 Lo = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Lo);
34312 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Lo);
34313 Hi = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Hi);
34314 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Hi);
34315 Hi = DAG.getNode(ISD::SHL, DL, MVT::i64, Hi,
34316 DAG.getConstant(32, DL, MVT::i8));
34317 V = DAG.getNode(ISD::OR, DL, MVT::i64, Lo, Hi);
34318 } else if (SExtVT == MVT::v16i8 || SExtVT == MVT::v32i8) {
34319 V = getPMOVMSKB(DL, V, DAG, Subtarget);
34320 } else {
34321 if (SExtVT == MVT::v8i16)
34322 V = DAG.getNode(X86ISD::PACKSS, DL, MVT::v16i8, V,
34323 DAG.getUNDEF(MVT::v8i16));
34324 V = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, V);
34325 }
34326
34327 EVT IntVT =
34328 EVT::getIntegerVT(*DAG.getContext(), SrcVT.getVectorNumElements());
34329 V = DAG.getZExtOrTrunc(V, DL, IntVT);
34330 return DAG.getBitcast(VT, V);
34331}
34332
34333// Convert a vXi1 constant build vector to the same width scalar integer.
34334static SDValue combinevXi1ConstantToInteger(SDValue Op, SelectionDAG &DAG) {
34335 EVT SrcVT = Op.getValueType();
34336 assert(SrcVT.getVectorElementType() == MVT::i1 &&((SrcVT.getVectorElementType() == MVT::i1 && "Expected a vXi1 vector"
) ? static_cast<void> (0) : __assert_fail ("SrcVT.getVectorElementType() == MVT::i1 && \"Expected a vXi1 vector\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 34337, __PRETTY_FUNCTION__))
34337 "Expected a vXi1 vector")((SrcVT.getVectorElementType() == MVT::i1 && "Expected a vXi1 vector"
) ? static_cast<void> (0) : __assert_fail ("SrcVT.getVectorElementType() == MVT::i1 && \"Expected a vXi1 vector\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 34337, __PRETTY_FUNCTION__))
;
34338 assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&((ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
"Expected a constant build vector") ? static_cast<void>
(0) : __assert_fail ("ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) && \"Expected a constant build vector\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 34339, __PRETTY_FUNCTION__))
34339 "Expected a constant build vector")((ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
"Expected a constant build vector") ? static_cast<void>
(0) : __assert_fail ("ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) && \"Expected a constant build vector\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 34339, __PRETTY_FUNCTION__))
;
34340
34341 APInt Imm(SrcVT.getVectorNumElements(), 0);
34342 for (unsigned Idx = 0, e = Op.getNumOperands(); Idx < e; ++Idx) {
34343 SDValue In = Op.getOperand(Idx);
34344 if (!In.isUndef() && (cast<ConstantSDNode>(In)->getZExtValue() & 0x1))
34345 Imm.setBit(Idx);
34346 }
34347 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), Imm.getBitWidth());
34348 return DAG.getConstant(Imm, SDLoc(Op), IntVT);
34349}
34350
34351static SDValue combineCastedMaskArithmetic(SDNode *N, SelectionDAG &DAG,
34352 TargetLowering::DAGCombinerInfo &DCI,
34353 const X86Subtarget &Subtarget) {
34354 assert(N->getOpcode() == ISD::BITCAST && "Expected a bitcast")((N->getOpcode() == ISD::BITCAST && "Expected a bitcast"
) ? static_cast<void> (0) : __assert_fail ("N->getOpcode() == ISD::BITCAST && \"Expected a bitcast\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 34354, __PRETTY_FUNCTION__))
;
34355
34356 if (!DCI.isBeforeLegalizeOps())
34357 return SDValue();
34358
34359 // Only do this if we have k-registers.
34360 if (!Subtarget.hasAVX512())
34361 return SDValue();
34362
34363 EVT DstVT = N->getValueType(0);
34364 SDValue Op = N->getOperand(0);
34365 EVT SrcVT = Op.getValueType();
34366
34367 if (!Op.hasOneUse())
34368 return SDValue();
34369
34370 // Look for logic ops.
34371 if (Op.getOpcode() != ISD::AND &&
34372 Op.getOpcode() != ISD::OR &&
34373 Op.getOpcode() != ISD::XOR)
34374 return SDValue();
34375
34376 // Make sure we have a bitcast between mask registers and a scalar type.
34377 if (!(SrcVT.isVector() && SrcVT.getVectorElementType() == MVT::i1 &&
34378 DstVT.isScalarInteger()) &&
34379 !(DstVT.isVector() && DstVT.getVectorElementType() == MVT::i1 &&
34380 SrcVT.isScalarInteger()))
34381 return SDValue();
34382
34383 SDValue LHS = Op.getOperand(0);
34384 SDValue RHS = Op.getOperand(1);
34385
34386 if (LHS.hasOneUse() && LHS.getOpcode() == ISD::BITCAST &&
34387 LHS.getOperand(0).getValueType() == DstVT)
34388 return DAG.getNode(Op.getOpcode(), SDLoc(N), DstVT, LHS.getOperand(0),
34389 DAG.getBitcast(DstVT, RHS));
34390
34391 if (RHS.hasOneUse() && RHS.getOpcode() == ISD::BITCAST &&
34392 RHS.getOperand(0).getValueType() == DstVT)
34393 return DAG.getNode(Op.getOpcode(), SDLoc(N), DstVT,
34394 DAG.getBitcast(DstVT, LHS), RHS.getOperand(0));
34395
34396 // If the RHS is a vXi1 build vector, this is a good reason to flip too.
34397 // Most of these have to move a constant from the scalar domain anyway.
34398 if (ISD::isBuildVectorOfConstantSDNodes(RHS.getNode())) {
34399 RHS = combinevXi1ConstantToInteger(RHS, DAG);
34400 return DAG.getNode(Op.getOpcode(), SDLoc(N), DstVT,
34401 DAG.getBitcast(DstVT, LHS), RHS);
34402 }
34403
34404 return SDValue();
34405}
34406
34407static SDValue createMMXBuildVector(SDValue N, SelectionDAG &DAG,
34408 const X86Subtarget &Subtarget) {
34409 SDLoc DL(N);
34410 unsigned NumElts = N.getNumOperands();
34411
34412 auto *BV = cast<BuildVectorSDNode>(N);
34413 SDValue Splat = BV->getSplatValue();
34414
34415 // Build MMX element from integer GPR or SSE float values.
34416 auto CreateMMXElement = [&](SDValue V) {
34417 if (V.isUndef())
34418 return DAG.getUNDEF(MVT::x86mmx);
34419 if (V.getValueType().isFloatingPoint()) {
34420 if (Subtarget.hasSSE1() && !isa<ConstantFPSDNode>(V)) {
34421 V = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v4f32, V);
34422 V = DAG.getBitcast(MVT::v2i64, V);
34423 return DAG.getNode(X86ISD::MOVDQ2Q, DL, MVT::x86mmx, V);
34424 }
34425 V = DAG.getBitcast(MVT::i32, V);
34426 } else {
34427 V = DAG.getAnyExtOrTrunc(V, DL, MVT::i32);
34428 }
34429 return DAG.getNode(X86ISD::MMX_MOVW2D, DL, MVT::x86mmx, V);
34430 };
34431
34432 // Convert build vector ops to MMX data in the bottom elements.
34433 SmallVector<SDValue, 8> Ops;
34434
34435 // Broadcast - use (PUNPCKL+)PSHUFW to broadcast single element.
34436 if (Splat) {
34437 if (Splat.isUndef())
34438 return DAG.getUNDEF(MVT::x86mmx);
34439
34440 Splat = CreateMMXElement(Splat);
34441
34442 if (Subtarget.hasSSE1()) {
34443 // Unpack v8i8 to splat i8 elements to lowest 16-bits.
34444 if (NumElts == 8)
34445 Splat = DAG.getNode(
34446 ISD::INTRINSIC_WO_CHAIN, DL, MVT::x86mmx,
34447 DAG.getConstant(Intrinsic::x86_mmx_punpcklbw, DL, MVT::i32), Splat,
34448 Splat);
34449
34450 // Use PSHUFW to repeat 16-bit elements.
34451 unsigned ShufMask = (NumElts > 2 ? 0 : 0x44);
34452 return DAG.getNode(
34453 ISD::INTRINSIC_WO_CHAIN, DL, MVT::x86mmx,
34454 DAG.getConstant(Intrinsic::x86_sse_pshuf_w, DL, MVT::i32), Splat,
34455 DAG.getConstant(ShufMask, DL, MVT::i8));
34456 }
34457 Ops.append(NumElts, Splat);
34458 } else {
34459 for (unsigned i = 0; i != NumElts; ++i)
34460 Ops.push_back(CreateMMXElement(N.getOperand(i)));
34461 }
34462
34463 // Use tree of PUNPCKLs to build up general MMX vector.
34464 while (Ops.size() > 1) {
34465 unsigned NumOps = Ops.size();
34466 unsigned IntrinOp =
34467 (NumOps == 2 ? Intrinsic::x86_mmx_punpckldq
34468 : (NumOps == 4 ? Intrinsic::x86_mmx_punpcklwd
34469 : Intrinsic::x86_mmx_punpcklbw));
34470 SDValue Intrin = DAG.getConstant(IntrinOp, DL, MVT::i32);
34471 for (unsigned i = 0; i != NumOps; i += 2)
34472 Ops[i / 2] = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, MVT::x86mmx, Intrin,
34473 Ops[i], Ops[i + 1]);
34474 Ops.resize(NumOps / 2);
34475 }
34476
34477 return Ops[0];
34478}
34479
34480static SDValue combineBitcast(SDNode *N, SelectionDAG &DAG,
34481 TargetLowering::DAGCombinerInfo &DCI,
34482 const X86Subtarget &Subtarget) {
34483 SDValue N0 = N->getOperand(0);
34484 EVT VT = N->getValueType(0);
34485 EVT SrcVT = N0.getValueType();
34486
34487 // Try to match patterns such as
34488 // (i16 bitcast (v16i1 x))
34489 // ->
34490 // (i16 movmsk (16i8 sext (v16i1 x)))
34491 // before the setcc result is scalarized on subtargets that don't have legal
34492 // vxi1 types.
34493 if (DCI.isBeforeLegalize()) {
34494 SDLoc dl(N);
34495 if (SDValue V = combineBitcastvxi1(DAG, VT, N0, dl, Subtarget))
34496 return V;
34497
34498 // If this is a bitcast between a MVT::v4i1/v2i1 and an illegal integer
34499 // type, widen both sides to avoid a trip through memory.
34500 if ((VT == MVT::v4i1 || VT == MVT::v2i1) && SrcVT.isScalarInteger() &&
34501 Subtarget.hasAVX512()) {
34502 N0 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i8, N0);
34503 N0 = DAG.getBitcast(MVT::v8i1, N0);
34504 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, N0,
34505 DAG.getIntPtrConstant(0, dl));
34506 }
34507
34508 // If this is a bitcast between a MVT::v4i1/v2i1 and an illegal integer
34509 // type, widen both sides to avoid a trip through memory.
34510 if ((SrcVT == MVT::v4i1 || SrcVT == MVT::v2i1) && VT.isScalarInteger() &&
34511 Subtarget.hasAVX512()) {
34512 unsigned NumConcats = 8 / SrcVT.getVectorNumElements();
34513 SmallVector<SDValue, 4> Ops(NumConcats, DAG.getUNDEF(SrcVT));
34514 Ops[0] = N0;
34515 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i1, Ops);
34516 N0 = DAG.getBitcast(MVT::i8, N0);
34517 return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
34518 }
34519 }
34520
34521 // Since MMX types are special and don't usually play with other vector types,
34522 // it's better to handle them early to be sure we emit efficient code by
34523 // avoiding store-load conversions.
34524 if (VT == MVT::x86mmx) {
34525 // Detect MMX constant vectors.
34526 APInt UndefElts;
34527 SmallVector<APInt, 1> EltBits;
34528 if (getTargetConstantBitsFromNode(N0, 64, UndefElts, EltBits)) {
34529 SDLoc DL(N0);
34530 // Handle zero-extension of i32 with MOVD.
34531 if (EltBits[0].countLeadingZeros() >= 32)
34532 return DAG.getNode(X86ISD::MMX_MOVW2D, DL, VT,
34533 DAG.getConstant(EltBits[0].trunc(32), DL, MVT::i32));
34534 // Else, bitcast to a double.
34535 // TODO - investigate supporting sext 32-bit immediates on x86_64.
34536 APFloat F64(APFloat::IEEEdouble(), EltBits[0]);
34537 return DAG.getBitcast(VT, DAG.getConstantFP(F64, DL, MVT::f64));
34538 }
34539
34540 // Detect bitcasts to x86mmx low word.
34541 if (N0.getOpcode() == ISD::BUILD_VECTOR &&
34542 (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) &&
34543 N0.getOperand(0).getValueType() == SrcVT.getScalarType()) {
34544 bool LowUndef = true, AllUndefOrZero = true;
34545 for (unsigned i = 1, e = SrcVT.getVectorNumElements(); i != e; ++i) {
34546 SDValue Op = N0.getOperand(i);
34547 LowUndef &= Op.isUndef() || (i >= e/2);
34548 AllUndefOrZero &= (Op.isUndef() || isNullConstant(Op));
34549 }
34550 if (AllUndefOrZero) {
34551 SDValue N00 = N0.getOperand(0);
34552 SDLoc dl(N00);
34553 N00 = LowUndef ? DAG.getAnyExtOrTrunc(N00, dl, MVT::i32)
34554 : DAG.getZExtOrTrunc(N00, dl, MVT::i32);
34555 return DAG.getNode(X86ISD::MMX_MOVW2D, dl, VT, N00);
34556 }
34557 }
34558
34559 // Detect bitcasts of 64-bit build vectors and convert to a
34560 // MMX UNPCK/PSHUFW which takes MMX type inputs with the value in the
34561 // lowest element.
34562 if (N0.getOpcode() == ISD::BUILD_VECTOR &&
34563 (SrcVT == MVT::v2f32 || SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 ||
34564 SrcVT == MVT::v8i8))
34565 return createMMXBuildVector(N0, DAG, Subtarget);
34566
34567 // Detect bitcasts between element or subvector extraction to x86mmx.
34568 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
34569 N0.getOpcode() == ISD::EXTRACT_SUBVECTOR) &&
34570 isNullConstant(N0.getOperand(1))) {
34571 SDValue N00 = N0.getOperand(0);
34572 if (N00.getValueType().is128BitVector())
34573 return DAG.getNode(X86ISD::MOVDQ2Q, SDLoc(N00), VT,
34574 DAG.getBitcast(MVT::v2i64, N00));
34575 }
34576
34577 // Detect bitcasts from FP_TO_SINT to x86mmx.
34578 if (SrcVT == MVT::v2i32 && N0.getOpcode() == ISD::FP_TO_SINT) {
34579 SDLoc DL(N0);
34580 SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4i32, N0,
34581 DAG.getUNDEF(MVT::v2i32));
34582 return DAG.getNode(X86ISD::MOVDQ2Q, DL, VT,
34583 DAG.getBitcast(MVT::v2i64, Res));
34584 }
34585 }
34586
34587 // Try to remove a bitcast of constant vXi1 vector. We have to legalize
34588 // most of these to scalar anyway.
34589 if (Subtarget.hasAVX512() && VT.isScalarInteger() &&
34590 SrcVT.isVector() && SrcVT.getVectorElementType() == MVT::i1 &&
34591 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
34592 return combinevXi1ConstantToInteger(N0, DAG);
34593 }
34594
34595 if (Subtarget.hasAVX512() && SrcVT.isScalarInteger() &&
34596 VT.isVector() && VT.getVectorElementType() == MVT::i1 &&
34597 isa<ConstantSDNode>(N0)) {
34598 auto *C = cast<ConstantSDNode>(N0);
34599 if (C->isAllOnesValue())
34600 return DAG.getConstant(1, SDLoc(N0), VT);
34601 if (C->isNullValue())
34602 return DAG.getConstant(0, SDLoc(N0), VT);
34603 }
34604
34605 // Try to remove bitcasts from input and output of mask arithmetic to
34606 // remove GPR<->K-register crossings.
34607 if (SDValue V = combineCastedMaskArithmetic(N, DAG, DCI, Subtarget))
34608 return V;
34609
34610 // Convert a bitcasted integer logic operation that has one bitcasted
34611 // floating-point operand into a floating-point logic operation. This may
34612 // create a load of a constant, but that is cheaper than materializing the
34613 // constant in an integer register and transferring it to an SSE register or
34614 // transferring the SSE operand to integer register and back.
34615 unsigned FPOpcode;
34616 switch (N0.getOpcode()) {
34617 case ISD::AND: FPOpcode = X86ISD::FAND; break;
34618 case ISD::OR: FPOpcode = X86ISD::FOR; break;
34619 case ISD::XOR: FPOpcode = X86ISD::FXOR; break;
34620 default: return SDValue();
34621 }
34622
34623 if (!((Subtarget.hasSSE1() && VT == MVT::f32) ||
34624 (Subtarget.hasSSE2() && VT == MVT::f64)))
34625 return SDValue();
34626
34627 SDValue LogicOp0 = N0.getOperand(0);
34628 SDValue LogicOp1 = N0.getOperand(1);
34629 SDLoc DL0(N0);
34630
34631 // bitcast(logic(bitcast(X), Y)) --> logic'(X, bitcast(Y))
34632 if (N0.hasOneUse() && LogicOp0.getOpcode() == ISD::BITCAST &&
34633 LogicOp0.hasOneUse() && LogicOp0.getOperand(0).getValueType() == VT &&
34634 !isa<ConstantSDNode>(LogicOp0.getOperand(0))) {
34635 SDValue CastedOp1 = DAG.getBitcast(VT, LogicOp1);
34636 return DAG.getNode(FPOpcode, DL0, VT, LogicOp0.getOperand(0), CastedOp1);
34637 }
34638 // bitcast(logic(X, bitcast(Y))) --> logic'(bitcast(X), Y)
34639 if (N0.hasOneUse() && LogicOp1.getOpcode() == ISD::BITCAST &&
34640 LogicOp1.hasOneUse() && LogicOp1.getOperand(0).getValueType() == VT &&
34641 !isa<ConstantSDNode>(LogicOp1.getOperand(0))) {
34642 SDValue CastedOp0 = DAG.getBitcast(VT, LogicOp0);
34643 return DAG.getNode(FPOpcode, DL0, VT, LogicOp1.getOperand(0), CastedOp0);
34644 }
34645
34646 return SDValue();
34647}
34648
34649// Given a ABS node, detect the following pattern:
34650// (ABS (SUB (ZERO_EXTEND a), (ZERO_EXTEND b))).
34651// This is useful as it is the input into a SAD pattern.
34652static bool detectZextAbsDiff(const SDValue &Abs, SDValue &Op0, SDValue &Op1) {
34653 SDValue AbsOp1 = Abs->getOperand(0);
34654 if (AbsOp1.getOpcode() != ISD::SUB)
34655 return false;
34656
34657 Op0 = AbsOp1.getOperand(0);
34658 Op1 = AbsOp1.getOperand(1);
34659
34660 // Check if the operands of the sub are zero-extended from vectors of i8.
34661 if (Op0.getOpcode() != ISD::ZERO_EXTEND ||
34662 Op0.getOperand(0).getValueType().getVectorElementType() != MVT::i8 ||
34663 Op1.getOpcode() != ISD::ZERO_EXTEND ||
34664 Op1.getOperand(0).getValueType().getVectorElementType() != MVT::i8)
34665 return false;
34666
34667 return true;
34668}
34669
34670// Given two zexts of <k x i8> to <k x i32>, create a PSADBW of the inputs
34671// to these zexts.
34672static SDValue createPSADBW(SelectionDAG &DAG, const SDValue &Zext0,
34673 const SDValue &Zext1, const SDLoc &DL,
34674 const X86Subtarget &Subtarget) {
34675 // Find the appropriate width for the PSADBW.
34676 EVT InVT = Zext0.getOperand(0).getValueType();
34677 unsigned RegSize = std::max(128u, InVT.getSizeInBits());
34678
34679 // "Zero-extend" the i8 vectors. This is not a per-element zext, rather we
34680 // fill in the missing vector elements with 0.
34681 unsigned NumConcat = RegSize / InVT.getSizeInBits();
34682 SmallVector<SDValue, 16> Ops(NumConcat, DAG.getConstant(0, DL, InVT));
34683 Ops[0] = Zext0.getOperand(0);
34684 MVT ExtendedVT = MVT::getVectorVT(MVT::i8, RegSize / 8);
34685 SDValue SadOp0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, ExtendedVT, Ops);
34686 Ops[0] = Zext1.getOperand(0);
34687 SDValue SadOp1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, ExtendedVT, Ops);
34688
34689 // Actually build the SAD, split as 128/256/512 bits for SSE/AVX2/AVX512BW.
34690 auto PSADBWBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
34691 ArrayRef<SDValue> Ops) {
34692 MVT VT = MVT::getVectorVT(MVT::i64, Ops[0].getValueSizeInBits() / 64);
34693 return DAG.getNode(X86ISD::PSADBW, DL, VT, Ops);
34694 };
34695 MVT SadVT = MVT::getVectorVT(MVT::i64, RegSize / 64);
34696 return SplitOpsAndApply(DAG, Subtarget, DL, SadVT, { SadOp0, SadOp1 },
34697 PSADBWBuilder);
34698}
34699
34700// Attempt to replace an min/max v8i16/v16i8 horizontal reduction with
34701// PHMINPOSUW.
34702static SDValue combineHorizontalMinMaxResult(SDNode *Extract, SelectionDAG &DAG,
34703 const X86Subtarget &Subtarget) {
34704 // Bail without SSE41.
34705 if (!Subtarget.hasSSE41())
34706 return SDValue();
34707
34708 EVT ExtractVT = Extract->getValueType(0);
34709 if (ExtractVT != MVT::i16 && ExtractVT != MVT::i8)
34710 return SDValue();
34711
34712 // Check for SMAX/SMIN/UMAX/UMIN horizontal reduction patterns.
34713 ISD::NodeType BinOp;
34714 SDValue Src = DAG.matchBinOpReduction(
34715 Extract, BinOp, {ISD::SMAX, ISD::SMIN, ISD::UMAX, ISD::UMIN});
34716 if (!Src)
34717 return SDValue();
34718
34719 EVT SrcVT = Src.getValueType();
34720 EVT SrcSVT = SrcVT.getScalarType();
34721 if (SrcSVT != ExtractVT || (SrcVT.getSizeInBits() % 128) != 0)
34722 return SDValue();
34723
34724 SDLoc DL(Extract);
34725 SDValue MinPos = Src;
34726
34727 // First, reduce the source down to 128-bit, applying BinOp to lo/hi.
34728 while (SrcVT.getSizeInBits() > 128) {
34729 unsigned NumElts = SrcVT.getVectorNumElements();
34730 unsigned NumSubElts = NumElts / 2;
34731 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcSVT, NumSubElts);
34732 unsigned SubSizeInBits = SrcVT.getSizeInBits();
34733 SDValue Lo = extractSubVector(MinPos, 0, DAG, DL, SubSizeInBits);
34734 SDValue Hi = extractSubVector(MinPos, NumSubElts, DAG, DL, SubSizeInBits);
34735 MinPos = DAG.getNode(BinOp, DL, SrcVT, Lo, Hi);
34736 }
34737 assert(((SrcVT == MVT::v8i16 && ExtractVT == MVT::i16) ||((((SrcVT == MVT::v8i16 && ExtractVT == MVT::i16) || (
SrcVT == MVT::v16i8 && ExtractVT == MVT::i8)) &&
"Unexpected value type") ? static_cast<void> (0) : __assert_fail
("((SrcVT == MVT::v8i16 && ExtractVT == MVT::i16) || (SrcVT == MVT::v16i8 && ExtractVT == MVT::i8)) && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 34739, __PRETTY_FUNCTION__))
34738 (SrcVT == MVT::v16i8 && ExtractVT == MVT::i8)) &&((((SrcVT == MVT::v8i16 && ExtractVT == MVT::i16) || (
SrcVT == MVT::v16i8 && ExtractVT == MVT::i8)) &&
"Unexpected value type") ? static_cast<void> (0) : __assert_fail
("((SrcVT == MVT::v8i16 && ExtractVT == MVT::i16) || (SrcVT == MVT::v16i8 && ExtractVT == MVT::i8)) && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 34739, __PRETTY_FUNCTION__))
34739 "Unexpected value type")((((SrcVT == MVT::v8i16 && ExtractVT == MVT::i16) || (
SrcVT == MVT::v16i8 && ExtractVT == MVT::i8)) &&
"Unexpected value type") ? static_cast<void> (0) : __assert_fail
("((SrcVT == MVT::v8i16 && ExtractVT == MVT::i16) || (SrcVT == MVT::v16i8 && ExtractVT == MVT::i8)) && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 34739, __PRETTY_FUNCTION__))
;
34740
34741 // PHMINPOSUW applies to UMIN(v8i16), for SMIN/SMAX/UMAX we must apply a mask
34742 // to flip the value accordingly.
34743 SDValue Mask;
34744 unsigned MaskEltsBits = ExtractVT.getSizeInBits();
34745 if (BinOp == ISD::SMAX)
34746 Mask = DAG.getConstant(APInt::getSignedMaxValue(MaskEltsBits), DL, SrcVT);
34747 else if (BinOp == ISD::SMIN)
34748 Mask = DAG.getConstant(APInt::getSignedMinValue(MaskEltsBits), DL, SrcVT);
34749 else if (BinOp == ISD::UMAX)
34750 Mask = DAG.getConstant(APInt::getAllOnesValue(MaskEltsBits), DL, SrcVT);
34751
34752 if (Mask)
34753 MinPos = DAG.getNode(ISD::XOR, DL, SrcVT, Mask, MinPos);
34754
34755 // For v16i8 cases we need to perform UMIN on pairs of byte elements,
34756 // shuffling each upper element down and insert zeros. This means that the
34757 // v16i8 UMIN will leave the upper element as zero, performing zero-extension
34758 // ready for the PHMINPOS.
34759 if (ExtractVT == MVT::i8) {
34760 SDValue Upper = DAG.getVectorShuffle(
34761 SrcVT, DL, MinPos, DAG.getConstant(0, DL, MVT::v16i8),
34762 {1, 16, 3, 16, 5, 16, 7, 16, 9, 16, 11, 16, 13, 16, 15, 16});
34763 MinPos = DAG.getNode(ISD::UMIN, DL, SrcVT, MinPos, Upper);
34764 }
34765
34766 // Perform the PHMINPOS on a v8i16 vector,
34767 MinPos = DAG.getBitcast(MVT::v8i16, MinPos);
34768 MinPos = DAG.getNode(X86ISD::PHMINPOS, DL, MVT::v8i16, MinPos);
34769 MinPos = DAG.getBitcast(SrcVT, MinPos);
34770
34771 if (Mask)
34772 MinPos = DAG.getNode(ISD::XOR, DL, SrcVT, Mask, MinPos);
34773
34774 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtractVT, MinPos,
34775 DAG.getIntPtrConstant(0, DL));
34776}
34777
34778// Attempt to replace an all_of/any_of/parity style horizontal reduction with a MOVMSK.
34779static SDValue combineHorizontalPredicateResult(SDNode *Extract,
34780 SelectionDAG &DAG,
34781 const X86Subtarget &Subtarget) {
34782 // Bail without SSE2.
34783 if (!Subtarget.hasSSE2())
34784 return SDValue();
34785
34786 EVT ExtractVT = Extract->getValueType(0);
34787 unsigned BitWidth = ExtractVT.getSizeInBits();
34788 if (ExtractVT != MVT::i64 && ExtractVT != MVT::i32 && ExtractVT != MVT::i16 &&
34789 ExtractVT != MVT::i8 && ExtractVT != MVT::i1)
34790 return SDValue();
34791
34792 // Check for OR(any_of)/AND(all_of)/XOR(parity) horizontal reduction patterns.
34793 ISD::NodeType BinOp;
34794 SDValue Match = DAG.matchBinOpReduction(Extract, BinOp, {ISD::OR, ISD::AND});
34795 if (!Match && ExtractVT == MVT::i1)
34796 Match = DAG.matchBinOpReduction(Extract, BinOp, {ISD::XOR});
34797 if (!Match)
34798 return SDValue();
34799
34800 // EXTRACT_VECTOR_ELT can require implicit extension of the vector element
34801 // which we can't support here for now.
34802 if (Match.getScalarValueSizeInBits() != BitWidth)
34803 return SDValue();
34804
34805 SDValue Movmsk;
34806 SDLoc DL(Extract);
34807 EVT MatchVT = Match.getValueType();
34808 unsigned NumElts = MatchVT.getVectorNumElements();
34809
34810 if (ExtractVT == MVT::i1) {
34811 // Special case for (pre-legalization) vXi1 reductions.
34812 if (NumElts > 32)
34813 return SDValue();
34814 if (DAG.getTargetLoweringInfo().isTypeLegal(MatchVT)) {
34815 // If this is a legal AVX512 predicate type then we can just bitcast.
34816 EVT MovmskVT = EVT::getIntegerVT(*DAG.getContext(), NumElts);
34817 Movmsk = DAG.getBitcast(MovmskVT, Match);
34818 } else {
34819 // Use combineBitcastvxi1 to create the MOVMSK.
34820 if (NumElts == 32 && !Subtarget.hasInt256()) {
34821 SDValue Lo, Hi;
34822 std::tie(Lo, Hi) = DAG.SplitVector(Match, DL);
34823 Match = DAG.getNode(BinOp, DL, Lo.getValueType(), Lo, Hi);
34824 NumElts = 16;
34825 }
34826 EVT MovmskVT = EVT::getIntegerVT(*DAG.getContext(), NumElts);
34827 Movmsk = combineBitcastvxi1(DAG, MovmskVT, Match, DL, Subtarget);
34828 }
34829 if (!Movmsk)
34830 return SDValue();
34831 Movmsk = DAG.getZExtOrTrunc(Movmsk, DL, MVT::i32);
34832 } else {
34833 // Bail with AVX512VL (which uses predicate registers).
34834 if (Subtarget.hasVLX())
34835 return SDValue();
34836
34837 unsigned MatchSizeInBits = Match.getValueSizeInBits();
34838 if (!(MatchSizeInBits == 128 ||
34839 (MatchSizeInBits == 256 && Subtarget.hasAVX())))
34840 return SDValue();
34841
34842 // Make sure this isn't a vector of 1 element. The perf win from using
34843 // MOVMSK diminishes with less elements in the reduction, but it is
34844 // generally better to get the comparison over to the GPRs as soon as
34845 // possible to reduce the number of vector ops.
34846 if (Match.getValueType().getVectorNumElements() < 2)
34847 return SDValue();
34848
34849 // Check that we are extracting a reduction of all sign bits.
34850 if (DAG.ComputeNumSignBits(Match) != BitWidth)
34851 return SDValue();
34852
34853 if (MatchSizeInBits == 256 && BitWidth < 32 && !Subtarget.hasInt256()) {
34854 SDValue Lo, Hi;
34855 std::tie(Lo, Hi) = DAG.SplitVector(Match, DL);
34856 Match = DAG.getNode(BinOp, DL, Lo.getValueType(), Lo, Hi);
34857 MatchSizeInBits = Match.getValueSizeInBits();
34858 }
34859
34860 // For 32/64 bit comparisons use MOVMSKPS/MOVMSKPD, else PMOVMSKB.
34861 MVT MaskSrcVT;
34862 if (64 == BitWidth || 32 == BitWidth)
34863 MaskSrcVT = MVT::getVectorVT(MVT::getFloatingPointVT(BitWidth),
34864 MatchSizeInBits / BitWidth);
34865 else
34866 MaskSrcVT = MVT::getVectorVT(MVT::i8, MatchSizeInBits / 8);
34867
34868 SDValue BitcastLogicOp = DAG.getBitcast(MaskSrcVT, Match);
34869 Movmsk = getPMOVMSKB(DL, BitcastLogicOp, DAG, Subtarget);
34870 NumElts = MaskSrcVT.getVectorNumElements();
34871 }
34872 assert(NumElts <= 32 && "Not expecting more than 32 elements")((NumElts <= 32 && "Not expecting more than 32 elements"
) ? static_cast<void> (0) : __assert_fail ("NumElts <= 32 && \"Not expecting more than 32 elements\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 34872, __PRETTY_FUNCTION__))
;
34873
34874 if (BinOp == ISD::XOR) {
34875 // parity -> (AND (CTPOP(MOVMSK X)), 1)
34876 SDValue Mask = DAG.getConstant(1, DL, MVT::i32);
34877 SDValue Result = DAG.getNode(ISD::CTPOP, DL, MVT::i32, Movmsk);
34878 Result = DAG.getNode(ISD::AND, DL, MVT::i32, Result, Mask);
34879 return DAG.getZExtOrTrunc(Result, DL, ExtractVT);
34880 }
34881
34882 SDValue CmpC;
34883 ISD::CondCode CondCode;
34884 if (BinOp == ISD::OR) {
34885 // any_of -> MOVMSK != 0
34886 CmpC = DAG.getConstant(0, DL, MVT::i32);
34887 CondCode = ISD::CondCode::SETNE;
34888 } else {
34889 // all_of -> MOVMSK == ((1 << NumElts) - 1)
34890 CmpC = DAG.getConstant((1ULL << NumElts) - 1, DL, MVT::i32);
34891 CondCode = ISD::CondCode::SETEQ;
34892 }
34893
34894 // The setcc produces an i8 of 0/1, so extend that to the result width and
34895 // negate to get the final 0/-1 mask value.
34896 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
34897 EVT SetccVT =
34898 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i32);
34899 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Movmsk, CmpC, CondCode);
34900 SDValue Zext = DAG.getZExtOrTrunc(Setcc, DL, ExtractVT);
34901 SDValue Zero = DAG.getConstant(0, DL, ExtractVT);
34902 return DAG.getNode(ISD::SUB, DL, ExtractVT, Zero, Zext);
34903}
34904
34905static SDValue combineBasicSADPattern(SDNode *Extract, SelectionDAG &DAG,
34906 const X86Subtarget &Subtarget) {
34907 // PSADBW is only supported on SSE2 and up.
34908 if (!Subtarget.hasSSE2())
34909 return SDValue();
34910
34911 // Verify the type we're extracting from is any integer type above i16.
34912 EVT VT = Extract->getOperand(0).getValueType();
34913 if (!VT.isSimple() || !(VT.getVectorElementType().getSizeInBits() > 16))
34914 return SDValue();
34915
34916 unsigned RegSize = 128;
34917 if (Subtarget.useBWIRegs())
34918 RegSize = 512;
34919 else if (Subtarget.hasAVX())
34920 RegSize = 256;
34921
34922 // We handle upto v16i* for SSE2 / v32i* for AVX / v64i* for AVX512.
34923 // TODO: We should be able to handle larger vectors by splitting them before
34924 // feeding them into several SADs, and then reducing over those.
34925 if (RegSize / VT.getVectorNumElements() < 8)
34926 return SDValue();
34927
34928 // Match shuffle + add pyramid.
34929 ISD::NodeType BinOp;
34930 SDValue Root = DAG.matchBinOpReduction(Extract, BinOp, {ISD::ADD});
34931
34932 // The operand is expected to be zero extended from i8
34933 // (verified in detectZextAbsDiff).
34934 // In order to convert to i64 and above, additional any/zero/sign
34935 // extend is expected.
34936 // The zero extend from 32 bit has no mathematical effect on the result.
34937 // Also the sign extend is basically zero extend
34938 // (extends the sign bit which is zero).
34939 // So it is correct to skip the sign/zero extend instruction.
34940 if (Root && (Root.getOpcode() == ISD::SIGN_EXTEND ||
34941 Root.getOpcode() == ISD::ZERO_EXTEND ||
34942 Root.getOpcode() == ISD::ANY_EXTEND))
34943 Root = Root.getOperand(0);
34944
34945 // If there was a match, we want Root to be a select that is the root of an
34946 // abs-diff pattern.
34947 if (!Root || Root.getOpcode() != ISD::ABS)
34948 return SDValue();
34949
34950 // Check whether we have an abs-diff pattern feeding into the select.
34951 SDValue Zext0, Zext1;
34952 if (!detectZextAbsDiff(Root, Zext0, Zext1))
34953 return SDValue();
34954
34955 // Create the SAD instruction.
34956 SDLoc DL(Extract);
34957 SDValue SAD = createPSADBW(DAG, Zext0, Zext1, DL, Subtarget);
34958
34959 // If the original vector was wider than 8 elements, sum over the results
34960 // in the SAD vector.
34961 unsigned Stages = Log2_32(VT.getVectorNumElements());
34962 MVT SadVT = SAD.getSimpleValueType();
34963 if (Stages > 3) {
34964 unsigned SadElems = SadVT.getVectorNumElements();
34965
34966 for(unsigned i = Stages - 3; i > 0; --i) {
34967 SmallVector<int, 16> Mask(SadElems, -1);
34968 for(unsigned j = 0, MaskEnd = 1 << (i - 1); j < MaskEnd; ++j)
34969 Mask[j] = MaskEnd + j;
34970
34971 SDValue Shuffle =
34972 DAG.getVectorShuffle(SadVT, DL, SAD, DAG.getUNDEF(SadVT), Mask);
34973 SAD = DAG.getNode(ISD::ADD, DL, SadVT, SAD, Shuffle);
34974 }
34975 }
34976
34977 MVT Type = Extract->getSimpleValueType(0);
34978 unsigned TypeSizeInBits = Type.getSizeInBits();
34979 // Return the lowest TypeSizeInBits bits.
34980 MVT ResVT = MVT::getVectorVT(Type, SadVT.getSizeInBits() / TypeSizeInBits);
34981 SAD = DAG.getBitcast(ResVT, SAD);
34982 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, Type, SAD,
34983 Extract->getOperand(1));
34984}
34985
34986// Attempt to peek through a target shuffle and extract the scalar from the
34987// source.
34988static SDValue combineExtractWithShuffle(SDNode *N, SelectionDAG &DAG,
34989 TargetLowering::DAGCombinerInfo &DCI,
34990 const X86Subtarget &Subtarget) {
34991 if (DCI.isBeforeLegalizeOps())
34992 return SDValue();
34993
34994 SDValue Src = N->getOperand(0);
34995 SDValue Idx = N->getOperand(1);
34996
34997 EVT VT = N->getValueType(0);
34998 EVT SrcVT = Src.getValueType();
34999 EVT SrcSVT = SrcVT.getVectorElementType();
35000 unsigned NumSrcElts = SrcVT.getVectorNumElements();
35001
35002 // Don't attempt this for boolean mask vectors or unknown extraction indices.
35003 if (SrcSVT == MVT::i1 || !isa<ConstantSDNode>(Idx))
35004 return SDValue();
35005
35006 SDValue SrcBC = peekThroughBitcasts(Src);
35007
35008 // Handle extract(broadcast(scalar_value)), it doesn't matter what index is.
35009 if (X86ISD::VBROADCAST == SrcBC.getOpcode()) {
35010 SDValue SrcOp = SrcBC.getOperand(0);
35011 if (SrcOp.getValueSizeInBits() == VT.getSizeInBits())
35012 return DAG.getBitcast(VT, SrcOp);
35013 }
35014
35015 // Resolve the target shuffle inputs and mask.
35016 SmallVector<int, 16> Mask;
35017 SmallVector<SDValue, 2> Ops;
35018 if (!resolveTargetShuffleInputs(SrcBC, Ops, Mask, DAG))
35019 return SDValue();
35020
35021 // Attempt to narrow/widen the shuffle mask to the correct size.
35022 if (Mask.size() != NumSrcElts) {
35023 if ((NumSrcElts % Mask.size()) == 0) {
35024 SmallVector<int, 16> ScaledMask;
35025 int Scale = NumSrcElts / Mask.size();
35026 scaleShuffleMask<int>(Scale, Mask, ScaledMask);
35027 Mask = std::move(ScaledMask);
35028 } else if ((Mask.size() % NumSrcElts) == 0) {
35029 // Simplify Mask based on demanded element.
35030 int ExtractIdx = (int)N->getConstantOperandVal(1);
35031 int Scale = Mask.size() / NumSrcElts;
35032 int Lo = Scale * ExtractIdx;
35033 int Hi = Scale * (ExtractIdx + 1);
35034 for (int i = 0, e = (int)Mask.size(); i != e; ++i)
35035 if (i < Lo || Hi <= i)
35036 Mask[i] = SM_SentinelUndef;
35037
35038 SmallVector<int, 16> WidenedMask;
35039 while (Mask.size() > NumSrcElts &&
35040 canWidenShuffleElements(Mask, WidenedMask))
35041 Mask = std::move(WidenedMask);
35042 // TODO - investigate support for wider shuffle masks with known upper
35043 // undef/zero elements for implicit zero-extension.
35044 }
35045 }
35046
35047 // Check if narrowing/widening failed.
35048 if (Mask.size() != NumSrcElts)
35049 return SDValue();
35050
35051 int SrcIdx = Mask[N->getConstantOperandVal(1)];
35052 SDLoc dl(N);
35053
35054 // If the shuffle source element is undef/zero then we can just accept it.
35055 if (SrcIdx == SM_SentinelUndef)
35056 return DAG.getUNDEF(VT);
35057
35058 if (SrcIdx == SM_SentinelZero)
35059 return VT.isFloatingPoint() ? DAG.getConstantFP(0.0, dl, VT)
35060 : DAG.getConstant(0, dl, VT);
35061
35062 SDValue SrcOp = Ops[SrcIdx / Mask.size()];
35063 SrcIdx = SrcIdx % Mask.size();
35064
35065 // We can only extract other elements from 128-bit vectors and in certain
35066 // circumstances, depending on SSE-level.
35067 // TODO: Investigate using extract_subvector for larger vectors.
35068 // TODO: Investigate float/double extraction if it will be just stored.
35069 if ((SrcVT == MVT::v4i32 || SrcVT == MVT::v2i64) &&
35070 ((SrcIdx == 0 && Subtarget.hasSSE2()) || Subtarget.hasSSE41())) {
35071 assert(SrcSVT == VT && "Unexpected extraction type")((SrcSVT == VT && "Unexpected extraction type") ? static_cast
<void> (0) : __assert_fail ("SrcSVT == VT && \"Unexpected extraction type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 35071, __PRETTY_FUNCTION__))
;
35072 SrcOp = DAG.getBitcast(SrcVT, SrcOp);
35073 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcSVT, SrcOp,
35074 DAG.getIntPtrConstant(SrcIdx, dl));
35075 }
35076
35077 if ((SrcVT == MVT::v8i16 && Subtarget.hasSSE2()) ||
35078 (SrcVT == MVT::v16i8 && Subtarget.hasSSE41())) {
35079 assert(VT.getSizeInBits() >= SrcSVT.getSizeInBits() &&((VT.getSizeInBits() >= SrcSVT.getSizeInBits() && "Unexpected extraction type"
) ? static_cast<void> (0) : __assert_fail ("VT.getSizeInBits() >= SrcSVT.getSizeInBits() && \"Unexpected extraction type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 35080, __PRETTY_FUNCTION__))
35080 "Unexpected extraction type")((VT.getSizeInBits() >= SrcSVT.getSizeInBits() && "Unexpected extraction type"
) ? static_cast<void> (0) : __assert_fail ("VT.getSizeInBits() >= SrcSVT.getSizeInBits() && \"Unexpected extraction type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 35080, __PRETTY_FUNCTION__))
;
35081 unsigned OpCode = (SrcVT == MVT::v8i16 ? X86ISD::PEXTRW : X86ISD::PEXTRB);
35082 SrcOp = DAG.getBitcast(SrcVT, SrcOp);
35083 SDValue ExtOp = DAG.getNode(OpCode, dl, MVT::i32, SrcOp,
35084 DAG.getIntPtrConstant(SrcIdx, dl));
35085 return DAG.getZExtOrTrunc(ExtOp, dl, VT);
35086 }
35087
35088 return SDValue();
35089}
35090
35091/// Extracting a scalar FP value from vector element 0 is free, so extract each
35092/// operand first, then perform the math as a scalar op.
35093static SDValue scalarizeExtEltFP(SDNode *ExtElt, SelectionDAG &DAG) {
35094 assert(ExtElt->getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Expected extract")((ExtElt->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
"Expected extract") ? static_cast<void> (0) : __assert_fail
("ExtElt->getOpcode() == ISD::EXTRACT_VECTOR_ELT && \"Expected extract\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 35094, __PRETTY_FUNCTION__))
;
35095 SDValue Vec = ExtElt->getOperand(0);
35096 SDValue Index = ExtElt->getOperand(1);
35097 EVT VT = ExtElt->getValueType(0);
35098 EVT VecVT = Vec.getValueType();
35099
35100 // TODO: If this is a unary/expensive/expand op, allow extraction from a
35101 // non-zero element because the shuffle+scalar op will be cheaper?
35102 if (!Vec.hasOneUse() || !isNullConstant(Index) || VecVT.getScalarType() != VT)
35103 return SDValue();
35104
35105 // Vector FP compares don't fit the pattern of FP math ops (propagate, not
35106 // extract, the condition code), so deal with those as a special-case.
35107 if (Vec.getOpcode() == ISD::SETCC && VT == MVT::i1) {
35108 EVT OpVT = Vec.getOperand(0).getValueType().getScalarType();
35109 if (OpVT != MVT::f32 && OpVT != MVT::f64)
35110 return SDValue();
35111
35112 // extract (setcc X, Y, CC), 0 --> setcc (extract X, 0), (extract Y, 0), CC
35113 SDLoc DL(ExtElt);
35114 SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, OpVT,
35115 Vec.getOperand(0), Index);
35116 SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, OpVT,
35117 Vec.getOperand(1), Index);
35118 return DAG.getNode(Vec.getOpcode(), DL, VT, Ext0, Ext1, Vec.getOperand(2));
35119 }
35120
35121 if (VT != MVT::f32 && VT != MVT::f64)
35122 return SDValue();
35123
35124 // Vector FP selects don't fit the pattern of FP math ops (because the
35125 // condition has a different type and we have to change the opcode), so deal
35126 // with those here.
35127 // FIXME: This is restricted to pre type legalization by ensuring the setcc
35128 // has i1 elements. If we loosen this we need to convert vector bool to a
35129 // scalar bool.
35130 if (Vec.getOpcode() == ISD::VSELECT &&
35131 Vec.getOperand(0).getOpcode() == ISD::SETCC &&
35132 Vec.getOperand(0).getValueType().getScalarType() == MVT::i1 &&
35133 Vec.getOperand(0).getOperand(0).getValueType() == VecVT) {
35134 // ext (sel Cond, X, Y), 0 --> sel (ext Cond, 0), (ext X, 0), (ext Y, 0)
35135 SDLoc DL(ExtElt);
35136 SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
35137 Vec.getOperand(0).getValueType().getScalarType(),
35138 Vec.getOperand(0), Index);
35139 SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
35140 Vec.getOperand(1), Index);
35141 SDValue Ext2 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
35142 Vec.getOperand(2), Index);
35143 return DAG.getNode(ISD::SELECT, DL, VT, Ext0, Ext1, Ext2);
35144 }
35145
35146 // TODO: This switch could include FNEG and the x86-specific FP logic ops
35147 // (FAND, FANDN, FOR, FXOR). But that may require enhancements to avoid
35148 // missed load folding and fma+fneg combining.
35149 switch (Vec.getOpcode()) {
35150 case ISD::FMA: // Begin 3 operands
35151 case ISD::FMAD:
35152 case ISD::FADD: // Begin 2 operands
35153 case ISD::FSUB:
35154 case ISD::FMUL:
35155 case ISD::FDIV:
35156 case ISD::FREM:
35157 case ISD::FCOPYSIGN:
35158 case ISD::FMINNUM:
35159 case ISD::FMAXNUM:
35160 case ISD::FMINNUM_IEEE:
35161 case ISD::FMAXNUM_IEEE:
35162 case ISD::FMAXIMUM:
35163 case ISD::FMINIMUM:
35164 case X86ISD::FMAX:
35165 case X86ISD::FMIN:
35166 case ISD::FABS: // Begin 1 operand
35167 case ISD::FSQRT:
35168 case ISD::FRINT:
35169 case ISD::FCEIL:
35170 case ISD::FTRUNC:
35171 case ISD::FNEARBYINT:
35172 case ISD::FROUND:
35173 case ISD::FFLOOR:
35174 case X86ISD::FRCP:
35175 case X86ISD::FRSQRT: {
35176 // extract (fp X, Y, ...), 0 --> fp (extract X, 0), (extract Y, 0), ...
35177 SDLoc DL(ExtElt);
35178 SmallVector<SDValue, 4> ExtOps;
35179 for (SDValue Op : Vec->ops())
35180 ExtOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Op, Index));
35181 return DAG.getNode(Vec.getOpcode(), DL, VT, ExtOps);
35182 }
35183 default:
35184 return SDValue();
35185 }
35186 llvm_unreachable("All opcodes should return within switch")::llvm::llvm_unreachable_internal("All opcodes should return within switch"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 35186)
;
35187}
35188
35189/// Detect vector gather/scatter index generation and convert it from being a
35190/// bunch of shuffles and extracts into a somewhat faster sequence.
35191/// For i686, the best sequence is apparently storing the value and loading
35192/// scalars back, while for x64 we should use 64-bit extracts and shifts.
35193static SDValue combineExtractVectorElt(SDNode *N, SelectionDAG &DAG,
35194 TargetLowering::DAGCombinerInfo &DCI,
35195 const X86Subtarget &Subtarget) {
35196 if (SDValue NewOp = combineExtractWithShuffle(N, DAG, DCI, Subtarget))
35197 return NewOp;
35198
35199 SDValue InputVector = N->getOperand(0);
35200 SDValue EltIdx = N->getOperand(1);
35201 auto *CIdx = dyn_cast<ConstantSDNode>(EltIdx);
35202
35203 EVT SrcVT = InputVector.getValueType();
35204 EVT VT = N->getValueType(0);
35205 SDLoc dl(InputVector);
35206 bool IsPextr = N->getOpcode() != ISD::EXTRACT_VECTOR_ELT;
35207
35208 if (CIdx && CIdx->getAPIntValue().uge(SrcVT.getVectorNumElements()))
35209 return IsPextr ? DAG.getConstant(0, dl, VT) : DAG.getUNDEF(VT);
35210
35211 // Integer Constant Folding.
35212 if (CIdx && VT.isInteger()) {
35213 APInt UndefVecElts;
35214 SmallVector<APInt, 16> EltBits;
35215 unsigned VecEltBitWidth = SrcVT.getScalarSizeInBits();
35216 if (getTargetConstantBitsFromNode(InputVector, VecEltBitWidth, UndefVecElts,
35217 EltBits, true, false)) {
35218 uint64_t Idx = CIdx->getZExtValue();
35219 if (UndefVecElts[Idx])
35220 return IsPextr ? DAG.getConstant(0, dl, VT) : DAG.getUNDEF(VT);
35221 return DAG.getConstant(EltBits[Idx].zextOrSelf(VT.getScalarSizeInBits()),
35222 dl, VT);
35223 }
35224 }
35225
35226 // TODO - Remove this once we can handle the implicit zero-extension of
35227 // X86ISD::PEXTRW/X86ISD::PEXTRB in:
35228 // XFormVExtractWithShuffleIntoLoad, combineHorizontalPredicateResult and
35229 // combineBasicSADPattern.
35230 if (IsPextr) {
35231 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
35232 if (TLI.SimplifyDemandedBits(
35233 SDValue(N, 0), APInt::getAllOnesValue(VT.getSizeInBits()), DCI))
35234 return SDValue(N, 0);
35235 return SDValue();
35236 }
35237
35238 if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
35239 return NewOp;
35240
35241 // Detect mmx extraction of all bits as a i64. It works better as a bitcast.
35242 if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
35243 VT == MVT::i64 && SrcVT == MVT::v1i64 && isNullConstant(EltIdx)) {
35244 SDValue MMXSrc = InputVector.getOperand(0);
35245
35246 // The bitcast source is a direct mmx result.
35247 if (MMXSrc.getValueType() == MVT::x86mmx)
35248 return DAG.getBitcast(VT, InputVector);
35249 }
35250
35251 // Detect mmx to i32 conversion through a v2i32 elt extract.
35252 if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
35253 VT == MVT::i32 && SrcVT == MVT::v2i32 && isNullConstant(EltIdx)) {
35254 SDValue MMXSrc = InputVector.getOperand(0);
35255
35256 // The bitcast source is a direct mmx result.
35257 if (MMXSrc.getValueType() == MVT::x86mmx)
35258 return DAG.getNode(X86ISD::MMX_MOVD2W, dl, MVT::i32, MMXSrc);
35259 }
35260
35261 // Check whether this extract is the root of a sum of absolute differences
35262 // pattern. This has to be done here because we really want it to happen
35263 // pre-legalization,
35264 if (SDValue SAD = combineBasicSADPattern(N, DAG, Subtarget))
35265 return SAD;
35266
35267 // Attempt to replace an all_of/any_of horizontal reduction with a MOVMSK.
35268 if (SDValue Cmp = combineHorizontalPredicateResult(N, DAG, Subtarget))
35269 return Cmp;
35270
35271 // Attempt to replace min/max v8i16/v16i8 reductions with PHMINPOSUW.
35272 if (SDValue MinMax = combineHorizontalMinMaxResult(N, DAG, Subtarget))
35273 return MinMax;
35274
35275 if (SDValue V = scalarizeExtEltFP(N, DAG))
35276 return V;
35277
35278 // Attempt to extract a i1 element by using MOVMSK to extract the signbits
35279 // and then testing the relevant element.
35280 if (CIdx && SrcVT.getScalarType() == MVT::i1) {
35281 SmallVector<SDNode *, 16> BoolExtracts;
35282 auto IsBoolExtract = [&BoolExtracts](SDNode *Use) {
35283 if (Use->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
35284 isa<ConstantSDNode>(Use->getOperand(1)) &&
35285 Use->getValueType(0) == MVT::i1) {
35286 BoolExtracts.push_back(Use);
35287 return true;
35288 }
35289 return false;
35290 };
35291 if (all_of(InputVector->uses(), IsBoolExtract) &&
35292 BoolExtracts.size() > 1) {
35293 unsigned NumSrcElts = SrcVT.getVectorNumElements();
35294 EVT BCVT = EVT::getIntegerVT(*DAG.getContext(), NumSrcElts);
35295 if (SDValue BC =
35296 combineBitcastvxi1(DAG, BCVT, InputVector, dl, Subtarget)) {
35297 for (SDNode *Use : BoolExtracts) {
35298 // extractelement vXi1 X, MaskIdx --> ((movmsk X) & Mask) == Mask
35299 unsigned MaskIdx = Use->getConstantOperandVal(1);
35300 APInt MaskBit = APInt::getOneBitSet(NumSrcElts, MaskIdx);
35301 SDValue Mask = DAG.getConstant(MaskBit, dl, BCVT);
35302 SDValue Res = DAG.getNode(ISD::AND, dl, BCVT, BC, Mask);
35303 Res = DAG.getSetCC(dl, MVT::i1, Res, Mask, ISD::SETEQ);
35304 DCI.CombineTo(Use, Res);
35305 }
35306 return SDValue(N, 0);
35307 }
35308 }
35309 }
35310
35311 return SDValue();
35312}
35313
35314/// If a vector select has an operand that is -1 or 0, try to simplify the
35315/// select to a bitwise logic operation.
35316/// TODO: Move to DAGCombiner, possibly using TargetLowering::hasAndNot()?
35317static SDValue
35318combineVSelectWithAllOnesOrZeros(SDNode *N, SelectionDAG &DAG,
35319 TargetLowering::DAGCombinerInfo &DCI,
35320 const X86Subtarget &Subtarget) {
35321 SDValue Cond = N->getOperand(0);
35322 SDValue LHS = N->getOperand(1);
35323 SDValue RHS = N->getOperand(2);
35324 EVT VT = LHS.getValueType();
35325 EVT CondVT = Cond.getValueType();
35326 SDLoc DL(N);
35327 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
35328
35329 if (N->getOpcode() != ISD::VSELECT)
35330 return SDValue();
35331
35332 assert(CondVT.isVector() && "Vector select expects a vector selector!")((CondVT.isVector() && "Vector select expects a vector selector!"
) ? static_cast<void> (0) : __assert_fail ("CondVT.isVector() && \"Vector select expects a vector selector!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 35332, __PRETTY_FUNCTION__))
;
35333
35334 // Check if the first operand is all zeros and Cond type is vXi1.
35335 // This situation only applies to avx512.
35336 // TODO: Use isNullOrNullSplat() to distinguish constants with undefs?
35337 // TODO: Can we assert that both operands are not zeros (because that should
35338 // get simplified at node creation time)?
35339 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
35340 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
35341 if (TValIsAllZeros && !FValIsAllZeros && Subtarget.hasAVX512() &&
35342 Cond.hasOneUse() && CondVT.getVectorElementType() == MVT::i1) {
35343 // Invert the cond to not(cond) : xor(op,allones)=not(op)
35344 SDValue CondNew = DAG.getNOT(DL, Cond, CondVT);
35345 // Vselect cond, op1, op2 = Vselect not(cond), op2, op1
35346 return DAG.getSelect(DL, VT, CondNew, RHS, LHS);
35347 }
35348
35349 // To use the condition operand as a bitwise mask, it must have elements that
35350 // are the same size as the select elements. Ie, the condition operand must
35351 // have already been promoted from the IR select condition type <N x i1>.
35352 // Don't check if the types themselves are equal because that excludes
35353 // vector floating-point selects.
35354 if (CondVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
35355 return SDValue();
35356
35357 // Try to invert the condition if true value is not all 1s and false value is
35358 // not all 0s. Only do this if the condition has one use.
35359 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
35360 if (!TValIsAllOnes && !FValIsAllZeros && Cond.hasOneUse() &&
35361 // Check if the selector will be produced by CMPP*/PCMP*.
35362 Cond.getOpcode() == ISD::SETCC &&
35363 // Check if SETCC has already been promoted.
35364 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
35365 CondVT) {
35366 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
35367
35368 if (TValIsAllZeros || FValIsAllOnes) {
35369 SDValue CC = Cond.getOperand(2);
35370 ISD::CondCode NewCC =
35371 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
35372 Cond.getOperand(0).getValueType().isInteger());
35373 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1),
35374 NewCC);
35375 std::swap(LHS, RHS);
35376 TValIsAllOnes = FValIsAllOnes;
35377 FValIsAllZeros = TValIsAllZeros;
35378 }
35379 }
35380
35381 // Cond value must be 'sign splat' to be converted to a logical op.
35382 if (DAG.ComputeNumSignBits(Cond) != CondVT.getScalarSizeInBits())
35383 return SDValue();
35384
35385 // vselect Cond, 111..., 000... -> Cond
35386 if (TValIsAllOnes && FValIsAllZeros)
35387 return DAG.getBitcast(VT, Cond);
35388
35389 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(CondVT))
35390 return SDValue();
35391
35392 // vselect Cond, 111..., X -> or Cond, X
35393 if (TValIsAllOnes) {
35394 SDValue CastRHS = DAG.getBitcast(CondVT, RHS);
35395 SDValue Or = DAG.getNode(ISD::OR, DL, CondVT, Cond, CastRHS);
35396 return DAG.getBitcast(VT, Or);
35397 }
35398
35399 // vselect Cond, X, 000... -> and Cond, X
35400 if (FValIsAllZeros) {
35401 SDValue CastLHS = DAG.getBitcast(CondVT, LHS);
35402 SDValue And = DAG.getNode(ISD::AND, DL, CondVT, Cond, CastLHS);
35403 return DAG.getBitcast(VT, And);
35404 }
35405
35406 // vselect Cond, 000..., X -> andn Cond, X
35407 if (TValIsAllZeros) {
35408 MVT AndNVT = MVT::getVectorVT(MVT::i64, CondVT.getSizeInBits() / 64);
35409 SDValue CastCond = DAG.getBitcast(AndNVT, Cond);
35410 SDValue CastRHS = DAG.getBitcast(AndNVT, RHS);
35411 SDValue AndN = DAG.getNode(X86ISD::ANDNP, DL, AndNVT, CastCond, CastRHS);
35412 return DAG.getBitcast(VT, AndN);
35413 }
35414
35415 return SDValue();
35416}
35417
35418static SDValue combineSelectOfTwoConstants(SDNode *N, SelectionDAG &DAG) {
35419 SDValue Cond = N->getOperand(0);
35420 SDValue LHS = N->getOperand(1);
35421 SDValue RHS = N->getOperand(2);
35422 SDLoc DL(N);
35423
35424 auto *TrueC = dyn_cast<ConstantSDNode>(LHS);
35425 auto *FalseC = dyn_cast<ConstantSDNode>(RHS);
35426 if (!TrueC || !FalseC)
35427 return SDValue();
35428
35429 // Don't do this for crazy integer types.
35430 EVT VT = N->getValueType(0);
35431 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
35432 return SDValue();
35433
35434 // We're going to use the condition bit in math or logic ops. We could allow
35435 // this with a wider condition value (post-legalization it becomes an i8),
35436 // but if nothing is creating selects that late, it doesn't matter.
35437 if (Cond.getValueType() != MVT::i1)
35438 return SDValue();
35439
35440 // A power-of-2 multiply is just a shift. LEA also cheaply handles multiply by
35441 // 3, 5, or 9 with i32/i64, so those get transformed too.
35442 // TODO: For constants that overflow or do not differ by power-of-2 or small
35443 // multiplier, convert to 'and' + 'add'.
35444 const APInt &TrueVal = TrueC->getAPIntValue();
35445 const APInt &FalseVal = FalseC->getAPIntValue();
35446 bool OV;
35447 APInt Diff = TrueVal.ssub_ov(FalseVal, OV);
35448 if (OV)
35449 return SDValue();
35450
35451 APInt AbsDiff = Diff.abs();
35452 if (AbsDiff.isPowerOf2() ||
35453 ((VT == MVT::i32 || VT == MVT::i64) &&
35454 (AbsDiff == 3 || AbsDiff == 5 || AbsDiff == 9))) {
35455
35456 // We need a positive multiplier constant for shift/LEA codegen. The 'not'
35457 // of the condition can usually be folded into a compare predicate, but even
35458 // without that, the sequence should be cheaper than a CMOV alternative.
35459 if (TrueVal.slt(FalseVal)) {
35460 Cond = DAG.getNOT(DL, Cond, MVT::i1);
35461 std::swap(TrueC, FalseC);
35462 }
35463
35464 // select Cond, TC, FC --> (zext(Cond) * (TC - FC)) + FC
35465 SDValue R = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
35466
35467 // Multiply condition by the difference if non-one.
35468 if (!AbsDiff.isOneValue())
35469 R = DAG.getNode(ISD::MUL, DL, VT, R, DAG.getConstant(AbsDiff, DL, VT));
35470
35471 // Add the base if non-zero.
35472 if (!FalseC->isNullValue())
35473 R = DAG.getNode(ISD::ADD, DL, VT, R, SDValue(FalseC, 0));
35474
35475 return R;
35476 }
35477
35478 return SDValue();
35479}
35480
35481/// If this is a *dynamic* select (non-constant condition) and we can match
35482/// this node with one of the variable blend instructions, restructure the
35483/// condition so that blends can use the high (sign) bit of each element.
35484/// This function will also call SimplifyDemandedBits on already created
35485/// BLENDV to perform additional simplifications.
35486static SDValue combineVSelectToBLENDV(SDNode *N, SelectionDAG &DAG,
35487 TargetLowering::DAGCombinerInfo &DCI,
35488 const X86Subtarget &Subtarget) {
35489 SDValue Cond = N->getOperand(0);
35490 if ((N->getOpcode() != ISD::VSELECT &&
35491 N->getOpcode() != X86ISD::BLENDV) ||
35492 ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
35493 return SDValue();
35494
35495 // Don't optimize before the condition has been transformed to a legal type
35496 // and don't ever optimize vector selects that map to AVX512 mask-registers.
35497 unsigned BitWidth = Cond.getScalarValueSizeInBits();
35498 if (BitWidth < 8 || BitWidth > 64)
35499 return SDValue();
35500
35501 // We can only handle the cases where VSELECT is directly legal on the
35502 // subtarget. We custom lower VSELECT nodes with constant conditions and
35503 // this makes it hard to see whether a dynamic VSELECT will correctly
35504 // lower, so we both check the operation's status and explicitly handle the
35505 // cases where a *dynamic* blend will fail even though a constant-condition
35506 // blend could be custom lowered.
35507 // FIXME: We should find a better way to handle this class of problems.
35508 // Potentially, we should combine constant-condition vselect nodes
35509 // pre-legalization into shuffles and not mark as many types as custom
35510 // lowered.
35511 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
35512 EVT VT = N->getValueType(0);
35513 if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
35514 return SDValue();
35515 // FIXME: We don't support i16-element blends currently. We could and
35516 // should support them by making *all* the bits in the condition be set
35517 // rather than just the high bit and using an i8-element blend.
35518 if (VT.getVectorElementType() == MVT::i16)
35519 return SDValue();
35520 // Dynamic blending was only available from SSE4.1 onward.
35521 if (VT.is128BitVector() && !Subtarget.hasSSE41())
35522 return SDValue();
35523 // Byte blends are only available in AVX2
35524 if (VT == MVT::v32i8 && !Subtarget.hasAVX2())
35525 return SDValue();
35526 // There are no 512-bit blend instructions that use sign bits.
35527 if (VT.is512BitVector())
35528 return SDValue();
35529
35530 // TODO: Add other opcodes eventually lowered into BLEND.
35531 for (SDNode::use_iterator UI = Cond->use_begin(), UE = Cond->use_end();
35532 UI != UE; ++UI)
35533 if ((UI->getOpcode() != ISD::VSELECT &&
35534 UI->getOpcode() != X86ISD::BLENDV) ||
35535 UI.getOperandNo() != 0)
35536 return SDValue();
35537
35538 APInt DemandedMask(APInt::getSignMask(BitWidth));
35539 KnownBits Known;
35540 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
35541 !DCI.isBeforeLegalizeOps());
35542 if (!TLI.SimplifyDemandedBits(Cond, DemandedMask, Known, TLO, 0, true))
35543 return SDValue();
35544
35545 // If we changed the computation somewhere in the DAG, this change will
35546 // affect all users of Cond. Update all the nodes so that we do not use
35547 // the generic VSELECT anymore. Otherwise, we may perform wrong
35548 // optimizations as we messed with the actual expectation for the vector
35549 // boolean values.
35550 for (SDNode *U : Cond->uses()) {
35551 if (U->getOpcode() == X86ISD::BLENDV)
35552 continue;
35553
35554 SDValue SB = DAG.getNode(X86ISD::BLENDV, SDLoc(U), U->getValueType(0),
35555 Cond, U->getOperand(1), U->getOperand(2));
35556 DAG.ReplaceAllUsesOfValueWith(SDValue(U, 0), SB);
35557 DCI.AddToWorklist(U);
35558 }
35559 DCI.CommitTargetLoweringOpt(TLO);
35560 return SDValue(N, 0);
35561}
35562
35563/// Do target-specific dag combines on SELECT and VSELECT nodes.
35564static SDValue combineSelect(SDNode *N, SelectionDAG &DAG,
35565 TargetLowering::DAGCombinerInfo &DCI,
35566 const X86Subtarget &Subtarget) {
35567 SDLoc DL(N);
35568 SDValue Cond = N->getOperand(0);
35569 SDValue LHS = N->getOperand(1);
35570 SDValue RHS = N->getOperand(2);
35571
35572 // Try simplification again because we use this function to optimize
35573 // BLENDV nodes that are not handled by the generic combiner.
35574 if (SDValue V = DAG.simplifySelect(Cond, LHS, RHS))
35575 return V;
35576
35577 EVT VT = LHS.getValueType();
35578 EVT CondVT = Cond.getValueType();
35579 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
35580
35581 // Convert vselects with constant condition into shuffles.
35582 if (ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()) &&
35583 DCI.isBeforeLegalizeOps()) {
35584 SmallVector<int, 64> Mask;
35585 if (createShuffleMaskFromVSELECT(Mask, Cond))
35586 return DAG.getVectorShuffle(VT, DL, LHS, RHS, Mask);
35587 }
35588
35589 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
35590 // instructions match the semantics of the common C idiom x<y?x:y but not
35591 // x<=y?x:y, because of how they handle negative zero (which can be
35592 // ignored in unsafe-math mode).
35593 // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
35594 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
35595 VT != MVT::f80 && VT != MVT::f128 &&
35596 (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
35597 (Subtarget.hasSSE2() ||
35598 (Subtarget.hasSSE1() && VT.getScalarType() == MVT::f32))) {
35599 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
35600
35601 unsigned Opcode = 0;
35602 // Check for x CC y ? x : y.
35603 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
35604 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
35605 switch (CC) {
35606 default: break;
35607 case ISD::SETULT:
35608 // Converting this to a min would handle NaNs incorrectly, and swapping
35609 // the operands would cause it to handle comparisons between positive
35610 // and negative zero incorrectly.
35611 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
35612 if (!DAG.getTarget().Options.UnsafeFPMath &&
35613 !(DAG.isKnownNeverZeroFloat(LHS) ||
35614 DAG.isKnownNeverZeroFloat(RHS)))
35615 break;
35616 std::swap(LHS, RHS);
35617 }
35618 Opcode = X86ISD::FMIN;
35619 break;
35620 case ISD::SETOLE:
35621 // Converting this to a min would handle comparisons between positive
35622 // and negative zero incorrectly.
35623 if (!DAG.getTarget().Options.UnsafeFPMath &&
35624 !DAG.isKnownNeverZeroFloat(LHS) && !DAG.isKnownNeverZeroFloat(RHS))
35625 break;
35626 Opcode = X86ISD::FMIN;
35627 break;
35628 case ISD::SETULE:
35629 // Converting this to a min would handle both negative zeros and NaNs
35630 // incorrectly, but we can swap the operands to fix both.
35631 std::swap(LHS, RHS);
35632 LLVM_FALLTHROUGH[[clang::fallthrough]];
35633 case ISD::SETOLT:
35634 case ISD::SETLT:
35635 case ISD::SETLE:
35636 Opcode = X86ISD::FMIN;
35637 break;
35638
35639 case ISD::SETOGE:
35640 // Converting this to a max would handle comparisons between positive
35641 // and negative zero incorrectly.
35642 if (!DAG.getTarget().Options.UnsafeFPMath &&
35643 !DAG.isKnownNeverZeroFloat(LHS) && !DAG.isKnownNeverZeroFloat(RHS))
35644 break;
35645 Opcode = X86ISD::FMAX;
35646 break;
35647 case ISD::SETUGT:
35648 // Converting this to a max would handle NaNs incorrectly, and swapping
35649 // the operands would cause it to handle comparisons between positive
35650 // and negative zero incorrectly.
35651 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
35652 if (!DAG.getTarget().Options.UnsafeFPMath &&
35653 !(DAG.isKnownNeverZeroFloat(LHS) ||
35654 DAG.isKnownNeverZeroFloat(RHS)))
35655 break;
35656 std::swap(LHS, RHS);
35657 }
35658 Opcode = X86ISD::FMAX;
35659 break;
35660 case ISD::SETUGE:
35661 // Converting this to a max would handle both negative zeros and NaNs
35662 // incorrectly, but we can swap the operands to fix both.
35663 std::swap(LHS, RHS);
35664 LLVM_FALLTHROUGH[[clang::fallthrough]];
35665 case ISD::SETOGT:
35666 case ISD::SETGT:
35667 case ISD::SETGE:
35668 Opcode = X86ISD::FMAX;
35669 break;
35670 }
35671 // Check for x CC y ? y : x -- a min/max with reversed arms.
35672 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
35673 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
35674 switch (CC) {
35675 default: break;
35676 case ISD::SETOGE:
35677 // Converting this to a min would handle comparisons between positive
35678 // and negative zero incorrectly, and swapping the operands would
35679 // cause it to handle NaNs incorrectly.
35680 if (!DAG.getTarget().Options.UnsafeFPMath &&
35681 !(DAG.isKnownNeverZeroFloat(LHS) ||
35682 DAG.isKnownNeverZeroFloat(RHS))) {
35683 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
35684 break;
35685 std::swap(LHS, RHS);
35686 }
35687 Opcode = X86ISD::FMIN;
35688 break;
35689 case ISD::SETUGT:
35690 // Converting this to a min would handle NaNs incorrectly.
35691 if (!DAG.getTarget().Options.UnsafeFPMath &&
35692 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
35693 break;
35694 Opcode = X86ISD::FMIN;
35695 break;
35696 case ISD::SETUGE:
35697 // Converting this to a min would handle both negative zeros and NaNs
35698 // incorrectly, but we can swap the operands to fix both.
35699 std::swap(LHS, RHS);
35700 LLVM_FALLTHROUGH[[clang::fallthrough]];
35701 case ISD::SETOGT:
35702 case ISD::SETGT:
35703 case ISD::SETGE:
35704 Opcode = X86ISD::FMIN;
35705 break;
35706
35707 case ISD::SETULT:
35708 // Converting this to a max would handle NaNs incorrectly.
35709 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
35710 break;
35711 Opcode = X86ISD::FMAX;
35712 break;
35713 case ISD::SETOLE:
35714 // Converting this to a max would handle comparisons between positive
35715 // and negative zero incorrectly, and swapping the operands would
35716 // cause it to handle NaNs incorrectly.
35717 if (!DAG.getTarget().Options.UnsafeFPMath &&
35718 !DAG.isKnownNeverZeroFloat(LHS) &&
35719 !DAG.isKnownNeverZeroFloat(RHS)) {
35720 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
35721 break;
35722 std::swap(LHS, RHS);
35723 }
35724 Opcode = X86ISD::FMAX;
35725 break;
35726 case ISD::SETULE:
35727 // Converting this to a max would handle both negative zeros and NaNs
35728 // incorrectly, but we can swap the operands to fix both.
35729 std::swap(LHS, RHS);
35730 LLVM_FALLTHROUGH[[clang::fallthrough]];
35731 case ISD::SETOLT:
35732 case ISD::SETLT:
35733 case ISD::SETLE:
35734 Opcode = X86ISD::FMAX;
35735 break;
35736 }
35737 }
35738
35739 if (Opcode)
35740 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
35741 }
35742
35743 // Some mask scalar intrinsics rely on checking if only one bit is set
35744 // and implement it in C code like this:
35745 // A[0] = (U & 1) ? A[0] : W[0];
35746 // This creates some redundant instructions that break pattern matching.
35747 // fold (select (setcc (and (X, 1), 0, seteq), Y, Z)) -> select(and(X, 1),Z,Y)
35748 if (Subtarget.hasAVX512() && N->getOpcode() == ISD::SELECT &&
35749 Cond.getOpcode() == ISD::SETCC && (VT == MVT::f32 || VT == MVT::f64)) {
35750 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
35751 SDValue AndNode = Cond.getOperand(0);
35752 if (AndNode.getOpcode() == ISD::AND && CC == ISD::SETEQ &&
35753 isNullConstant(Cond.getOperand(1)) &&
35754 isOneConstant(AndNode.getOperand(1))) {
35755 // LHS and RHS swapped due to
35756 // setcc outputting 1 when AND resulted in 0 and vice versa.
35757 AndNode = DAG.getZExtOrTrunc(AndNode, DL, MVT::i8);
35758 return DAG.getNode(ISD::SELECT, DL, VT, AndNode, RHS, LHS);
35759 }
35760 }
35761
35762 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
35763 // lowering on KNL. In this case we convert it to
35764 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
35765 // The same situation all vectors of i8 and i16 without BWI.
35766 // Make sure we extend these even before type legalization gets a chance to
35767 // split wide vectors.
35768 // Since SKX these selects have a proper lowering.
35769 if (Subtarget.hasAVX512() && !Subtarget.hasBWI() && CondVT.isVector() &&
35770 CondVT.getVectorElementType() == MVT::i1 &&
35771 (ExperimentalVectorWideningLegalization ||
35772 VT.getVectorNumElements() > 4) &&
35773 (VT.getVectorElementType() == MVT::i8 ||
35774 VT.getVectorElementType() == MVT::i16)) {
35775 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
35776 return DAG.getNode(N->getOpcode(), DL, VT, Cond, LHS, RHS);
35777 }
35778
35779 // AVX512 - Extend select with zero to merge with target shuffle.
35780 // select(mask, extract_subvector(shuffle(x)), zero) -->
35781 // extract_subvector(select(insert_subvector(mask), shuffle(x), zero))
35782 // TODO - support non target shuffles as well.
35783 if (Subtarget.hasAVX512() && CondVT.isVector() &&
35784 CondVT.getVectorElementType() == MVT::i1) {
35785 auto SelectableOp = [&TLI](SDValue Op) {
35786 return Op.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
35787 isTargetShuffle(Op.getOperand(0).getOpcode()) &&
35788 isNullConstant(Op.getOperand(1)) &&
35789 TLI.isTypeLegal(Op.getOperand(0).getValueType()) &&
35790 Op.hasOneUse() && Op.getOperand(0).hasOneUse();
35791 };
35792
35793 bool SelectableLHS = SelectableOp(LHS);
35794 bool SelectableRHS = SelectableOp(RHS);
35795 bool ZeroLHS = ISD::isBuildVectorAllZeros(LHS.getNode());
35796 bool ZeroRHS = ISD::isBuildVectorAllZeros(RHS.getNode());
35797
35798 if ((SelectableLHS && ZeroRHS) || (SelectableRHS && ZeroLHS)) {
35799 EVT SrcVT = SelectableLHS ? LHS.getOperand(0).getValueType()
35800 : RHS.getOperand(0).getValueType();
35801 unsigned NumSrcElts = SrcVT.getVectorNumElements();
35802 EVT SrcCondVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1, NumSrcElts);
35803 LHS = insertSubVector(DAG.getUNDEF(SrcVT), LHS, 0, DAG, DL,
35804 VT.getSizeInBits());
35805 RHS = insertSubVector(DAG.getUNDEF(SrcVT), RHS, 0, DAG, DL,
35806 VT.getSizeInBits());
35807 Cond = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SrcCondVT,
35808 DAG.getUNDEF(SrcCondVT), Cond,
35809 DAG.getIntPtrConstant(0, DL));
35810 SDValue Res = DAG.getSelect(DL, SrcVT, Cond, LHS, RHS);
35811 return extractSubVector(Res, 0, DAG, DL, VT.getSizeInBits());
35812 }
35813 }
35814
35815 if (SDValue V = combineSelectOfTwoConstants(N, DAG))
35816 return V;
35817
35818 // Canonicalize max and min:
35819 // (x > y) ? x : y -> (x >= y) ? x : y
35820 // (x < y) ? x : y -> (x <= y) ? x : y
35821 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
35822 // the need for an extra compare
35823 // against zero. e.g.
35824 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
35825 // subl %esi, %edi
35826 // testl %edi, %edi
35827 // movl $0, %eax
35828 // cmovgl %edi, %eax
35829 // =>
35830 // xorl %eax, %eax
35831 // subl %esi, $edi
35832 // cmovsl %eax, %edi
35833 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
35834 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
35835 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
35836 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
35837 switch (CC) {
35838 default: break;
35839 case ISD::SETLT:
35840 case ISD::SETGT: {
35841 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
35842 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
35843 Cond.getOperand(0), Cond.getOperand(1), NewCC);
35844 return DAG.getSelect(DL, VT, Cond, LHS, RHS);
35845 }
35846 }
35847 }
35848
35849 // Match VSELECTs into subs with unsigned saturation.
35850 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
35851 // psubus is available in SSE2 for i8 and i16 vectors.
35852 Subtarget.hasSSE2() && VT.getVectorNumElements() >= 2 &&
35853 isPowerOf2_32(VT.getVectorNumElements()) &&
35854 (VT.getVectorElementType() == MVT::i8 ||
35855 VT.getVectorElementType() == MVT::i16)) {
35856 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
35857
35858 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
35859 // left side invert the predicate to simplify logic below.
35860 SDValue Other;
35861 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
35862 Other = RHS;
35863 CC = ISD::getSetCCInverse(CC, true);
35864 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
35865 Other = LHS;
35866 }
35867
35868 if (Other.getNode() && Other->getNumOperands() == 2 &&
35869 Other->getOperand(0) == Cond.getOperand(0)) {
35870 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
35871 SDValue CondRHS = Cond->getOperand(1);
35872
35873 // Look for a general sub with unsigned saturation first.
35874 // x >= y ? x-y : 0 --> subus x, y
35875 // x > y ? x-y : 0 --> subus x, y
35876 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
35877 Other->getOpcode() == ISD::SUB && OpRHS == CondRHS)
35878 return DAG.getNode(ISD::USUBSAT, DL, VT, OpLHS, OpRHS);
35879
35880 if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS)) {
35881 if (isa<BuildVectorSDNode>(CondRHS)) {
35882 // If the RHS is a constant we have to reverse the const
35883 // canonicalization.
35884 // x > C-1 ? x+-C : 0 --> subus x, C
35885 auto MatchUSUBSAT = [](ConstantSDNode *Op, ConstantSDNode *Cond) {
35886 return (!Op && !Cond) ||
35887 (Op && Cond &&
35888 Cond->getAPIntValue() == (-Op->getAPIntValue() - 1));
35889 };
35890 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
35891 ISD::matchBinaryPredicate(OpRHS, CondRHS, MatchUSUBSAT,
35892 /*AllowUndefs*/ true)) {
35893 OpRHS = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
35894 OpRHS);
35895 return DAG.getNode(ISD::USUBSAT, DL, VT, OpLHS, OpRHS);
35896 }
35897
35898 // Another special case: If C was a sign bit, the sub has been
35899 // canonicalized into a xor.
35900 // FIXME: Would it be better to use computeKnownBits to determine
35901 // whether it's safe to decanonicalize the xor?
35902 // x s< 0 ? x^C : 0 --> subus x, C
35903 if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
35904 if (CC == ISD::SETLT && Other.getOpcode() == ISD::XOR &&
35905 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
35906 OpRHSConst->getAPIntValue().isSignMask()) {
35907 // Note that we have to rebuild the RHS constant here to ensure we
35908 // don't rely on particular values of undef lanes.
35909 OpRHS = DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT);
35910 return DAG.getNode(ISD::USUBSAT, DL, VT, OpLHS, OpRHS);
35911 }
35912 }
35913 }
35914 }
35915 }
35916 }
35917
35918 // Match VSELECTs into add with unsigned saturation.
35919 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
35920 // paddus is available in SSE2 for i8 and i16 vectors.
35921 Subtarget.hasSSE2() && VT.getVectorNumElements() >= 2 &&
35922 isPowerOf2_32(VT.getVectorNumElements()) &&
35923 (VT.getVectorElementType() == MVT::i8 ||
35924 VT.getVectorElementType() == MVT::i16)) {
35925 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
35926
35927 SDValue CondLHS = Cond->getOperand(0);
35928 SDValue CondRHS = Cond->getOperand(1);
35929
35930 // Check if one of the arms of the VSELECT is vector with all bits set.
35931 // If it's on the left side invert the predicate to simplify logic below.
35932 SDValue Other;
35933 if (ISD::isBuildVectorAllOnes(LHS.getNode())) {
35934 Other = RHS;
35935 CC = ISD::getSetCCInverse(CC, true);
35936 } else if (ISD::isBuildVectorAllOnes(RHS.getNode())) {
35937 Other = LHS;
35938 }
35939
35940 if (Other.getNode() && Other.getOpcode() == ISD::ADD) {
35941 SDValue OpLHS = Other.getOperand(0), OpRHS = Other.getOperand(1);
35942
35943 // Canonicalize condition operands.
35944 if (CC == ISD::SETUGE) {
35945 std::swap(CondLHS, CondRHS);
35946 CC = ISD::SETULE;
35947 }
35948
35949 // We can test against either of the addition operands.
35950 // x <= x+y ? x+y : ~0 --> addus x, y
35951 // x+y >= x ? x+y : ~0 --> addus x, y
35952 if (CC == ISD::SETULE && Other == CondRHS &&
35953 (OpLHS == CondLHS || OpRHS == CondLHS))
35954 return DAG.getNode(ISD::UADDSAT, DL, VT, OpLHS, OpRHS);
35955
35956 if (isa<BuildVectorSDNode>(OpRHS) && isa<BuildVectorSDNode>(CondRHS) &&
35957 CondLHS == OpLHS) {
35958 // If the RHS is a constant we have to reverse the const
35959 // canonicalization.
35960 // x > ~C ? x+C : ~0 --> addus x, C
35961 auto MatchUADDSAT = [](ConstantSDNode *Op, ConstantSDNode *Cond) {
35962 return Cond->getAPIntValue() == ~Op->getAPIntValue();
35963 };
35964 if (CC == ISD::SETULE &&
35965 ISD::matchBinaryPredicate(OpRHS, CondRHS, MatchUADDSAT))
35966 return DAG.getNode(ISD::UADDSAT, DL, VT, OpLHS, OpRHS);
35967 }
35968 }
35969 }
35970
35971 // Early exit check
35972 if (!TLI.isTypeLegal(VT))
35973 return SDValue();
35974
35975 if (SDValue V = combineVSelectWithAllOnesOrZeros(N, DAG, DCI, Subtarget))
35976 return V;
35977
35978 if (SDValue V = combineVSelectToBLENDV(N, DAG, DCI, Subtarget))
35979 return V;
35980
35981 // Custom action for SELECT MMX
35982 if (VT == MVT::x86mmx) {
35983 LHS = DAG.getBitcast(MVT::i64, LHS);
35984 RHS = DAG.getBitcast(MVT::i64, RHS);
35985 SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::i64, Cond, LHS, RHS);
35986 return DAG.getBitcast(VT, newSelect);
35987 }
35988
35989 return SDValue();
35990}
35991
35992/// Combine:
35993/// (brcond/cmov/setcc .., (cmp (atomic_load_add x, 1), 0), COND_S)
35994/// to:
35995/// (brcond/cmov/setcc .., (LADD x, 1), COND_LE)
35996/// i.e., reusing the EFLAGS produced by the LOCKed instruction.
35997/// Note that this is only legal for some op/cc combinations.
35998static SDValue combineSetCCAtomicArith(SDValue Cmp, X86::CondCode &CC,
35999 SelectionDAG &DAG,
36000 const X86Subtarget &Subtarget) {
36001 // This combine only operates on CMP-like nodes.
36002 if (!(Cmp.getOpcode() == X86ISD::CMP ||
36003 (Cmp.getOpcode() == X86ISD::SUB && !Cmp->hasAnyUseOfValue(0))))
36004 return SDValue();
36005
36006 // Can't replace the cmp if it has more uses than the one we're looking at.
36007 // FIXME: We would like to be able to handle this, but would need to make sure
36008 // all uses were updated.
36009 if (!Cmp.hasOneUse())
36010 return SDValue();
36011
36012 // This only applies to variations of the common case:
36013 // (icmp slt x, 0) -> (icmp sle (add x, 1), 0)
36014 // (icmp sge x, 0) -> (icmp sgt (add x, 1), 0)
36015 // (icmp sle x, 0) -> (icmp slt (sub x, 1), 0)
36016 // (icmp sgt x, 0) -> (icmp sge (sub x, 1), 0)
36017 // Using the proper condcodes (see below), overflow is checked for.
36018
36019 // FIXME: We can generalize both constraints:
36020 // - XOR/OR/AND (if they were made to survive AtomicExpand)
36021 // - LHS != 1
36022 // if the result is compared.
36023
36024 SDValue CmpLHS = Cmp.getOperand(0);
36025 SDValue CmpRHS = Cmp.getOperand(1);
36026
36027 if (!CmpLHS.hasOneUse())
36028 return SDValue();
36029
36030 unsigned Opc = CmpLHS.getOpcode();
36031 if (Opc != ISD::ATOMIC_LOAD_ADD && Opc != ISD::ATOMIC_LOAD_SUB)
36032 return SDValue();
36033
36034 SDValue OpRHS = CmpLHS.getOperand(2);
36035 auto *OpRHSC = dyn_cast<ConstantSDNode>(OpRHS);
36036 if (!OpRHSC)
36037 return SDValue();
36038
36039 APInt Addend = OpRHSC->getAPIntValue();
36040 if (Opc == ISD::ATOMIC_LOAD_SUB)
36041 Addend = -Addend;
36042
36043 auto *CmpRHSC = dyn_cast<ConstantSDNode>(CmpRHS);
36044 if (!CmpRHSC)
36045 return SDValue();
36046
36047 APInt Comparison = CmpRHSC->getAPIntValue();
36048
36049 // If the addend is the negation of the comparison value, then we can do
36050 // a full comparison by emitting the atomic arithmetic as a locked sub.
36051 if (Comparison == -Addend) {
36052 // The CC is fine, but we need to rewrite the LHS of the comparison as an
36053 // atomic sub.
36054 auto *AN = cast<AtomicSDNode>(CmpLHS.getNode());
36055 auto AtomicSub = DAG.getAtomic(
36056 ISD::ATOMIC_LOAD_SUB, SDLoc(CmpLHS), CmpLHS.getValueType(),
36057 /*Chain*/ CmpLHS.getOperand(0), /*LHS*/ CmpLHS.getOperand(1),
36058 /*RHS*/ DAG.getConstant(-Addend, SDLoc(CmpRHS), CmpRHS.getValueType()),
36059 AN->getMemOperand());
36060 auto LockOp = lowerAtomicArithWithLOCK(AtomicSub, DAG, Subtarget);
36061 DAG.ReplaceAllUsesOfValueWith(CmpLHS.getValue(0),
36062 DAG.getUNDEF(CmpLHS.getValueType()));
36063 DAG.ReplaceAllUsesOfValueWith(CmpLHS.getValue(1), LockOp.getValue(1));
36064 return LockOp;
36065 }
36066
36067 // We can handle comparisons with zero in a number of cases by manipulating
36068 // the CC used.
36069 if (!Comparison.isNullValue())
36070 return SDValue();
36071
36072 if (CC == X86::COND_S && Addend == 1)
36073 CC = X86::COND_LE;
36074 else if (CC == X86::COND_NS && Addend == 1)
36075 CC = X86::COND_G;
36076 else if (CC == X86::COND_G && Addend == -1)
36077 CC = X86::COND_GE;
36078 else if (CC == X86::COND_LE && Addend == -1)
36079 CC = X86::COND_L;
36080 else
36081 return SDValue();
36082
36083 SDValue LockOp = lowerAtomicArithWithLOCK(CmpLHS, DAG, Subtarget);
36084 DAG.ReplaceAllUsesOfValueWith(CmpLHS.getValue(0),
36085 DAG.getUNDEF(CmpLHS.getValueType()));
36086 DAG.ReplaceAllUsesOfValueWith(CmpLHS.getValue(1), LockOp.getValue(1));
36087 return LockOp;
36088}
36089
36090// Check whether a boolean test is testing a boolean value generated by
36091// X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
36092// code.
36093//
36094// Simplify the following patterns:
36095// (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
36096// (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
36097// to (Op EFLAGS Cond)
36098//
36099// (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
36100// (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
36101// to (Op EFLAGS !Cond)
36102//
36103// where Op could be BRCOND or CMOV.
36104//
36105static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
36106 // This combine only operates on CMP-like nodes.
36107 if (!(Cmp.getOpcode() == X86ISD::CMP ||
36108 (Cmp.getOpcode() == X86ISD::SUB && !Cmp->hasAnyUseOfValue(0))))
36109 return SDValue();
36110
36111 // Quit if not used as a boolean value.
36112 if (CC != X86::COND_E && CC != X86::COND_NE)
36113 return SDValue();
36114
36115 // Check CMP operands. One of them should be 0 or 1 and the other should be
36116 // an SetCC or extended from it.
36117 SDValue Op1 = Cmp.getOperand(0);
36118 SDValue Op2 = Cmp.getOperand(1);
36119
36120 SDValue SetCC;
36121 const ConstantSDNode* C = nullptr;
36122 bool needOppositeCond = (CC == X86::COND_E);
36123 bool checkAgainstTrue = false; // Is it a comparison against 1?
36124
36125 if ((C = dyn_cast<ConstantSDNode>(Op1)))
36126 SetCC = Op2;
36127 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
36128 SetCC = Op1;
36129 else // Quit if all operands are not constants.
36130 return SDValue();
36131
36132 if (C->getZExtValue() == 1) {
36133 needOppositeCond = !needOppositeCond;
36134 checkAgainstTrue = true;
36135 } else if (C->getZExtValue() != 0)
36136 // Quit if the constant is neither 0 or 1.
36137 return SDValue();
36138
36139 bool truncatedToBoolWithAnd = false;
36140 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
36141 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
36142 SetCC.getOpcode() == ISD::TRUNCATE ||
36143 SetCC.getOpcode() == ISD::AND) {
36144 if (SetCC.getOpcode() == ISD::AND) {
36145 int OpIdx = -1;
36146 if (isOneConstant(SetCC.getOperand(0)))
36147 OpIdx = 1;
36148 if (isOneConstant(SetCC.getOperand(1)))
36149 OpIdx = 0;
36150 if (OpIdx < 0)
36151 break;
36152 SetCC = SetCC.getOperand(OpIdx);
36153 truncatedToBoolWithAnd = true;
36154 } else
36155 SetCC = SetCC.getOperand(0);
36156 }
36157
36158 switch (SetCC.getOpcode()) {
36159 case X86ISD::SETCC_CARRY:
36160 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
36161 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
36162 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
36163 // truncated to i1 using 'and'.
36164 if (checkAgainstTrue && !truncatedToBoolWithAnd)
36165 break;
36166 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&((X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B
&& "Invalid use of SETCC_CARRY!") ? static_cast<void
> (0) : __assert_fail ("X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B && \"Invalid use of SETCC_CARRY!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 36167, __PRETTY_FUNCTION__))
36167 "Invalid use of SETCC_CARRY!")((X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B
&& "Invalid use of SETCC_CARRY!") ? static_cast<void
> (0) : __assert_fail ("X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B && \"Invalid use of SETCC_CARRY!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 36167, __PRETTY_FUNCTION__))
;
36168 LLVM_FALLTHROUGH[[clang::fallthrough]];
36169 case X86ISD::SETCC:
36170 // Set the condition code or opposite one if necessary.
36171 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
36172 if (needOppositeCond)
36173 CC = X86::GetOppositeBranchCondition(CC);
36174 return SetCC.getOperand(1);
36175 case X86ISD::CMOV: {
36176 // Check whether false/true value has canonical one, i.e. 0 or 1.
36177 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
36178 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
36179 // Quit if true value is not a constant.
36180 if (!TVal)
36181 return SDValue();
36182 // Quit if false value is not a constant.
36183 if (!FVal) {
36184 SDValue Op = SetCC.getOperand(0);
36185 // Skip 'zext' or 'trunc' node.
36186 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
36187 Op.getOpcode() == ISD::TRUNCATE)
36188 Op = Op.getOperand(0);
36189 // A special case for rdrand/rdseed, where 0 is set if false cond is
36190 // found.
36191 if ((Op.getOpcode() != X86ISD::RDRAND &&
36192 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
36193 return SDValue();
36194 }
36195 // Quit if false value is not the constant 0 or 1.
36196 bool FValIsFalse = true;
36197 if (FVal && FVal->getZExtValue() != 0) {
36198 if (FVal->getZExtValue() != 1)
36199 return SDValue();
36200 // If FVal is 1, opposite cond is needed.
36201 needOppositeCond = !needOppositeCond;
36202 FValIsFalse = false;
36203 }
36204 // Quit if TVal is not the constant opposite of FVal.
36205 if (FValIsFalse && TVal->getZExtValue() != 1)
36206 return SDValue();
36207 if (!FValIsFalse && TVal->getZExtValue() != 0)
36208 return SDValue();
36209 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
36210 if (needOppositeCond)
36211 CC = X86::GetOppositeBranchCondition(CC);
36212 return SetCC.getOperand(3);
36213 }
36214 }
36215
36216 return SDValue();
36217}
36218
36219/// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
36220/// Match:
36221/// (X86or (X86setcc) (X86setcc))
36222/// (X86cmp (and (X86setcc) (X86setcc)), 0)
36223static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
36224 X86::CondCode &CC1, SDValue &Flags,
36225 bool &isAnd) {
36226 if (Cond->getOpcode() == X86ISD::CMP) {
36227 if (!isNullConstant(Cond->getOperand(1)))
36228 return false;
36229
36230 Cond = Cond->getOperand(0);
36231 }
36232
36233 isAnd = false;
36234
36235 SDValue SetCC0, SetCC1;
36236 switch (Cond->getOpcode()) {
36237 default: return false;
36238 case ISD::AND:
36239 case X86ISD::AND:
36240 isAnd = true;
36241 LLVM_FALLTHROUGH[[clang::fallthrough]];
36242 case ISD::OR:
36243 case X86ISD::OR:
36244 SetCC0 = Cond->getOperand(0);
36245 SetCC1 = Cond->getOperand(1);
36246 break;
36247 };
36248
36249 // Make sure we have SETCC nodes, using the same flags value.
36250 if (SetCC0.getOpcode() != X86ISD::SETCC ||
36251 SetCC1.getOpcode() != X86ISD::SETCC ||
36252 SetCC0->getOperand(1) != SetCC1->getOperand(1))
36253 return false;
36254
36255 CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
36256 CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
36257 Flags = SetCC0->getOperand(1);
36258 return true;
36259}
36260
36261// When legalizing carry, we create carries via add X, -1
36262// If that comes from an actual carry, via setcc, we use the
36263// carry directly.
36264static SDValue combineCarryThroughADD(SDValue EFLAGS, SelectionDAG &DAG) {
36265 if (EFLAGS.getOpcode() == X86ISD::ADD) {
36266 if (isAllOnesConstant(EFLAGS.getOperand(1))) {
36267 SDValue Carry = EFLAGS.getOperand(0);
36268 while (Carry.getOpcode() == ISD::TRUNCATE ||
36269 Carry.getOpcode() == ISD::ZERO_EXTEND ||
36270 Carry.getOpcode() == ISD::SIGN_EXTEND ||
36271 Carry.getOpcode() == ISD::ANY_EXTEND ||
36272 (Carry.getOpcode() == ISD::AND &&
36273 isOneConstant(Carry.getOperand(1))))
36274 Carry = Carry.getOperand(0);
36275 if (Carry.getOpcode() == X86ISD::SETCC ||
36276 Carry.getOpcode() == X86ISD::SETCC_CARRY) {
36277 // TODO: Merge this code with equivalent in combineAddOrSubToADCOrSBB?
36278 uint64_t CarryCC = Carry.getConstantOperandVal(0);
36279 SDValue CarryOp1 = Carry.getOperand(1);
36280 if (CarryCC == X86::COND_B)
36281 return CarryOp1;
36282 if (CarryCC == X86::COND_A) {
36283 // Try to convert COND_A into COND_B in an attempt to facilitate
36284 // materializing "setb reg".
36285 //
36286 // Do not flip "e > c", where "c" is a constant, because Cmp
36287 // instruction cannot take an immediate as its first operand.
36288 //
36289 if (CarryOp1.getOpcode() == X86ISD::SUB &&
36290 CarryOp1.getNode()->hasOneUse() &&
36291 CarryOp1.getValueType().isInteger() &&
36292 !isa<ConstantSDNode>(CarryOp1.getOperand(1))) {
36293 SDValue SubCommute =
36294 DAG.getNode(X86ISD::SUB, SDLoc(CarryOp1), CarryOp1->getVTList(),
36295 CarryOp1.getOperand(1), CarryOp1.getOperand(0));
36296 return SDValue(SubCommute.getNode(), CarryOp1.getResNo());
36297 }
36298 }
36299 // If this is a check of the z flag of an add with 1, switch to the
36300 // C flag.
36301 if (CarryCC == X86::COND_E &&
36302 CarryOp1.getOpcode() == X86ISD::ADD &&
36303 isOneConstant(CarryOp1.getOperand(1)))
36304 return CarryOp1;
36305 }
36306 }
36307 }
36308
36309 return SDValue();
36310}
36311
36312/// Optimize an EFLAGS definition used according to the condition code \p CC
36313/// into a simpler EFLAGS value, potentially returning a new \p CC and replacing
36314/// uses of chain values.
36315static SDValue combineSetCCEFLAGS(SDValue EFLAGS, X86::CondCode &CC,
36316 SelectionDAG &DAG,
36317 const X86Subtarget &Subtarget) {
36318 if (CC == X86::COND_B)
36319 if (SDValue Flags = combineCarryThroughADD(EFLAGS, DAG))
36320 return Flags;
36321
36322 if (SDValue R = checkBoolTestSetCCCombine(EFLAGS, CC))
36323 return R;
36324 return combineSetCCAtomicArith(EFLAGS, CC, DAG, Subtarget);
36325}
36326
36327/// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
36328static SDValue combineCMov(SDNode *N, SelectionDAG &DAG,
36329 TargetLowering::DAGCombinerInfo &DCI,
36330 const X86Subtarget &Subtarget) {
36331 SDLoc DL(N);
36332
36333 SDValue FalseOp = N->getOperand(0);
36334 SDValue TrueOp = N->getOperand(1);
36335 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
36336 SDValue Cond = N->getOperand(3);
36337
36338 // Try to simplify the EFLAGS and condition code operands.
36339 // We can't always do this as FCMOV only supports a subset of X86 cond.
36340 if (SDValue Flags = combineSetCCEFLAGS(Cond, CC, DAG, Subtarget)) {
36341 if (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC)) {
36342 SDValue Ops[] = {FalseOp, TrueOp, DAG.getConstant(CC, DL, MVT::i8),
36343 Flags};
36344 return DAG.getNode(X86ISD::CMOV, DL, N->getValueType(0), Ops);
36345 }
36346 }
36347
36348 // If this is a select between two integer constants, try to do some
36349 // optimizations. Note that the operands are ordered the opposite of SELECT
36350 // operands.
36351 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
36352 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
36353 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
36354 // larger than FalseC (the false value).
36355 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
36356 CC = X86::GetOppositeBranchCondition(CC);
36357 std::swap(TrueC, FalseC);
36358 std::swap(TrueOp, FalseOp);
36359 }
36360
36361 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
36362 // This is efficient for any integer data type (including i8/i16) and
36363 // shift amount.
36364 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
36365 Cond = getSETCC(CC, Cond, DL, DAG);
36366
36367 // Zero extend the condition if needed.
36368 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
36369
36370 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
36371 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
36372 DAG.getConstant(ShAmt, DL, MVT::i8));
36373 return Cond;
36374 }
36375
36376 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
36377 // for any integer data type, including i8/i16.
36378 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
36379 Cond = getSETCC(CC, Cond, DL, DAG);
36380
36381 // Zero extend the condition if needed.
36382 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
36383 FalseC->getValueType(0), Cond);
36384 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
36385 SDValue(FalseC, 0));
36386 return Cond;
36387 }
36388
36389 // Optimize cases that will turn into an LEA instruction. This requires
36390 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
36391 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
36392 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
36393 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
36394
36395 bool isFastMultiplier = false;
36396 if (Diff < 10) {
36397 switch ((unsigned char)Diff) {
36398 default: break;
36399 case 1: // result = add base, cond
36400 case 2: // result = lea base( , cond*2)
36401 case 3: // result = lea base(cond, cond*2)
36402 case 4: // result = lea base( , cond*4)
36403 case 5: // result = lea base(cond, cond*4)
36404 case 8: // result = lea base( , cond*8)
36405 case 9: // result = lea base(cond, cond*8)
36406 isFastMultiplier = true;
36407 break;
36408 }
36409 }
36410
36411 if (isFastMultiplier) {
36412 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
36413 Cond = getSETCC(CC, Cond, DL ,DAG);
36414 // Zero extend the condition if needed.
36415 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
36416 Cond);
36417 // Scale the condition by the difference.
36418 if (Diff != 1)
36419 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
36420 DAG.getConstant(Diff, DL, Cond.getValueType()));
36421
36422 // Add the base if non-zero.
36423 if (FalseC->getAPIntValue() != 0)
36424 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
36425 SDValue(FalseC, 0));
36426 return Cond;
36427 }
36428 }
36429 }
36430 }
36431
36432 // Handle these cases:
36433 // (select (x != c), e, c) -> select (x != c), e, x),
36434 // (select (x == c), c, e) -> select (x == c), x, e)
36435 // where the c is an integer constant, and the "select" is the combination
36436 // of CMOV and CMP.
36437 //
36438 // The rationale for this change is that the conditional-move from a constant
36439 // needs two instructions, however, conditional-move from a register needs
36440 // only one instruction.
36441 //
36442 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
36443 // some instruction-combining opportunities. This opt needs to be
36444 // postponed as late as possible.
36445 //
36446 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
36447 // the DCI.xxxx conditions are provided to postpone the optimization as
36448 // late as possible.
36449
36450 ConstantSDNode *CmpAgainst = nullptr;
36451 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
36452 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
36453 !isa<ConstantSDNode>(Cond.getOperand(0))) {
36454
36455 if (CC == X86::COND_NE &&
36456 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
36457 CC = X86::GetOppositeBranchCondition(CC);
36458 std::swap(TrueOp, FalseOp);
36459 }
36460
36461 if (CC == X86::COND_E &&
36462 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
36463 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
36464 DAG.getConstant(CC, DL, MVT::i8), Cond };
36465 return DAG.getNode(X86ISD::CMOV, DL, N->getValueType(0), Ops);
36466 }
36467 }
36468 }
36469
36470 // Fold and/or of setcc's to double CMOV:
36471 // (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
36472 // (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
36473 //
36474 // This combine lets us generate:
36475 // cmovcc1 (jcc1 if we don't have CMOV)
36476 // cmovcc2 (same)
36477 // instead of:
36478 // setcc1
36479 // setcc2
36480 // and/or
36481 // cmovne (jne if we don't have CMOV)
36482 // When we can't use the CMOV instruction, it might increase branch
36483 // mispredicts.
36484 // When we can use CMOV, or when there is no mispredict, this improves
36485 // throughput and reduces register pressure.
36486 //
36487 if (CC == X86::COND_NE) {
36488 SDValue Flags;
36489 X86::CondCode CC0, CC1;
36490 bool isAndSetCC;
36491 if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
36492 if (isAndSetCC) {
36493 std::swap(FalseOp, TrueOp);
36494 CC0 = X86::GetOppositeBranchCondition(CC0);
36495 CC1 = X86::GetOppositeBranchCondition(CC1);
36496 }
36497
36498 SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
36499 Flags};
36500 SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getValueType(0), LOps);
36501 SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
36502 SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getValueType(0), Ops);
36503 return CMOV;
36504 }
36505 }
36506
36507 // Fold (CMOV C1, (ADD (CTTZ X), C2), (X != 0)) ->
36508 // (ADD (CMOV C1-C2, (CTTZ X), (X != 0)), C2)
36509 // Or (CMOV (ADD (CTTZ X), C2), C1, (X == 0)) ->
36510 // (ADD (CMOV (CTTZ X), C1-C2, (X == 0)), C2)
36511 if ((CC == X86::COND_NE || CC == X86::COND_E) &&
36512 Cond.getOpcode() == X86ISD::CMP && isNullConstant(Cond.getOperand(1))) {
36513 SDValue Add = TrueOp;
36514 SDValue Const = FalseOp;
36515 // Canonicalize the condition code for easier matching and output.
36516 if (CC == X86::COND_E)
36517 std::swap(Add, Const);
36518
36519 // We might have replaced the constant in the cmov with the LHS of the
36520 // compare. If so change it to the RHS of the compare.
36521 if (Const == Cond.getOperand(0))
36522 Const = Cond.getOperand(1);
36523
36524 // Ok, now make sure that Add is (add (cttz X), C2) and Const is a constant.
36525 if (isa<ConstantSDNode>(Const) && Add.getOpcode() == ISD::ADD &&
36526 Add.hasOneUse() && isa<ConstantSDNode>(Add.getOperand(1)) &&
36527 (Add.getOperand(0).getOpcode() == ISD::CTTZ_ZERO_UNDEF ||
36528 Add.getOperand(0).getOpcode() == ISD::CTTZ) &&
36529 Add.getOperand(0).getOperand(0) == Cond.getOperand(0)) {
36530 EVT VT = N->getValueType(0);
36531 // This should constant fold.
36532 SDValue Diff = DAG.getNode(ISD::SUB, DL, VT, Const, Add.getOperand(1));
36533 SDValue CMov = DAG.getNode(X86ISD::CMOV, DL, VT, Diff, Add.getOperand(0),
36534 DAG.getConstant(X86::COND_NE, DL, MVT::i8),
36535 Cond);
36536 return DAG.getNode(ISD::ADD, DL, VT, CMov, Add.getOperand(1));
36537 }
36538 }
36539
36540 return SDValue();
36541}
36542
36543/// Different mul shrinking modes.
36544enum ShrinkMode { MULS8, MULU8, MULS16, MULU16 };
36545
36546static bool canReduceVMulWidth(SDNode *N, SelectionDAG &DAG, ShrinkMode &Mode) {
36547 EVT VT = N->getOperand(0).getValueType();
36548 if (VT.getScalarSizeInBits() != 32)
36549 return false;
36550
36551 assert(N->getNumOperands() == 2 && "NumOperands of Mul are 2")((N->getNumOperands() == 2 && "NumOperands of Mul are 2"
) ? static_cast<void> (0) : __assert_fail ("N->getNumOperands() == 2 && \"NumOperands of Mul are 2\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 36551, __PRETTY_FUNCTION__))
;
36552 unsigned SignBits[2] = {1, 1};
36553 bool IsPositive[2] = {false, false};
36554 for (unsigned i = 0; i < 2; i++) {
36555 SDValue Opd = N->getOperand(i);
36556
36557 SignBits[i] = DAG.ComputeNumSignBits(Opd);
36558 IsPositive[i] = DAG.SignBitIsZero(Opd);
36559 }
36560
36561 bool AllPositive = IsPositive[0] && IsPositive[1];
36562 unsigned MinSignBits = std::min(SignBits[0], SignBits[1]);
36563 // When ranges are from -128 ~ 127, use MULS8 mode.
36564 if (MinSignBits >= 25)
36565 Mode = MULS8;
36566 // When ranges are from 0 ~ 255, use MULU8 mode.
36567 else if (AllPositive && MinSignBits >= 24)
36568 Mode = MULU8;
36569 // When ranges are from -32768 ~ 32767, use MULS16 mode.
36570 else if (MinSignBits >= 17)
36571 Mode = MULS16;
36572 // When ranges are from 0 ~ 65535, use MULU16 mode.
36573 else if (AllPositive && MinSignBits >= 16)
36574 Mode = MULU16;
36575 else
36576 return false;
36577 return true;
36578}
36579
36580/// When the operands of vector mul are extended from smaller size values,
36581/// like i8 and i16, the type of mul may be shrinked to generate more
36582/// efficient code. Two typical patterns are handled:
36583/// Pattern1:
36584/// %2 = sext/zext <N x i8> %1 to <N x i32>
36585/// %4 = sext/zext <N x i8> %3 to <N x i32>
36586// or %4 = build_vector <N x i32> %C1, ..., %CN (%C1..%CN are constants)
36587/// %5 = mul <N x i32> %2, %4
36588///
36589/// Pattern2:
36590/// %2 = zext/sext <N x i16> %1 to <N x i32>
36591/// %4 = zext/sext <N x i16> %3 to <N x i32>
36592/// or %4 = build_vector <N x i32> %C1, ..., %CN (%C1..%CN are constants)
36593/// %5 = mul <N x i32> %2, %4
36594///
36595/// There are four mul shrinking modes:
36596/// If %2 == sext32(trunc8(%2)), i.e., the scalar value range of %2 is
36597/// -128 to 128, and the scalar value range of %4 is also -128 to 128,
36598/// generate pmullw+sext32 for it (MULS8 mode).
36599/// If %2 == zext32(trunc8(%2)), i.e., the scalar value range of %2 is
36600/// 0 to 255, and the scalar value range of %4 is also 0 to 255,
36601/// generate pmullw+zext32 for it (MULU8 mode).
36602/// If %2 == sext32(trunc16(%2)), i.e., the scalar value range of %2 is
36603/// -32768 to 32767, and the scalar value range of %4 is also -32768 to 32767,
36604/// generate pmullw+pmulhw for it (MULS16 mode).
36605/// If %2 == zext32(trunc16(%2)), i.e., the scalar value range of %2 is
36606/// 0 to 65535, and the scalar value range of %4 is also 0 to 65535,
36607/// generate pmullw+pmulhuw for it (MULU16 mode).
36608static SDValue reduceVMULWidth(SDNode *N, SelectionDAG &DAG,
36609 const X86Subtarget &Subtarget) {
36610 // Check for legality
36611 // pmullw/pmulhw are not supported by SSE.
36612 if (!Subtarget.hasSSE2())
36613 return SDValue();
36614
36615 // Check for profitability
36616 // pmulld is supported since SSE41. It is better to use pmulld
36617 // instead of pmullw+pmulhw, except for subtargets where pmulld is slower than
36618 // the expansion.
36619 bool OptForMinSize = DAG.getMachineFunction().getFunction().hasMinSize();
36620 if (Subtarget.hasSSE41() && (OptForMinSize || !Subtarget.isPMULLDSlow()))
36621 return SDValue();
36622
36623 ShrinkMode Mode;
36624 if (!canReduceVMulWidth(N, DAG, Mode))
36625 return SDValue();
36626
36627 SDLoc DL(N);
36628 SDValue N0 = N->getOperand(0);
36629 SDValue N1 = N->getOperand(1);
36630 EVT VT = N->getOperand(0).getValueType();
36631 unsigned NumElts = VT.getVectorNumElements();
36632 if ((NumElts % 2) != 0)
36633 return SDValue();
36634
36635 unsigned RegSize = 128;
36636 MVT OpsVT = MVT::getVectorVT(MVT::i16, RegSize / 16);
36637 EVT ReducedVT = EVT::getVectorVT(*DAG.getContext(), MVT::i16, NumElts);
36638
36639 // Shrink the operands of mul.
36640 SDValue NewN0 = DAG.getNode(ISD::TRUNCATE, DL, ReducedVT, N0);
36641 SDValue NewN1 = DAG.getNode(ISD::TRUNCATE, DL, ReducedVT, N1);
36642
36643 if (ExperimentalVectorWideningLegalization ||
36644 NumElts >= OpsVT.getVectorNumElements()) {
36645 // Generate the lower part of mul: pmullw. For MULU8/MULS8, only the
36646 // lower part is needed.
36647 SDValue MulLo = DAG.getNode(ISD::MUL, DL, ReducedVT, NewN0, NewN1);
36648 if (Mode == MULU8 || Mode == MULS8)
36649 return DAG.getNode((Mode == MULU8) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND,
36650 DL, VT, MulLo);
36651
36652 MVT ResVT = MVT::getVectorVT(MVT::i32, NumElts / 2);
36653 // Generate the higher part of mul: pmulhw/pmulhuw. For MULU16/MULS16,
36654 // the higher part is also needed.
36655 SDValue MulHi = DAG.getNode(Mode == MULS16 ? ISD::MULHS : ISD::MULHU, DL,
36656 ReducedVT, NewN0, NewN1);
36657
36658 // Repack the lower part and higher part result of mul into a wider
36659 // result.
36660 // Generate shuffle functioning as punpcklwd.
36661 SmallVector<int, 16> ShuffleMask(NumElts);
36662 for (unsigned i = 0, e = NumElts / 2; i < e; i++) {
36663 ShuffleMask[2 * i] = i;
36664 ShuffleMask[2 * i + 1] = i + NumElts;
36665 }
36666 SDValue ResLo =
36667 DAG.getVectorShuffle(ReducedVT, DL, MulLo, MulHi, ShuffleMask);
36668 ResLo = DAG.getBitcast(ResVT, ResLo);
36669 // Generate shuffle functioning as punpckhwd.
36670 for (unsigned i = 0, e = NumElts / 2; i < e; i++) {
36671 ShuffleMask[2 * i] = i + NumElts / 2;
36672 ShuffleMask[2 * i + 1] = i + NumElts * 3 / 2;
36673 }
36674 SDValue ResHi =
36675 DAG.getVectorShuffle(ReducedVT, DL, MulLo, MulHi, ShuffleMask);
36676 ResHi = DAG.getBitcast(ResVT, ResHi);
36677 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ResLo, ResHi);
36678 }
36679
36680 // When VT.getVectorNumElements() < OpsVT.getVectorNumElements(), we want
36681 // to legalize the mul explicitly because implicit legalization for type
36682 // <4 x i16> to <4 x i32> sometimes involves unnecessary unpack
36683 // instructions which will not exist when we explicitly legalize it by
36684 // extending <4 x i16> to <8 x i16> (concatenating the <4 x i16> val with
36685 // <4 x i16> undef).
36686 //
36687 // Legalize the operands of mul.
36688 // FIXME: We may be able to handle non-concatenated vectors by insertion.
36689 unsigned ReducedSizeInBits = ReducedVT.getSizeInBits();
36690 if ((RegSize % ReducedSizeInBits) != 0)
36691 return SDValue();
36692
36693 SmallVector<SDValue, 16> Ops(RegSize / ReducedSizeInBits,
36694 DAG.getUNDEF(ReducedVT));
36695 Ops[0] = NewN0;
36696 NewN0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, OpsVT, Ops);
36697 Ops[0] = NewN1;
36698 NewN1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, OpsVT, Ops);
36699
36700 if (Mode == MULU8 || Mode == MULS8) {
36701 // Generate lower part of mul: pmullw. For MULU8/MULS8, only the lower
36702 // part is needed.
36703 SDValue Mul = DAG.getNode(ISD::MUL, DL, OpsVT, NewN0, NewN1);
36704
36705 // convert the type of mul result to VT.
36706 MVT ResVT = MVT::getVectorVT(MVT::i32, RegSize / 32);
36707 SDValue Res = DAG.getNode(Mode == MULU8 ? ISD::ZERO_EXTEND_VECTOR_INREG
36708 : ISD::SIGN_EXTEND_VECTOR_INREG,
36709 DL, ResVT, Mul);
36710 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
36711 DAG.getIntPtrConstant(0, DL));
36712 }
36713
36714 // Generate the lower and higher part of mul: pmulhw/pmulhuw. For
36715 // MULU16/MULS16, both parts are needed.
36716 SDValue MulLo = DAG.getNode(ISD::MUL, DL, OpsVT, NewN0, NewN1);
36717 SDValue MulHi = DAG.getNode(Mode == MULS16 ? ISD::MULHS : ISD::MULHU, DL,
36718 OpsVT, NewN0, NewN1);
36719
36720 // Repack the lower part and higher part result of mul into a wider
36721 // result. Make sure the type of mul result is VT.
36722 MVT ResVT = MVT::getVectorVT(MVT::i32, RegSize / 32);
36723 SDValue Res = getUnpackl(DAG, DL, OpsVT, MulLo, MulHi);
36724 Res = DAG.getBitcast(ResVT, Res);
36725 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Res,
36726 DAG.getIntPtrConstant(0, DL));
36727}
36728
36729static SDValue combineMulSpecial(uint64_t MulAmt, SDNode *N, SelectionDAG &DAG,
36730 EVT VT, const SDLoc &DL) {
36731
36732 auto combineMulShlAddOrSub = [&](int Mult, int Shift, bool isAdd) {
36733 SDValue Result = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
36734 DAG.getConstant(Mult, DL, VT));
36735 Result = DAG.getNode(ISD::SHL, DL, VT, Result,
36736 DAG.getConstant(Shift, DL, MVT::i8));
36737 Result = DAG.getNode(isAdd ? ISD::ADD : ISD::SUB, DL, VT, Result,
36738 N->getOperand(0));
36739 return Result;
36740 };
36741
36742 auto combineMulMulAddOrSub = [&](int Mul1, int Mul2, bool isAdd) {
36743 SDValue Result = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
36744 DAG.getConstant(Mul1, DL, VT));
36745 Result = DAG.getNode(X86ISD::MUL_IMM, DL, VT, Result,
36746 DAG.getConstant(Mul2, DL, VT));
36747 Result = DAG.getNode(isAdd ? ISD::ADD : ISD::SUB, DL, VT, Result,
36748 N->getOperand(0));
36749 return Result;
36750 };
36751
36752 switch (MulAmt) {
36753 default:
36754 break;
36755 case 11:
36756 // mul x, 11 => add ((shl (mul x, 5), 1), x)
36757 return combineMulShlAddOrSub(5, 1, /*isAdd*/ true);
36758 case 21:
36759 // mul x, 21 => add ((shl (mul x, 5), 2), x)
36760 return combineMulShlAddOrSub(5, 2, /*isAdd*/ true);
36761 case 41:
36762 // mul x, 41 => add ((shl (mul x, 5), 3), x)
36763 return combineMulShlAddOrSub(5, 3, /*isAdd*/ true);
36764 case 22:
36765 // mul x, 22 => add (add ((shl (mul x, 5), 2), x), x)
36766 return DAG.getNode(ISD::ADD, DL, VT, N->getOperand(0),
36767 combineMulShlAddOrSub(5, 2, /*isAdd*/ true));
36768 case 19:
36769 // mul x, 19 => add ((shl (mul x, 9), 1), x)
36770 return combineMulShlAddOrSub(9, 1, /*isAdd*/ true);
36771 case 37:
36772 // mul x, 37 => add ((shl (mul x, 9), 2), x)
36773 return combineMulShlAddOrSub(9, 2, /*isAdd*/ true);
36774 case 73:
36775 // mul x, 73 => add ((shl (mul x, 9), 3), x)
36776 return combineMulShlAddOrSub(9, 3, /*isAdd*/ true);
36777 case 13:
36778 // mul x, 13 => add ((shl (mul x, 3), 2), x)
36779 return combineMulShlAddOrSub(3, 2, /*isAdd*/ true);
36780 case 23:
36781 // mul x, 23 => sub ((shl (mul x, 3), 3), x)
36782 return combineMulShlAddOrSub(3, 3, /*isAdd*/ false);
36783 case 26:
36784 // mul x, 26 => add ((mul (mul x, 5), 5), x)
36785 return combineMulMulAddOrSub(5, 5, /*isAdd*/ true);
36786 case 28:
36787 // mul x, 28 => add ((mul (mul x, 9), 3), x)
36788 return combineMulMulAddOrSub(9, 3, /*isAdd*/ true);
36789 case 29:
36790 // mul x, 29 => add (add ((mul (mul x, 9), 3), x), x)
36791 return DAG.getNode(ISD::ADD, DL, VT, N->getOperand(0),
36792 combineMulMulAddOrSub(9, 3, /*isAdd*/ true));
36793 }
36794
36795 // Another trick. If this is a power 2 + 2/4/8, we can use a shift followed
36796 // by a single LEA.
36797 // First check if this a sum of two power of 2s because that's easy. Then
36798 // count how many zeros are up to the first bit.
36799 // TODO: We can do this even without LEA at a cost of two shifts and an add.
36800 if (isPowerOf2_64(MulAmt & (MulAmt - 1))) {
36801 unsigned ScaleShift = countTrailingZeros(MulAmt);
36802 if (ScaleShift >= 1 && ScaleShift < 4) {
36803 unsigned ShiftAmt = Log2_64((MulAmt & (MulAmt - 1)));
36804 SDValue Shift1 = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
36805 DAG.getConstant(ShiftAmt, DL, MVT::i8));
36806 SDValue Shift2 = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
36807 DAG.getConstant(ScaleShift, DL, MVT::i8));
36808 return DAG.getNode(ISD::ADD, DL, VT, Shift1, Shift2);
36809 }
36810 }
36811
36812 return SDValue();
36813}
36814
36815// If the upper 17 bits of each element are zero then we can use PMADDWD,
36816// which is always at least as quick as PMULLD, except on KNL.
36817static SDValue combineMulToPMADDWD(SDNode *N, SelectionDAG &DAG,
36818 const X86Subtarget &Subtarget) {
36819 if (!Subtarget.hasSSE2())
36820 return SDValue();
36821
36822 if (Subtarget.isPMADDWDSlow())
36823 return SDValue();
36824
36825 EVT VT = N->getValueType(0);
36826
36827 // Only support vXi32 vectors.
36828 if (!VT.isVector() || VT.getVectorElementType() != MVT::i32)
36829 return SDValue();
36830
36831 // Make sure the vXi16 type is legal. This covers the AVX512 without BWI case.
36832 // Also allow v2i32 if it will be widened.
36833 MVT WVT = MVT::getVectorVT(MVT::i16, 2 * VT.getVectorNumElements());
36834 if (!((ExperimentalVectorWideningLegalization && VT == MVT::v2i32) ||
36835 DAG.getTargetLoweringInfo().isTypeLegal(WVT)))
36836 return SDValue();
36837
36838 SDValue N0 = N->getOperand(0);
36839 SDValue N1 = N->getOperand(1);
36840
36841 // If we are zero extending two steps without SSE4.1, its better to reduce
36842 // the vmul width instead.
36843 if (!Subtarget.hasSSE41() &&
36844 (N0.getOpcode() == ISD::ZERO_EXTEND &&
36845 N0.getOperand(0).getScalarValueSizeInBits() <= 8) &&
36846 (N1.getOpcode() == ISD::ZERO_EXTEND &&
36847 N1.getOperand(0).getScalarValueSizeInBits() <= 8))
36848 return SDValue();
36849
36850 APInt Mask17 = APInt::getHighBitsSet(32, 17);
36851 if (!DAG.MaskedValueIsZero(N1, Mask17) ||
36852 !DAG.MaskedValueIsZero(N0, Mask17))
36853 return SDValue();
36854
36855 // Use SplitOpsAndApply to handle AVX splitting.
36856 auto PMADDWDBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
36857 ArrayRef<SDValue> Ops) {
36858 MVT OpVT = MVT::getVectorVT(MVT::i32, Ops[0].getValueSizeInBits() / 32);
36859 return DAG.getNode(X86ISD::VPMADDWD, DL, OpVT, Ops);
36860 };
36861 return SplitOpsAndApply(DAG, Subtarget, SDLoc(N), VT,
36862 { DAG.getBitcast(WVT, N0), DAG.getBitcast(WVT, N1) },
36863 PMADDWDBuilder);
36864}
36865
36866static SDValue combineMulToPMULDQ(SDNode *N, SelectionDAG &DAG,
36867 const X86Subtarget &Subtarget) {
36868 if (!Subtarget.hasSSE2())
36869 return SDValue();
36870
36871 EVT VT = N->getValueType(0);
36872
36873 // Only support vXi64 vectors.
36874 if (!VT.isVector() || VT.getVectorElementType() != MVT::i64 ||
36875 VT.getVectorNumElements() < 2 ||
36876 !isPowerOf2_32(VT.getVectorNumElements()))
36877 return SDValue();
36878
36879 SDValue N0 = N->getOperand(0);
36880 SDValue N1 = N->getOperand(1);
36881
36882 // MULDQ returns the 64-bit result of the signed multiplication of the lower
36883 // 32-bits. We can lower with this if the sign bits stretch that far.
36884 if (Subtarget.hasSSE41() && DAG.ComputeNumSignBits(N0) > 32 &&
36885 DAG.ComputeNumSignBits(N1) > 32) {
36886 auto PMULDQBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
36887 ArrayRef<SDValue> Ops) {
36888 return DAG.getNode(X86ISD::PMULDQ, DL, Ops[0].getValueType(), Ops);
36889 };
36890 return SplitOpsAndApply(DAG, Subtarget, SDLoc(N), VT, { N0, N1 },
36891 PMULDQBuilder, /*CheckBWI*/false);
36892 }
36893
36894 // If the upper bits are zero we can use a single pmuludq.
36895 APInt Mask = APInt::getHighBitsSet(64, 32);
36896 if (DAG.MaskedValueIsZero(N0, Mask) && DAG.MaskedValueIsZero(N1, Mask)) {
36897 auto PMULUDQBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
36898 ArrayRef<SDValue> Ops) {
36899 return DAG.getNode(X86ISD::PMULUDQ, DL, Ops[0].getValueType(), Ops);
36900 };
36901 return SplitOpsAndApply(DAG, Subtarget, SDLoc(N), VT, { N0, N1 },
36902 PMULUDQBuilder, /*CheckBWI*/false);
36903 }
36904
36905 return SDValue();
36906}
36907
36908/// Optimize a single multiply with constant into two operations in order to
36909/// implement it with two cheaper instructions, e.g. LEA + SHL, LEA + LEA.
36910static SDValue combineMul(SDNode *N, SelectionDAG &DAG,
36911 TargetLowering::DAGCombinerInfo &DCI,
36912 const X86Subtarget &Subtarget) {
36913 EVT VT = N->getValueType(0);
36914
36915 if (SDValue V = combineMulToPMADDWD(N, DAG, Subtarget))
36916 return V;
36917
36918 if (SDValue V = combineMulToPMULDQ(N, DAG, Subtarget))
36919 return V;
36920
36921 if (DCI.isBeforeLegalize() && VT.isVector())
36922 return reduceVMULWidth(N, DAG, Subtarget);
36923
36924 if (!MulConstantOptimization)
36925 return SDValue();
36926 // An imul is usually smaller than the alternative sequence.
36927 if (DAG.getMachineFunction().getFunction().hasMinSize())
36928 return SDValue();
36929
36930 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
36931 return SDValue();
36932
36933 if (VT != MVT::i64 && VT != MVT::i32)
36934 return SDValue();
36935
36936 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
36937 if (!C)
36938 return SDValue();
36939 if (isPowerOf2_64(C->getZExtValue()))
36940 return SDValue();
36941
36942 int64_t SignMulAmt = C->getSExtValue();
36943 assert(SignMulAmt != INT64_MIN && "Int min should have been handled!")((SignMulAmt != (-9223372036854775807L -1) && "Int min should have been handled!"
) ? static_cast<void> (0) : __assert_fail ("SignMulAmt != INT64_MIN && \"Int min should have been handled!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 36943, __PRETTY_FUNCTION__))
;
36944 uint64_t AbsMulAmt = SignMulAmt < 0 ? -SignMulAmt : SignMulAmt;
36945
36946 SDLoc DL(N);
36947 if (AbsMulAmt == 3 || AbsMulAmt == 5 || AbsMulAmt == 9) {
36948 SDValue NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
36949 DAG.getConstant(AbsMulAmt, DL, VT));
36950 if (SignMulAmt < 0)
36951 NewMul = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
36952 NewMul);
36953
36954 return NewMul;
36955 }
36956
36957 uint64_t MulAmt1 = 0;
36958 uint64_t MulAmt2 = 0;
36959 if ((AbsMulAmt % 9) == 0) {
36960 MulAmt1 = 9;
36961 MulAmt2 = AbsMulAmt / 9;
36962 } else if ((AbsMulAmt % 5) == 0) {
36963 MulAmt1 = 5;
36964 MulAmt2 = AbsMulAmt / 5;
36965 } else if ((AbsMulAmt % 3) == 0) {
36966 MulAmt1 = 3;
36967 MulAmt2 = AbsMulAmt / 3;
36968 }
36969
36970 SDValue NewMul;
36971 // For negative multiply amounts, only allow MulAmt2 to be a power of 2.
36972 if (MulAmt2 &&
36973 (isPowerOf2_64(MulAmt2) ||
36974 (SignMulAmt >= 0 && (MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)))) {
36975
36976 if (isPowerOf2_64(MulAmt2) &&
36977 !(SignMulAmt >= 0 && N->hasOneUse() &&
36978 N->use_begin()->getOpcode() == ISD::ADD))
36979 // If second multiplifer is pow2, issue it first. We want the multiply by
36980 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
36981 // is an add. Only do this for positive multiply amounts since the
36982 // negate would prevent it from being used as an address mode anyway.
36983 std::swap(MulAmt1, MulAmt2);
36984
36985 if (isPowerOf2_64(MulAmt1))
36986 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
36987 DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
36988 else
36989 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
36990 DAG.getConstant(MulAmt1, DL, VT));
36991
36992 if (isPowerOf2_64(MulAmt2))
36993 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
36994 DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
36995 else
36996 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
36997 DAG.getConstant(MulAmt2, DL, VT));
36998
36999 // Negate the result.
37000 if (SignMulAmt < 0)
37001 NewMul = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
37002 NewMul);
37003 } else if (!Subtarget.slowLEA())
37004 NewMul = combineMulSpecial(C->getZExtValue(), N, DAG, VT, DL);
37005
37006 if (!NewMul) {
37007 assert(C->getZExtValue() != 0 &&((C->getZExtValue() != 0 && C->getZExtValue() !=
(VT == MVT::i64 ? (18446744073709551615UL) : (4294967295U)) &&
"Both cases that could cause potential overflows should have "
"already been handled.") ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 37010, __PRETTY_FUNCTION__))
37008 C->getZExtValue() != (VT == MVT::i64 ? UINT64_MAX : UINT32_MAX) &&((C->getZExtValue() != 0 && C->getZExtValue() !=
(VT == MVT::i64 ? (18446744073709551615UL) : (4294967295U)) &&
"Both cases that could cause potential overflows should have "
"already been handled.") ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 37010, __PRETTY_FUNCTION__))
37009 "Both cases that could cause potential overflows should have "((C->getZExtValue() != 0 && C->getZExtValue() !=
(VT == MVT::i64 ? (18446744073709551615UL) : (4294967295U)) &&
"Both cases that could cause potential overflows should have "
"already been handled.") ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 37010, __PRETTY_FUNCTION__))
37010 "already been handled.")((C->getZExtValue() != 0 && C->getZExtValue() !=
(VT == MVT::i64 ? (18446744073709551615UL) : (4294967295U)) &&
"Both cases that could cause potential overflows should have "
"already been handled.") ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 37010, __PRETTY_FUNCTION__))
;
37011 if (isPowerOf2_64(AbsMulAmt - 1)) {
37012 // (mul x, 2^N + 1) => (add (shl x, N), x)
37013 NewMul = DAG.getNode(
37014 ISD::ADD, DL, VT, N->getOperand(0),
37015 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
37016 DAG.getConstant(Log2_64(AbsMulAmt - 1), DL,
37017 MVT::i8)));
37018 // To negate, subtract the number from zero
37019 if (SignMulAmt < 0)
37020 NewMul = DAG.getNode(ISD::SUB, DL, VT,
37021 DAG.getConstant(0, DL, VT), NewMul);
37022 } else if (isPowerOf2_64(AbsMulAmt + 1)) {
37023 // (mul x, 2^N - 1) => (sub (shl x, N), x)
37024 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
37025 DAG.getConstant(Log2_64(AbsMulAmt + 1),
37026 DL, MVT::i8));
37027 // To negate, reverse the operands of the subtract.
37028 if (SignMulAmt < 0)
37029 NewMul = DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), NewMul);
37030 else
37031 NewMul = DAG.getNode(ISD::SUB, DL, VT, NewMul, N->getOperand(0));
37032 } else if (SignMulAmt >= 0 && isPowerOf2_64(AbsMulAmt - 2)) {
37033 // (mul x, 2^N + 2) => (add (add (shl x, N), x), x)
37034 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
37035 DAG.getConstant(Log2_64(AbsMulAmt - 2),
37036 DL, MVT::i8));
37037 NewMul = DAG.getNode(ISD::ADD, DL, VT, NewMul, N->getOperand(0));
37038 NewMul = DAG.getNode(ISD::ADD, DL, VT, NewMul, N->getOperand(0));
37039 } else if (SignMulAmt >= 0 && isPowerOf2_64(AbsMulAmt + 2)) {
37040 // (mul x, 2^N - 2) => (sub (sub (shl x, N), x), x)
37041 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
37042 DAG.getConstant(Log2_64(AbsMulAmt + 2),
37043 DL, MVT::i8));
37044 NewMul = DAG.getNode(ISD::SUB, DL, VT, NewMul, N->getOperand(0));
37045 NewMul = DAG.getNode(ISD::SUB, DL, VT, NewMul, N->getOperand(0));
37046 }
37047 }
37048
37049 return NewMul;
37050}
37051
37052static SDValue combineShiftLeft(SDNode *N, SelectionDAG &DAG) {
37053 SDValue N0 = N->getOperand(0);
37054 SDValue N1 = N->getOperand(1);
37055 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
37056 EVT VT = N0.getValueType();
37057
37058 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
37059 // since the result of setcc_c is all zero's or all ones.
37060 if (VT.isInteger() && !VT.isVector() &&
37061 N1C && N0.getOpcode() == ISD::AND &&
37062 N0.getOperand(1).getOpcode() == ISD::Constant) {
37063 SDValue N00 = N0.getOperand(0);
37064 APInt Mask = N0.getConstantOperandAPInt(1);
37065 Mask <<= N1C->getAPIntValue();
37066 bool MaskOK = false;
37067 // We can handle cases concerning bit-widening nodes containing setcc_c if
37068 // we carefully interrogate the mask to make sure we are semantics
37069 // preserving.
37070 // The transform is not safe if the result of C1 << C2 exceeds the bitwidth
37071 // of the underlying setcc_c operation if the setcc_c was zero extended.
37072 // Consider the following example:
37073 // zext(setcc_c) -> i32 0x0000FFFF
37074 // c1 -> i32 0x0000FFFF
37075 // c2 -> i32 0x00000001
37076 // (shl (and (setcc_c), c1), c2) -> i32 0x0001FFFE
37077 // (and setcc_c, (c1 << c2)) -> i32 0x0000FFFE
37078 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
37079 MaskOK = true;
37080 } else if (N00.getOpcode() == ISD::SIGN_EXTEND &&
37081 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
37082 MaskOK = true;
37083 } else if ((N00.getOpcode() == ISD::ZERO_EXTEND ||
37084 N00.getOpcode() == ISD::ANY_EXTEND) &&
37085 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
37086 MaskOK = Mask.isIntN(N00.getOperand(0).getValueSizeInBits());
37087 }
37088 if (MaskOK && Mask != 0) {
37089 SDLoc DL(N);
37090 return DAG.getNode(ISD::AND, DL, VT, N00, DAG.getConstant(Mask, DL, VT));
37091 }
37092 }
37093
37094 // Hardware support for vector shifts is sparse which makes us scalarize the
37095 // vector operations in many cases. Also, on sandybridge ADD is faster than
37096 // shl.
37097 // (shl V, 1) -> add V,V
37098 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
37099 if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
37100 assert(N0.getValueType().isVector() && "Invalid vector shift type")((N0.getValueType().isVector() && "Invalid vector shift type"
) ? static_cast<void> (0) : __assert_fail ("N0.getValueType().isVector() && \"Invalid vector shift type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 37100, __PRETTY_FUNCTION__))
;
37101 // We shift all of the values by one. In many cases we do not have
37102 // hardware support for this operation. This is better expressed as an ADD
37103 // of two values.
37104 if (N1SplatC->getAPIntValue() == 1)
37105 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
37106 }
37107
37108 return SDValue();
37109}
37110
37111static SDValue combineShiftRightArithmetic(SDNode *N, SelectionDAG &DAG) {
37112 SDValue N0 = N->getOperand(0);
37113 SDValue N1 = N->getOperand(1);
37114 EVT VT = N0.getValueType();
37115 unsigned Size = VT.getSizeInBits();
37116
37117 // fold (ashr (shl, a, [56,48,32,24,16]), SarConst)
37118 // into (shl, (sext (a), [56,48,32,24,16] - SarConst)) or
37119 // into (lshr, (sext (a), SarConst - [56,48,32,24,16]))
37120 // depending on sign of (SarConst - [56,48,32,24,16])
37121
37122 // sexts in X86 are MOVs. The MOVs have the same code size
37123 // as above SHIFTs (only SHIFT on 1 has lower code size).
37124 // However the MOVs have 2 advantages to a SHIFT:
37125 // 1. MOVs can write to a register that differs from source
37126 // 2. MOVs accept memory operands
37127
37128 if (VT.isVector() || N1.getOpcode() != ISD::Constant ||
37129 N0.getOpcode() != ISD::SHL || !N0.hasOneUse() ||
37130 N0.getOperand(1).getOpcode() != ISD::Constant)
37131 return SDValue();
37132
37133 SDValue N00 = N0.getOperand(0);
37134 SDValue N01 = N0.getOperand(1);
37135 APInt ShlConst = (cast<ConstantSDNode>(N01))->getAPIntValue();
37136 APInt SarConst = (cast<ConstantSDNode>(N1))->getAPIntValue();
37137 EVT CVT = N1.getValueType();
37138
37139 if (SarConst.isNegative())
37140 return SDValue();
37141
37142 for (MVT SVT : { MVT::i8, MVT::i16, MVT::i32 }) {
37143 unsigned ShiftSize = SVT.getSizeInBits();
37144 // skipping types without corresponding sext/zext and
37145 // ShlConst that is not one of [56,48,32,24,16]
37146 if (ShiftSize >= Size || ShlConst != Size - ShiftSize)
37147 continue;
37148 SDLoc DL(N);
37149 SDValue NN =
37150 DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, N00, DAG.getValueType(SVT));
37151 SarConst = SarConst - (Size - ShiftSize);
37152 if (SarConst == 0)
37153 return NN;
37154 else if (SarConst.isNegative())
37155 return DAG.getNode(ISD::SHL, DL, VT, NN,
37156 DAG.getConstant(-SarConst, DL, CVT));
37157 else
37158 return DAG.getNode(ISD::SRA, DL, VT, NN,
37159 DAG.getConstant(SarConst, DL, CVT));
37160 }
37161 return SDValue();
37162}
37163
37164static SDValue combineShiftRightLogical(SDNode *N, SelectionDAG &DAG,
37165 TargetLowering::DAGCombinerInfo &DCI) {
37166 SDValue N0 = N->getOperand(0);
37167 SDValue N1 = N->getOperand(1);
37168 EVT VT = N0.getValueType();
37169
37170 // Only do this on the last DAG combine as it can interfere with other
37171 // combines.
37172 if (!DCI.isAfterLegalizeDAG())
37173 return SDValue();
37174
37175 // Try to improve a sequence of srl (and X, C1), C2 by inverting the order.
37176 // TODO: This is a generic DAG combine that became an x86-only combine to
37177 // avoid shortcomings in other folds such as bswap, bit-test ('bt'), and
37178 // and-not ('andn').
37179 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
37180 return SDValue();
37181
37182 auto *ShiftC = dyn_cast<ConstantSDNode>(N1);
37183 auto *AndC = dyn_cast<ConstantSDNode>(N0.getOperand(1));
37184 if (!ShiftC || !AndC)
37185 return SDValue();
37186
37187 // If we can shrink the constant mask below 8-bits or 32-bits, then this
37188 // transform should reduce code size. It may also enable secondary transforms
37189 // from improved known-bits analysis or instruction selection.
37190 APInt MaskVal = AndC->getAPIntValue();
37191
37192 // If this can be matched by a zero extend, don't optimize.
37193 if (MaskVal.isMask()) {
37194 unsigned TO = MaskVal.countTrailingOnes();
37195 if (TO >= 8 && isPowerOf2_32(TO))
37196 return SDValue();
37197 }
37198
37199 APInt NewMaskVal = MaskVal.lshr(ShiftC->getAPIntValue());
37200 unsigned OldMaskSize = MaskVal.getMinSignedBits();
37201 unsigned NewMaskSize = NewMaskVal.getMinSignedBits();
37202 if ((OldMaskSize > 8 && NewMaskSize <= 8) ||
37203 (OldMaskSize > 32 && NewMaskSize <= 32)) {
37204 // srl (and X, AndC), ShiftC --> and (srl X, ShiftC), (AndC >> ShiftC)
37205 SDLoc DL(N);
37206 SDValue NewMask = DAG.getConstant(NewMaskVal, DL, VT);
37207 SDValue NewShift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), N1);
37208 return DAG.getNode(ISD::AND, DL, VT, NewShift, NewMask);
37209 }
37210 return SDValue();
37211}
37212
37213static SDValue combineVectorPack(SDNode *N, SelectionDAG &DAG,
37214 TargetLowering::DAGCombinerInfo &DCI,
37215 const X86Subtarget &Subtarget) {
37216 unsigned Opcode = N->getOpcode();
37217 assert((X86ISD::PACKSS == Opcode || X86ISD::PACKUS == Opcode) &&(((X86ISD::PACKSS == Opcode || X86ISD::PACKUS == Opcode) &&
"Unexpected shift opcode") ? static_cast<void> (0) : __assert_fail
("(X86ISD::PACKSS == Opcode || X86ISD::PACKUS == Opcode) && \"Unexpected shift opcode\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 37218, __PRETTY_FUNCTION__))
37218 "Unexpected shift opcode")(((X86ISD::PACKSS == Opcode || X86ISD::PACKUS == Opcode) &&
"Unexpected shift opcode") ? static_cast<void> (0) : __assert_fail
("(X86ISD::PACKSS == Opcode || X86ISD::PACKUS == Opcode) && \"Unexpected shift opcode\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 37218, __PRETTY_FUNCTION__))
;
37219
37220 EVT VT = N->getValueType(0);
37221 SDValue N0 = N->getOperand(0);
37222 SDValue N1 = N->getOperand(1);
37223 unsigned DstBitsPerElt = VT.getScalarSizeInBits();
37224 unsigned SrcBitsPerElt = 2 * DstBitsPerElt;
37225 assert(N0.getScalarValueSizeInBits() == SrcBitsPerElt &&((N0.getScalarValueSizeInBits() == SrcBitsPerElt && N1
.getScalarValueSizeInBits() == SrcBitsPerElt && "Unexpected PACKSS/PACKUS input type"
) ? static_cast<void> (0) : __assert_fail ("N0.getScalarValueSizeInBits() == SrcBitsPerElt && N1.getScalarValueSizeInBits() == SrcBitsPerElt && \"Unexpected PACKSS/PACKUS input type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 37227, __PRETTY_FUNCTION__))
37226 N1.getScalarValueSizeInBits() == SrcBitsPerElt &&((N0.getScalarValueSizeInBits() == SrcBitsPerElt && N1
.getScalarValueSizeInBits() == SrcBitsPerElt && "Unexpected PACKSS/PACKUS input type"
) ? static_cast<void> (0) : __assert_fail ("N0.getScalarValueSizeInBits() == SrcBitsPerElt && N1.getScalarValueSizeInBits() == SrcBitsPerElt && \"Unexpected PACKSS/PACKUS input type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 37227, __PRETTY_FUNCTION__))
37227 "Unexpected PACKSS/PACKUS input type")((N0.getScalarValueSizeInBits() == SrcBitsPerElt && N1
.getScalarValueSizeInBits() == SrcBitsPerElt && "Unexpected PACKSS/PACKUS input type"
) ? static_cast<void> (0) : __assert_fail ("N0.getScalarValueSizeInBits() == SrcBitsPerElt && N1.getScalarValueSizeInBits() == SrcBitsPerElt && \"Unexpected PACKSS/PACKUS input type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 37227, __PRETTY_FUNCTION__))
;
37228
37229 bool IsSigned = (X86ISD::PACKSS == Opcode);
37230
37231 // Constant Folding.
37232 APInt UndefElts0, UndefElts1;
37233 SmallVector<APInt, 32> EltBits0, EltBits1;
37234 if ((N0.isUndef() || N->isOnlyUserOf(N0.getNode())) &&
37235 (N1.isUndef() || N->isOnlyUserOf(N1.getNode())) &&
37236 getTargetConstantBitsFromNode(N0, SrcBitsPerElt, UndefElts0, EltBits0) &&
37237 getTargetConstantBitsFromNode(N1, SrcBitsPerElt, UndefElts1, EltBits1)) {
37238 unsigned NumLanes = VT.getSizeInBits() / 128;
37239 unsigned NumDstElts = VT.getVectorNumElements();
37240 unsigned NumSrcElts = NumDstElts / 2;
37241 unsigned NumDstEltsPerLane = NumDstElts / NumLanes;
37242 unsigned NumSrcEltsPerLane = NumSrcElts / NumLanes;
37243
37244 APInt Undefs(NumDstElts, 0);
37245 SmallVector<APInt, 32> Bits(NumDstElts, APInt::getNullValue(DstBitsPerElt));
37246 for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
37247 for (unsigned Elt = 0; Elt != NumDstEltsPerLane; ++Elt) {
37248 unsigned SrcIdx = Lane * NumSrcEltsPerLane + Elt % NumSrcEltsPerLane;
37249 auto &UndefElts = (Elt >= NumSrcEltsPerLane ? UndefElts1 : UndefElts0);
37250 auto &EltBits = (Elt >= NumSrcEltsPerLane ? EltBits1 : EltBits0);
37251
37252 if (UndefElts[SrcIdx]) {
37253 Undefs.setBit(Lane * NumDstEltsPerLane + Elt);
37254 continue;
37255 }
37256
37257 APInt &Val = EltBits[SrcIdx];
37258 if (IsSigned) {
37259 // PACKSS: Truncate signed value with signed saturation.
37260 // Source values less than dst minint are saturated to minint.
37261 // Source values greater than dst maxint are saturated to maxint.
37262 if (Val.isSignedIntN(DstBitsPerElt))
37263 Val = Val.trunc(DstBitsPerElt);
37264 else if (Val.isNegative())
37265 Val = APInt::getSignedMinValue(DstBitsPerElt);
37266 else
37267 Val = APInt::getSignedMaxValue(DstBitsPerElt);
37268 } else {
37269 // PACKUS: Truncate signed value with unsigned saturation.
37270 // Source values less than zero are saturated to zero.
37271 // Source values greater than dst maxuint are saturated to maxuint.
37272 if (Val.isIntN(DstBitsPerElt))
37273 Val = Val.trunc(DstBitsPerElt);
37274 else if (Val.isNegative())
37275 Val = APInt::getNullValue(DstBitsPerElt);
37276 else
37277 Val = APInt::getAllOnesValue(DstBitsPerElt);
37278 }
37279 Bits[Lane * NumDstEltsPerLane + Elt] = Val;
37280 }
37281 }
37282
37283 return getConstVector(Bits, Undefs, VT.getSimpleVT(), DAG, SDLoc(N));
37284 }
37285
37286 // Try to combine a PACKUSWB/PACKSSWB implemented truncate with a regular
37287 // truncate to create a larger truncate.
37288 if (Subtarget.hasAVX512() &&
37289 N0.getOpcode() == ISD::TRUNCATE && N1.isUndef() && VT == MVT::v16i8 &&
37290 N0.getOperand(0).getValueType() == MVT::v8i32) {
37291 if ((IsSigned && DAG.ComputeNumSignBits(N0) > 8) ||
37292 (!IsSigned &&
37293 DAG.MaskedValueIsZero(N0, APInt::getHighBitsSet(16, 8)))) {
37294 if (Subtarget.hasVLX())
37295 return DAG.getNode(X86ISD::VTRUNC, SDLoc(N), VT, N0.getOperand(0));
37296
37297 // Widen input to v16i32 so we can truncate that.
37298 SDLoc dl(N);
37299 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v16i32,
37300 N0.getOperand(0), DAG.getUNDEF(MVT::v8i32));
37301 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Concat);
37302 }
37303 }
37304
37305 // Attempt to combine as shuffle.
37306 SDValue Op(N, 0);
37307 if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
37308 return Res;
37309
37310 return SDValue();
37311}
37312
37313static SDValue combineVectorShiftVar(SDNode *N, SelectionDAG &DAG,
37314 TargetLowering::DAGCombinerInfo &DCI,
37315 const X86Subtarget &Subtarget) {
37316 assert((X86ISD::VSHL == N->getOpcode() || X86ISD::VSRA == N->getOpcode() ||(((X86ISD::VSHL == N->getOpcode() || X86ISD::VSRA == N->
getOpcode() || X86ISD::VSRL == N->getOpcode()) && "Unexpected shift opcode"
) ? static_cast<void> (0) : __assert_fail ("(X86ISD::VSHL == N->getOpcode() || X86ISD::VSRA == N->getOpcode() || X86ISD::VSRL == N->getOpcode()) && \"Unexpected shift opcode\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 37318, __PRETTY_FUNCTION__))
37317 X86ISD::VSRL == N->getOpcode()) &&(((X86ISD::VSHL == N->getOpcode() || X86ISD::VSRA == N->
getOpcode() || X86ISD::VSRL == N->getOpcode()) && "Unexpected shift opcode"
) ? static_cast<void> (0) : __assert_fail ("(X86ISD::VSHL == N->getOpcode() || X86ISD::VSRA == N->getOpcode() || X86ISD::VSRL == N->getOpcode()) && \"Unexpected shift opcode\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 37318, __PRETTY_FUNCTION__))
37318 "Unexpected shift opcode")(((X86ISD::VSHL == N->getOpcode() || X86ISD::VSRA == N->
getOpcode() || X86ISD::VSRL == N->getOpcode()) && "Unexpected shift opcode"
) ? static_cast<void> (0) : __assert_fail ("(X86ISD::VSHL == N->getOpcode() || X86ISD::VSRA == N->getOpcode() || X86ISD::VSRL == N->getOpcode()) && \"Unexpected shift opcode\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 37318, __PRETTY_FUNCTION__))
;
37319 EVT VT = N->getValueType(0);
37320 SDValue N0 = N->getOperand(0);
37321 SDValue N1 = N->getOperand(1);
37322
37323 // Shift zero -> zero.
37324 if (ISD::isBuildVectorAllZeros(N0.getNode()))
37325 return DAG.getConstant(0, SDLoc(N), VT);
37326
37327 // Detect constant shift amounts.
37328 APInt UndefElts;
37329 SmallVector<APInt, 32> EltBits;
37330 if (getTargetConstantBitsFromNode(N1, 64, UndefElts, EltBits, true, false)) {
37331 unsigned X86Opc = getTargetVShiftUniformOpcode(N->getOpcode(), false);
37332 return getTargetVShiftByConstNode(X86Opc, SDLoc(N), VT.getSimpleVT(), N0,
37333 EltBits[0].getZExtValue(), DAG);
37334 }
37335
37336 APInt KnownUndef, KnownZero;
37337 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
37338 APInt DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements());
37339 if (TLI.SimplifyDemandedVectorElts(SDValue(N, 0), DemandedElts, KnownUndef,
37340 KnownZero, DCI))
37341 return SDValue(N, 0);
37342
37343 return SDValue();
37344}
37345
37346static SDValue combineVectorShiftImm(SDNode *N, SelectionDAG &DAG,
37347 TargetLowering::DAGCombinerInfo &DCI,
37348 const X86Subtarget &Subtarget) {
37349 unsigned Opcode = N->getOpcode();
37350 assert((X86ISD::VSHLI == Opcode || X86ISD::VSRAI == Opcode ||(((X86ISD::VSHLI == Opcode || X86ISD::VSRAI == Opcode || X86ISD
::VSRLI == Opcode) && "Unexpected shift opcode") ? static_cast
<void> (0) : __assert_fail ("(X86ISD::VSHLI == Opcode || X86ISD::VSRAI == Opcode || X86ISD::VSRLI == Opcode) && \"Unexpected shift opcode\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 37352, __PRETTY_FUNCTION__))
37351 X86ISD::VSRLI == Opcode) &&(((X86ISD::VSHLI == Opcode || X86ISD::VSRAI == Opcode || X86ISD
::VSRLI == Opcode) && "Unexpected shift opcode") ? static_cast
<void> (0) : __assert_fail ("(X86ISD::VSHLI == Opcode || X86ISD::VSRAI == Opcode || X86ISD::VSRLI == Opcode) && \"Unexpected shift opcode\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 37352, __PRETTY_FUNCTION__))
37352 "Unexpected shift opcode")(((X86ISD::VSHLI == Opcode || X86ISD::VSRAI == Opcode || X86ISD
::VSRLI == Opcode) && "Unexpected shift opcode") ? static_cast
<void> (0) : __assert_fail ("(X86ISD::VSHLI == Opcode || X86ISD::VSRAI == Opcode || X86ISD::VSRLI == Opcode) && \"Unexpected shift opcode\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 37352, __PRETTY_FUNCTION__))
;
37353 bool LogicalShift = X86ISD::VSHLI == Opcode || X86ISD::VSRLI == Opcode;
37354 EVT VT = N->getValueType(0);
37355 SDValue N0 = N->getOperand(0);
37356 SDValue N1 = N->getOperand(1);
37357 unsigned NumBitsPerElt = VT.getScalarSizeInBits();
37358 assert(VT == N0.getValueType() && (NumBitsPerElt % 8) == 0 &&((VT == N0.getValueType() && (NumBitsPerElt % 8) == 0
&& "Unexpected value type") ? static_cast<void>
(0) : __assert_fail ("VT == N0.getValueType() && (NumBitsPerElt % 8) == 0 && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 37359, __PRETTY_FUNCTION__))
37359 "Unexpected value type")((VT == N0.getValueType() && (NumBitsPerElt % 8) == 0
&& "Unexpected value type") ? static_cast<void>
(0) : __assert_fail ("VT == N0.getValueType() && (NumBitsPerElt % 8) == 0 && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 37359, __PRETTY_FUNCTION__))
;
37360 assert(N1.getValueType() == MVT::i8 && "Unexpected shift amount type")((N1.getValueType() == MVT::i8 && "Unexpected shift amount type"
) ? static_cast<void> (0) : __assert_fail ("N1.getValueType() == MVT::i8 && \"Unexpected shift amount type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 37360, __PRETTY_FUNCTION__))
;
37361
37362 // Out of range logical bit shifts are guaranteed to be zero.
37363 // Out of range arithmetic bit shifts splat the sign bit.
37364 unsigned ShiftVal = cast<ConstantSDNode>(N1)->getZExtValue();
37365 if (ShiftVal >= NumBitsPerElt) {
37366 if (LogicalShift)
37367 return DAG.getConstant(0, SDLoc(N), VT);
37368 else
37369 ShiftVal = NumBitsPerElt - 1;
37370 }
37371
37372 // Shift N0 by zero -> N0.
37373 if (!ShiftVal)
37374 return N0;
37375
37376 // Shift zero -> zero.
37377 if (ISD::isBuildVectorAllZeros(N0.getNode()))
37378 return DAG.getConstant(0, SDLoc(N), VT);
37379
37380 // Fold (VSRAI (VSRAI X, C1), C2) --> (VSRAI X, (C1 + C2)) with (C1 + C2)
37381 // clamped to (NumBitsPerElt - 1).
37382 if (Opcode == X86ISD::VSRAI && N0.getOpcode() == X86ISD::VSRAI) {
37383 unsigned ShiftVal2 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
37384 unsigned NewShiftVal = ShiftVal + ShiftVal2;
37385 if (NewShiftVal >= NumBitsPerElt)
37386 NewShiftVal = NumBitsPerElt - 1;
37387 return DAG.getNode(X86ISD::VSRAI, SDLoc(N), VT, N0.getOperand(0),
37388 DAG.getConstant(NewShiftVal, SDLoc(N), MVT::i8));
37389 }
37390
37391 // We can decode 'whole byte' logical bit shifts as shuffles.
37392 if (LogicalShift && (ShiftVal % 8) == 0) {
37393 SDValue Op(N, 0);
37394 if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
37395 return Res;
37396 }
37397
37398 // Constant Folding.
37399 APInt UndefElts;
37400 SmallVector<APInt, 32> EltBits;
37401 if (N->isOnlyUserOf(N0.getNode()) &&
37402 getTargetConstantBitsFromNode(N0, NumBitsPerElt, UndefElts, EltBits)) {
37403 assert(EltBits.size() == VT.getVectorNumElements() &&((EltBits.size() == VT.getVectorNumElements() && "Unexpected shift value type"
) ? static_cast<void> (0) : __assert_fail ("EltBits.size() == VT.getVectorNumElements() && \"Unexpected shift value type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 37404, __PRETTY_FUNCTION__))
37404 "Unexpected shift value type")((EltBits.size() == VT.getVectorNumElements() && "Unexpected shift value type"
) ? static_cast<void> (0) : __assert_fail ("EltBits.size() == VT.getVectorNumElements() && \"Unexpected shift value type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 37404, __PRETTY_FUNCTION__))
;
37405 for (APInt &Elt : EltBits) {
37406 if (X86ISD::VSHLI == Opcode)
37407 Elt <<= ShiftVal;
37408 else if (X86ISD::VSRAI == Opcode)
37409 Elt.ashrInPlace(ShiftVal);
37410 else
37411 Elt.lshrInPlace(ShiftVal);
37412 }
37413 return getConstVector(EltBits, UndefElts, VT.getSimpleVT(), DAG, SDLoc(N));
37414 }
37415
37416 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
37417 if (TLI.SimplifyDemandedBits(SDValue(N, 0),
37418 APInt::getAllOnesValue(NumBitsPerElt), DCI))
37419 return SDValue(N, 0);
37420
37421 return SDValue();
37422}
37423
37424static SDValue combineVectorInsert(SDNode *N, SelectionDAG &DAG,
37425 TargetLowering::DAGCombinerInfo &DCI,
37426 const X86Subtarget &Subtarget) {
37427 EVT VT = N->getValueType(0);
37428 assert(((N->getOpcode() == X86ISD::PINSRB && VT == MVT::v16i8) ||((((N->getOpcode() == X86ISD::PINSRB && VT == MVT::
v16i8) || (N->getOpcode() == X86ISD::PINSRW && VT ==
MVT::v8i16)) && "Unexpected vector insertion") ? static_cast
<void> (0) : __assert_fail ("((N->getOpcode() == X86ISD::PINSRB && VT == MVT::v16i8) || (N->getOpcode() == X86ISD::PINSRW && VT == MVT::v8i16)) && \"Unexpected vector insertion\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 37430, __PRETTY_FUNCTION__))
37429 (N->getOpcode() == X86ISD::PINSRW && VT == MVT::v8i16)) &&((((N->getOpcode() == X86ISD::PINSRB && VT == MVT::
v16i8) || (N->getOpcode() == X86ISD::PINSRW && VT ==
MVT::v8i16)) && "Unexpected vector insertion") ? static_cast
<void> (0) : __assert_fail ("((N->getOpcode() == X86ISD::PINSRB && VT == MVT::v16i8) || (N->getOpcode() == X86ISD::PINSRW && VT == MVT::v8i16)) && \"Unexpected vector insertion\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 37430, __PRETTY_FUNCTION__))
37430 "Unexpected vector insertion")((((N->getOpcode() == X86ISD::PINSRB && VT == MVT::
v16i8) || (N->getOpcode() == X86ISD::PINSRW && VT ==
MVT::v8i16)) && "Unexpected vector insertion") ? static_cast
<void> (0) : __assert_fail ("((N->getOpcode() == X86ISD::PINSRB && VT == MVT::v16i8) || (N->getOpcode() == X86ISD::PINSRW && VT == MVT::v8i16)) && \"Unexpected vector insertion\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 37430, __PRETTY_FUNCTION__))
;
37431
37432 unsigned NumBitsPerElt = VT.getScalarSizeInBits();
37433 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
37434 if (TLI.SimplifyDemandedBits(SDValue(N, 0),
37435 APInt::getAllOnesValue(NumBitsPerElt), DCI))
37436 return SDValue(N, 0);
37437
37438 // Attempt to combine PINSRB/PINSRW patterns to a shuffle.
37439 SDValue Op(N, 0);
37440 if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
37441 return Res;
37442
37443 return SDValue();
37444}
37445
37446/// Recognize the distinctive (AND (setcc ...) (setcc ..)) where both setccs
37447/// reference the same FP CMP, and rewrite for CMPEQSS and friends. Likewise for
37448/// OR -> CMPNEQSS.
37449static SDValue combineCompareEqual(SDNode *N, SelectionDAG &DAG,
37450 TargetLowering::DAGCombinerInfo &DCI,
37451 const X86Subtarget &Subtarget) {
37452 unsigned opcode;
37453
37454 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
37455 // we're requiring SSE2 for both.
37456 if (Subtarget.hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
37457 SDValue N0 = N->getOperand(0);
37458 SDValue N1 = N->getOperand(1);
37459 SDValue CMP0 = N0.getOperand(1);
37460 SDValue CMP1 = N1.getOperand(1);
37461 SDLoc DL(N);
37462
37463 // The SETCCs should both refer to the same CMP.
37464 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
37465 return SDValue();
37466
37467 SDValue CMP00 = CMP0->getOperand(0);
37468 SDValue CMP01 = CMP0->getOperand(1);
37469 EVT VT = CMP00.getValueType();
37470
37471 if (VT == MVT::f32 || VT == MVT::f64) {
37472 bool ExpectingFlags = false;
37473 // Check for any users that want flags:
37474 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
37475 !ExpectingFlags && UI != UE; ++UI)
37476 switch (UI->getOpcode()) {
37477 default:
37478 case ISD::BR_CC:
37479 case ISD::BRCOND:
37480 case ISD::SELECT:
37481 ExpectingFlags = true;
37482 break;
37483 case ISD::CopyToReg:
37484 case ISD::SIGN_EXTEND:
37485 case ISD::ZERO_EXTEND:
37486 case ISD::ANY_EXTEND:
37487 break;
37488 }
37489
37490 if (!ExpectingFlags) {
37491 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
37492 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
37493
37494 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
37495 X86::CondCode tmp = cc0;
37496 cc0 = cc1;
37497 cc1 = tmp;
37498 }
37499
37500 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
37501 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
37502 // FIXME: need symbolic constants for these magic numbers.
37503 // See X86ATTInstPrinter.cpp:printSSECC().
37504 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
37505 if (Subtarget.hasAVX512()) {
37506 SDValue FSetCC =
37507 DAG.getNode(X86ISD::FSETCCM, DL, MVT::v1i1, CMP00, CMP01,
37508 DAG.getConstant(x86cc, DL, MVT::i8));
37509 // Need to fill with zeros to ensure the bitcast will produce zeroes
37510 // for the upper bits. An EXTRACT_ELEMENT here wouldn't guarantee that.
37511 SDValue Ins = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v16i1,
37512 DAG.getConstant(0, DL, MVT::v16i1),
37513 FSetCC, DAG.getIntPtrConstant(0, DL));
37514 return DAG.getZExtOrTrunc(DAG.getBitcast(MVT::i16, Ins), DL,
37515 N->getSimpleValueType(0));
37516 }
37517 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
37518 CMP00.getValueType(), CMP00, CMP01,
37519 DAG.getConstant(x86cc, DL,
37520 MVT::i8));
37521
37522 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
37523 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
37524
37525 if (is64BitFP && !Subtarget.is64Bit()) {
37526 // On a 32-bit target, we cannot bitcast the 64-bit float to a
37527 // 64-bit integer, since that's not a legal type. Since
37528 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
37529 // bits, but can do this little dance to extract the lowest 32 bits
37530 // and work with those going forward.
37531 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
37532 OnesOrZeroesF);
37533 SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
37534 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
37535 Vector32, DAG.getIntPtrConstant(0, DL));
37536 IntVT = MVT::i32;
37537 }
37538
37539 SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
37540 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
37541 DAG.getConstant(1, DL, IntVT));
37542 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
37543 ANDed);
37544 return OneBitOfTruth;
37545 }
37546 }
37547 }
37548 }
37549 return SDValue();
37550}
37551
37552// Match (xor X, -1) -> X.
37553// Match extract_subvector(xor X, -1) -> extract_subvector(X).
37554static SDValue IsNOT(SDValue V, SelectionDAG &DAG) {
37555 V = peekThroughBitcasts(V);
37556 if (V.getOpcode() == ISD::XOR &&
37557 ISD::isBuildVectorAllOnes(V.getOperand(1).getNode()))
37558 return V.getOperand(0);
37559 if (V.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
37560 (isNullConstant(V.getOperand(1)) || V.getOperand(0).hasOneUse())) {
37561 if (SDValue Not = IsNOT(V.getOperand(0), DAG)) {
37562 Not = DAG.getBitcast(V.getOperand(0).getValueType(), Not);
37563 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Not), V.getValueType(),
37564 Not, V.getOperand(1));
37565 }
37566 }
37567 return SDValue();
37568}
37569
37570/// Try to fold: (and (xor X, -1), Y) -> (andnp X, Y).
37571static SDValue combineANDXORWithAllOnesIntoANDNP(SDNode *N, SelectionDAG &DAG) {
37572 assert(N->getOpcode() == ISD::AND)((N->getOpcode() == ISD::AND) ? static_cast<void> (0
) : __assert_fail ("N->getOpcode() == ISD::AND", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 37572, __PRETTY_FUNCTION__))
;
37573
37574 MVT VT = N->getSimpleValueType(0);
37575 if (!VT.is128BitVector() && !VT.is256BitVector() && !VT.is512BitVector())
37576 return SDValue();
37577
37578 SDValue X, Y;
37579 SDValue N0 = N->getOperand(0);
37580 SDValue N1 = N->getOperand(1);
37581
37582 if (SDValue Not = IsNOT(N0, DAG)) {
37583 X = Not;
37584 Y = N1;
37585 } else if (SDValue Not = IsNOT(N1, DAG)) {
37586 X = Not;
37587 Y = N0;
37588 } else
37589 return SDValue();
37590
37591 X = DAG.getBitcast(VT, X);
37592 Y = DAG.getBitcast(VT, Y);
37593 return DAG.getNode(X86ISD::ANDNP, SDLoc(N), VT, X, Y);
37594}
37595
37596// On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
37597// register. In most cases we actually compare or select YMM-sized registers
37598// and mixing the two types creates horrible code. This method optimizes
37599// some of the transition sequences.
37600// Even with AVX-512 this is still useful for removing casts around logical
37601// operations on vXi1 mask types.
37602static SDValue PromoteMaskArithmetic(SDNode *N, SelectionDAG &DAG,
37603 const X86Subtarget &Subtarget) {
37604 EVT VT = N->getValueType(0);
37605 assert(VT.isVector() && "Expected vector type")((VT.isVector() && "Expected vector type") ? static_cast
<void> (0) : __assert_fail ("VT.isVector() && \"Expected vector type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 37605, __PRETTY_FUNCTION__))
;
37606
37607 assert((N->getOpcode() == ISD::ANY_EXTEND ||(((N->getOpcode() == ISD::ANY_EXTEND || N->getOpcode() ==
ISD::ZERO_EXTEND || N->getOpcode() == ISD::SIGN_EXTEND) &&
"Invalid Node") ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 37609, __PRETTY_FUNCTION__))
37608 N->getOpcode() == ISD::ZERO_EXTEND ||(((N->getOpcode() == ISD::ANY_EXTEND || N->getOpcode() ==
ISD::ZERO_EXTEND || N->getOpcode() == ISD::SIGN_EXTEND) &&
"Invalid Node") ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 37609, __PRETTY_FUNCTION__))
37609 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node")(((N->getOpcode() == ISD::ANY_EXTEND || N->getOpcode() ==
ISD::ZERO_EXTEND || N->getOpcode() == ISD::SIGN_EXTEND) &&
"Invalid Node") ? static_cast<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-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 37609, __PRETTY_FUNCTION__))
;
37610
37611 SDValue Narrow = N->getOperand(0);
37612 EVT NarrowVT = Narrow.getValueType();
37613
37614 if (Narrow->getOpcode() != ISD::XOR &&
37615 Narrow->getOpcode() != ISD::AND &&
37616 Narrow->getOpcode() != ISD::OR)
37617 return SDValue();
37618
37619 SDValue N0 = Narrow->getOperand(0);
37620 SDValue N1 = Narrow->getOperand(1);
37621 SDLoc DL(Narrow);
37622
37623 // The Left side has to be a trunc.
37624 if (N0.getOpcode() != ISD::TRUNCATE)
37625 return SDValue();
37626
37627 // The type of the truncated inputs.
37628 if (N0.getOperand(0).getValueType() != VT)
37629 return SDValue();
37630
37631 // The right side has to be a 'trunc' or a constant vector.
37632 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE &&
37633 N1.getOperand(0).getValueType() == VT;
37634 if (!RHSTrunc &&
37635 !ISD::isBuildVectorOfConstantSDNodes(N1.getNode()))
37636 return SDValue();
37637
37638 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
37639
37640 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), VT))
37641 return SDValue();
37642
37643 // Set N0 and N1 to hold the inputs to the new wide operation.
37644 N0 = N0.getOperand(0);
37645 if (RHSTrunc)
37646 N1 = N1.getOperand(0);
37647 else
37648 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N1);
37649
37650 // Generate the wide operation.
37651 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, VT, N0, N1);
37652 unsigned Opcode = N->getOpcode();
37653 switch (Opcode) {
37654 default: llvm_unreachable("Unexpected opcode")::llvm::llvm_unreachable_internal("Unexpected opcode", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 37654)
;
37655 case ISD::ANY_EXTEND:
37656 return Op;
37657 case ISD::ZERO_EXTEND:
37658 return DAG.getZeroExtendInReg(Op, DL, NarrowVT.getScalarType());
37659 case ISD::SIGN_EXTEND:
37660 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
37661 Op, DAG.getValueType(NarrowVT));
37662 }
37663}
37664
37665/// If both input operands of a logic op are being cast from floating point
37666/// types, try to convert this into a floating point logic node to avoid
37667/// unnecessary moves from SSE to integer registers.
37668static SDValue convertIntLogicToFPLogic(SDNode *N, SelectionDAG &DAG,
37669 const X86Subtarget &Subtarget) {
37670 unsigned FPOpcode = ISD::DELETED_NODE;
37671 if (N->getOpcode() == ISD::AND)
37672 FPOpcode = X86ISD::FAND;
37673 else if (N->getOpcode() == ISD::OR)
37674 FPOpcode = X86ISD::FOR;
37675 else if (N->getOpcode() == ISD::XOR)
37676 FPOpcode = X86ISD::FXOR;
37677
37678 assert(FPOpcode != ISD::DELETED_NODE &&((FPOpcode != ISD::DELETED_NODE && "Unexpected input node for FP logic conversion"
) ? static_cast<void> (0) : __assert_fail ("FPOpcode != ISD::DELETED_NODE && \"Unexpected input node for FP logic conversion\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 37679, __PRETTY_FUNCTION__))
37679 "Unexpected input node for FP logic conversion")((FPOpcode != ISD::DELETED_NODE && "Unexpected input node for FP logic conversion"
) ? static_cast<void> (0) : __assert_fail ("FPOpcode != ISD::DELETED_NODE && \"Unexpected input node for FP logic conversion\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 37679, __PRETTY_FUNCTION__))
;
37680
37681 EVT VT = N->getValueType(0);
37682 SDValue N0 = N->getOperand(0);
37683 SDValue N1 = N->getOperand(1);
37684 SDLoc DL(N);
37685 if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST &&
37686 ((Subtarget.hasSSE1() && VT == MVT::i32) ||
37687 (Subtarget.hasSSE2() && VT == MVT::i64))) {
37688 SDValue N00 = N0.getOperand(0);
37689 SDValue N10 = N1.getOperand(0);
37690 EVT N00Type = N00.getValueType();
37691 EVT N10Type = N10.getValueType();
37692 if (N00Type.isFloatingPoint() && N10Type.isFloatingPoint()) {
37693 SDValue FPLogic = DAG.getNode(FPOpcode, DL, N00Type, N00, N10);
37694 return DAG.getBitcast(VT, FPLogic);
37695 }
37696 }
37697 return SDValue();
37698}
37699
37700/// If this is a zero/all-bits result that is bitwise-anded with a low bits
37701/// mask. (Mask == 1 for the x86 lowering of a SETCC + ZEXT), replace the 'and'
37702/// with a shift-right to eliminate loading the vector constant mask value.
37703static SDValue combineAndMaskToShift(SDNode *N, SelectionDAG &DAG,
37704 const X86Subtarget &Subtarget) {
37705 SDValue Op0 = peekThroughBitcasts(N->getOperand(0));
37706 SDValue Op1 = peekThroughBitcasts(N->getOperand(1));
37707 EVT VT0 = Op0.getValueType();
37708 EVT VT1 = Op1.getValueType();
37709
37710 if (VT0 != VT1 || !VT0.isSimple() || !VT0.isInteger())
37711 return SDValue();
37712
37713 APInt SplatVal;
37714 if (!ISD::isConstantSplatVector(Op1.getNode(), SplatVal) ||
37715 !SplatVal.isMask())
37716 return SDValue();
37717
37718 // Don't prevent creation of ANDN.
37719 if (isBitwiseNot(Op0))
37720 return SDValue();
37721
37722 if (!SupportedVectorShiftWithImm(VT0.getSimpleVT(), Subtarget, ISD::SRL))
37723 return SDValue();
37724
37725 unsigned EltBitWidth = VT0.getScalarSizeInBits();
37726 if (EltBitWidth != DAG.ComputeNumSignBits(Op0))
37727 return SDValue();
37728
37729 SDLoc DL(N);
37730 unsigned ShiftVal = SplatVal.countTrailingOnes();
37731 SDValue ShAmt = DAG.getConstant(EltBitWidth - ShiftVal, DL, MVT::i8);
37732 SDValue Shift = DAG.getNode(X86ISD::VSRLI, DL, VT0, Op0, ShAmt);
37733 return DAG.getBitcast(N->getValueType(0), Shift);
37734}
37735
37736// Get the index node from the lowered DAG of a GEP IR instruction with one
37737// indexing dimension.
37738static SDValue getIndexFromUnindexedLoad(LoadSDNode *Ld) {
37739 if (Ld->isIndexed())
37740 return SDValue();
37741
37742 SDValue Base = Ld->getBasePtr();
37743
37744 if (Base.getOpcode() != ISD::ADD)
37745 return SDValue();
37746
37747 SDValue ShiftedIndex = Base.getOperand(0);
37748
37749 if (ShiftedIndex.getOpcode() != ISD::SHL)
37750 return SDValue();
37751
37752 return ShiftedIndex.getOperand(0);
37753
37754}
37755
37756static bool hasBZHI(const X86Subtarget &Subtarget, MVT VT) {
37757 if (Subtarget.hasBMI2() && VT.isScalarInteger()) {
37758 switch (VT.getSizeInBits()) {
37759 default: return false;
37760 case 64: return Subtarget.is64Bit() ? true : false;
37761 case 32: return true;
37762 }
37763 }
37764 return false;
37765}
37766
37767// This function recognizes cases where X86 bzhi instruction can replace and
37768// 'and-load' sequence.
37769// In case of loading integer value from an array of constants which is defined
37770// as follows:
37771//
37772// int array[SIZE] = {0x0, 0x1, 0x3, 0x7, 0xF ..., 2^(SIZE-1) - 1}
37773//
37774// then applying a bitwise and on the result with another input.
37775// It's equivalent to performing bzhi (zero high bits) on the input, with the
37776// same index of the load.
37777static SDValue combineAndLoadToBZHI(SDNode *Node, SelectionDAG &DAG,
37778 const X86Subtarget &Subtarget) {
37779 MVT VT = Node->getSimpleValueType(0);
37780 SDLoc dl(Node);
37781
37782 // Check if subtarget has BZHI instruction for the node's type
37783 if (!hasBZHI(Subtarget, VT))
37784 return SDValue();
37785
37786 // Try matching the pattern for both operands.
37787 for (unsigned i = 0; i < 2; i++) {
37788 SDValue N = Node->getOperand(i);
37789 LoadSDNode *Ld = dyn_cast<LoadSDNode>(N.getNode());
37790
37791 // continue if the operand is not a load instruction
37792 if (!Ld)
37793 return SDValue();
37794
37795 const Value *MemOp = Ld->getMemOperand()->getValue();
37796
37797 if (!MemOp)
37798 return SDValue();
37799
37800 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(MemOp)) {
37801 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0))) {
37802 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
37803
37804 Constant *Init = GV->getInitializer();
37805 Type *Ty = Init->getType();
37806 if (!isa<ConstantDataArray>(Init) ||
37807 !Ty->getArrayElementType()->isIntegerTy() ||
37808 Ty->getArrayElementType()->getScalarSizeInBits() !=
37809 VT.getSizeInBits() ||
37810 Ty->getArrayNumElements() >
37811 Ty->getArrayElementType()->getScalarSizeInBits())
37812 continue;
37813
37814 // Check if the array's constant elements are suitable to our case.
37815 uint64_t ArrayElementCount = Init->getType()->getArrayNumElements();
37816 bool ConstantsMatch = true;
37817 for (uint64_t j = 0; j < ArrayElementCount; j++) {
37818 ConstantInt *Elem =
37819 dyn_cast<ConstantInt>(Init->getAggregateElement(j));
37820 if (Elem->getZExtValue() != (((uint64_t)1 << j) - 1)) {
37821 ConstantsMatch = false;
37822 break;
37823 }
37824 }
37825 if (!ConstantsMatch)
37826 continue;
37827
37828 // Do the transformation (For 32-bit type):
37829 // -> (and (load arr[idx]), inp)
37830 // <- (and (srl 0xFFFFFFFF, (sub 32, idx)))
37831 // that will be replaced with one bzhi instruction.
37832 SDValue Inp = (i == 0) ? Node->getOperand(1) : Node->getOperand(0);
37833 SDValue SizeC = DAG.getConstant(VT.getSizeInBits(), dl, MVT::i32);
37834
37835 // Get the Node which indexes into the array.
37836 SDValue Index = getIndexFromUnindexedLoad(Ld);
37837 if (!Index)
37838 return SDValue();
37839 Index = DAG.getZExtOrTrunc(Index, dl, MVT::i32);
37840
37841 SDValue Sub = DAG.getNode(ISD::SUB, dl, MVT::i32, SizeC, Index);
37842 Sub = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Sub);
37843
37844 SDValue AllOnes = DAG.getAllOnesConstant(dl, VT);
37845 SDValue LShr = DAG.getNode(ISD::SRL, dl, VT, AllOnes, Sub);
37846
37847 return DAG.getNode(ISD::AND, dl, VT, Inp, LShr);
37848 }
37849 }
37850 }
37851 }
37852 return SDValue();
37853}
37854
37855// Look for (and (ctpop X), 1) which is the IR form of __builtin_parity.
37856// Turn it into series of XORs and a setnp.
37857static SDValue combineParity(SDNode *N, SelectionDAG &DAG,
37858 const X86Subtarget &Subtarget) {
37859 EVT VT = N->getValueType(0);
37860
37861 // We only support 64-bit and 32-bit. 64-bit requires special handling
37862 // unless the 64-bit popcnt instruction is legal.
37863 if (VT != MVT::i32 && VT != MVT::i64)
37864 return SDValue();
37865
37866 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
37867 if (TLI.isTypeLegal(VT) && TLI.isOperationLegal(ISD::CTPOP, VT))
37868 return SDValue();
37869
37870 SDValue N0 = N->getOperand(0);
37871 SDValue N1 = N->getOperand(1);
37872
37873 // LHS needs to be a single use CTPOP.
37874 if (N0.getOpcode() != ISD::CTPOP || !N0.hasOneUse())
37875 return SDValue();
37876
37877 // RHS needs to be 1.
37878 if (!isOneConstant(N1))
37879 return SDValue();
37880
37881 SDLoc DL(N);
37882 SDValue X = N0.getOperand(0);
37883
37884 // If this is 64-bit, its always best to xor the two 32-bit pieces together
37885 // even if we have popcnt.
37886 if (VT == MVT::i64) {
37887 SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32,
37888 DAG.getNode(ISD::SRL, DL, VT, X,
37889 DAG.getConstant(32, DL, MVT::i8)));
37890 SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, X);
37891 X = DAG.getNode(ISD::XOR, DL, MVT::i32, Lo, Hi);
37892 // Generate a 32-bit parity idiom. This will bring us back here if we need
37893 // to expand it too.
37894 SDValue Parity = DAG.getNode(ISD::AND, DL, MVT::i32,
37895 DAG.getNode(ISD::CTPOP, DL, MVT::i32, X),
37896 DAG.getConstant(1, DL, MVT::i32));
37897 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Parity);
37898 }
37899 assert(VT == MVT::i32 && "Unexpected VT!")((VT == MVT::i32 && "Unexpected VT!") ? static_cast<
void> (0) : __assert_fail ("VT == MVT::i32 && \"Unexpected VT!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 37899, __PRETTY_FUNCTION__))
;
37900
37901 // Xor the high and low 16-bits together using a 32-bit operation.
37902 SDValue Hi16 = DAG.getNode(ISD::SRL, DL, VT, X,
37903 DAG.getConstant(16, DL, MVT::i8));
37904 X = DAG.getNode(ISD::XOR, DL, VT, X, Hi16);
37905
37906 // Finally xor the low 2 bytes together and use a 8-bit flag setting xor.
37907 // This should allow an h-reg to be used to save a shift.
37908 // FIXME: We only get an h-reg in 32-bit mode.
37909 SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
37910 DAG.getNode(ISD::SRL, DL, VT, X,
37911 DAG.getConstant(8, DL, MVT::i8)));
37912 SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, X);
37913 SDVTList VTs = DAG.getVTList(MVT::i8, MVT::i32);
37914 SDValue Flags = DAG.getNode(X86ISD::XOR, DL, VTs, Lo, Hi).getValue(1);
37915
37916 // Copy the inverse of the parity flag into a register with setcc.
37917 SDValue Setnp = getSETCC(X86::COND_NP, Flags, DL, DAG);
37918 // Zero extend to original type.
37919 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0), Setnp);
37920}
37921
37922static SDValue combineAnd(SDNode *N, SelectionDAG &DAG,
37923 TargetLowering::DAGCombinerInfo &DCI,
37924 const X86Subtarget &Subtarget) {
37925 EVT VT = N->getValueType(0);
37926
37927 // If this is SSE1 only convert to FAND to avoid scalarization.
37928 if (Subtarget.hasSSE1() && !Subtarget.hasSSE2() && VT == MVT::v4i32) {
37929 return DAG.getBitcast(
37930 MVT::v4i32, DAG.getNode(X86ISD::FAND, SDLoc(N), MVT::v4f32,
37931 DAG.getBitcast(MVT::v4f32, N->getOperand(0)),
37932 DAG.getBitcast(MVT::v4f32, N->getOperand(1))));
37933 }
37934
37935 // Use a 32-bit and+zext if upper bits known zero.
37936 if (VT == MVT::i64 && Subtarget.is64Bit() &&
37937 !isa<ConstantSDNode>(N->getOperand(1))) {
37938 APInt HiMask = APInt::getHighBitsSet(64, 32);
37939 if (DAG.MaskedValueIsZero(N->getOperand(1), HiMask) ||
37940 DAG.MaskedValueIsZero(N->getOperand(0), HiMask)) {
37941 SDLoc dl(N);
37942 SDValue LHS = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, N->getOperand(0));
37943 SDValue RHS = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, N->getOperand(1));
37944 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64,
37945 DAG.getNode(ISD::AND, dl, MVT::i32, LHS, RHS));
37946 }
37947 }
37948
37949 // This must be done before legalization has expanded the ctpop.
37950 if (SDValue V = combineParity(N, DAG, Subtarget))
37951 return V;
37952
37953 // Match all-of bool scalar reductions into a bitcast/movmsk + cmp.
37954 // TODO: Support multiple SrcOps.
37955 if (VT == MVT::i1) {
37956 SmallVector<SDValue, 2> SrcOps;
37957 if (matchBitOpReduction(SDValue(N, 0), ISD::AND, SrcOps) &&
37958 SrcOps.size() == 1) {
37959 SDLoc dl(N);
37960 unsigned NumElts = SrcOps[0].getValueType().getVectorNumElements();
37961 EVT MaskVT = EVT::getIntegerVT(*DAG.getContext(), NumElts);
37962 SDValue Mask = combineBitcastvxi1(DAG, MaskVT, SrcOps[0], dl, Subtarget);
37963 if (Mask) {
37964 APInt AllBits = APInt::getAllOnesValue(NumElts);
37965 return DAG.getSetCC(dl, MVT::i1, Mask,
37966 DAG.getConstant(AllBits, dl, MaskVT), ISD::SETEQ);
37967 }
37968 }
37969 }
37970
37971 if (DCI.isBeforeLegalizeOps())
37972 return SDValue();
37973
37974 if (SDValue R = combineCompareEqual(N, DAG, DCI, Subtarget))
37975 return R;
37976
37977 if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
37978 return FPLogic;
37979
37980 if (SDValue R = combineANDXORWithAllOnesIntoANDNP(N, DAG))
37981 return R;
37982
37983 if (SDValue ShiftRight = combineAndMaskToShift(N, DAG, Subtarget))
37984 return ShiftRight;
37985
37986 if (SDValue R = combineAndLoadToBZHI(N, DAG, Subtarget))
37987 return R;
37988
37989 // Attempt to recursively combine a bitmask AND with shuffles.
37990 if (VT.isVector() && (VT.getScalarSizeInBits() % 8) == 0) {
37991 SDValue Op(N, 0);
37992 if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
37993 return Res;
37994 }
37995
37996 // Attempt to combine a scalar bitmask AND with an extracted shuffle.
37997 if ((VT.getScalarSizeInBits() % 8) == 0 &&
37998 N->getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
37999 isa<ConstantSDNode>(N->getOperand(0).getOperand(1))) {
38000 SDValue BitMask = N->getOperand(1);
38001 SDValue SrcVec = N->getOperand(0).getOperand(0);
38002 EVT SrcVecVT = SrcVec.getValueType();
38003
38004 // Check that the constant bitmask masks whole bytes.
38005 APInt UndefElts;
38006 SmallVector<APInt, 64> EltBits;
38007 if (VT == SrcVecVT.getScalarType() &&
38008 N->getOperand(0)->isOnlyUserOf(SrcVec.getNode()) &&
38009 getTargetConstantBitsFromNode(BitMask, 8, UndefElts, EltBits) &&
38010 llvm::all_of(EltBits, [](APInt M) {
38011 return M.isNullValue() || M.isAllOnesValue();
38012 })) {
38013 unsigned NumElts = SrcVecVT.getVectorNumElements();
38014 unsigned Scale = SrcVecVT.getScalarSizeInBits() / 8;
38015 unsigned Idx = N->getOperand(0).getConstantOperandVal(1);
38016
38017 // Create a root shuffle mask from the byte mask and the extracted index.
38018 SmallVector<int, 16> ShuffleMask(NumElts * Scale, SM_SentinelUndef);
38019 for (unsigned i = 0; i != Scale; ++i) {
38020 if (UndefElts[i])
38021 continue;
38022 int VecIdx = Scale * Idx + i;
38023 ShuffleMask[VecIdx] =
38024 EltBits[i].isNullValue() ? SM_SentinelZero : VecIdx;
38025 }
38026
38027 if (SDValue Shuffle = combineX86ShufflesRecursively(
38028 {SrcVec}, 0, SrcVec, ShuffleMask, {}, /*Depth*/ 2,
38029 /*HasVarMask*/ false, /*AllowVarMask*/ true, DAG, Subtarget))
38030 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), VT, Shuffle,
38031 N->getOperand(0).getOperand(1));
38032 }
38033 }
38034
38035 return SDValue();
38036}
38037
38038// Canonicalize OR(AND(X,C),AND(Y,~C)) -> OR(AND(X,C),ANDNP(C,Y))
38039static SDValue canonicalizeBitSelect(SDNode *N, SelectionDAG &DAG,
38040 const X86Subtarget &Subtarget) {
38041 assert(N->getOpcode() == ISD::OR && "Unexpected Opcode")((N->getOpcode() == ISD::OR && "Unexpected Opcode"
) ? static_cast<void> (0) : __assert_fail ("N->getOpcode() == ISD::OR && \"Unexpected Opcode\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 38041, __PRETTY_FUNCTION__))
;
38042
38043 EVT VT = N->getValueType(0);
38044 if (!VT.isVector() || (VT.getScalarSizeInBits() % 8) != 0)
38045 return SDValue();
38046
38047 SDValue N0 = peekThroughBitcasts(N->getOperand(0));
38048 SDValue N1 = peekThroughBitcasts(N->getOperand(1));
38049 if (N0.getOpcode() != ISD::AND || N1.getOpcode() != ISD::AND)
38050 return SDValue();
38051
38052 // On XOP we'll lower to PCMOV so accept one use, otherwise only
38053 // do this if either mask has multiple uses already.
38054 if (!(Subtarget.hasXOP() || !N0.getOperand(1).hasOneUse() ||
38055 !N1.getOperand(1).hasOneUse()))
38056 return SDValue();
38057
38058 // Attempt to extract constant byte masks.
38059 APInt UndefElts0, UndefElts1;
38060 SmallVector<APInt, 32> EltBits0, EltBits1;
38061 if (!getTargetConstantBitsFromNode(N0.getOperand(1), 8, UndefElts0, EltBits0,
38062 false, false))
38063 return SDValue();
38064 if (!getTargetConstantBitsFromNode(N1.getOperand(1), 8, UndefElts1, EltBits1,
38065 false, false))
38066 return SDValue();
38067
38068 for (unsigned i = 0, e = EltBits0.size(); i != e; ++i) {
38069 // TODO - add UNDEF elts support.
38070 if (UndefElts0[i] || UndefElts1[i])
38071 return SDValue();
38072 if (EltBits0[i] != ~EltBits1[i])
38073 return SDValue();
38074 }
38075
38076 SDLoc DL(N);
38077 SDValue X = N->getOperand(0);
38078 SDValue Y =
38079 DAG.getNode(X86ISD::ANDNP, DL, VT, DAG.getBitcast(VT, N0.getOperand(1)),
38080 DAG.getBitcast(VT, N1.getOperand(0)));
38081 return DAG.getNode(ISD::OR, DL, VT, X, Y);
38082}
38083
38084// Try to match OR(AND(~MASK,X),AND(MASK,Y)) logic pattern.
38085static bool matchLogicBlend(SDNode *N, SDValue &X, SDValue &Y, SDValue &Mask) {
38086 if (N->getOpcode() != ISD::OR)
38087 return false;
38088
38089 SDValue N0 = N->getOperand(0);
38090 SDValue N1 = N->getOperand(1);
38091
38092 // Canonicalize AND to LHS.
38093 if (N1.getOpcode() == ISD::AND)
38094 std::swap(N0, N1);
38095
38096 // Attempt to match OR(AND(M,Y),ANDNP(M,X)).
38097 if (N0.getOpcode() != ISD::AND || N1.getOpcode() != X86ISD::ANDNP)
38098 return false;
38099
38100 Mask = N1.getOperand(0);
38101 X = N1.getOperand(1);
38102
38103 // Check to see if the mask appeared in both the AND and ANDNP.
38104 if (N0.getOperand(0) == Mask)
38105 Y = N0.getOperand(1);
38106 else if (N0.getOperand(1) == Mask)
38107 Y = N0.getOperand(0);
38108 else
38109 return false;
38110
38111 // TODO: Attempt to match against AND(XOR(-1,M),Y) as well, waiting for
38112 // ANDNP combine allows other combines to happen that prevent matching.
38113 return true;
38114}
38115
38116// Try to match:
38117// (or (and (M, (sub 0, X)), (pandn M, X)))
38118// which is a special case of vselect:
38119// (vselect M, (sub 0, X), X)
38120// Per:
38121// http://graphics.stanford.edu/~seander/bithacks.html#ConditionalNegate
38122// We know that, if fNegate is 0 or 1:
38123// (fNegate ? -v : v) == ((v ^ -fNegate) + fNegate)
38124//
38125// Here, we have a mask, M (all 1s or 0), and, similarly, we know that:
38126// ((M & 1) ? -X : X) == ((X ^ -(M & 1)) + (M & 1))
38127// ( M ? -X : X) == ((X ^ M ) + (M & 1))
38128// This lets us transform our vselect to:
38129// (add (xor X, M), (and M, 1))
38130// And further to:
38131// (sub (xor X, M), M)
38132static SDValue combineLogicBlendIntoConditionalNegate(
38133 EVT VT, SDValue Mask, SDValue X, SDValue Y, const SDLoc &DL,
38134 SelectionDAG &DAG, const X86Subtarget &Subtarget) {
38135 EVT MaskVT = Mask.getValueType();
38136 assert(MaskVT.isInteger() &&((MaskVT.isInteger() && DAG.ComputeNumSignBits(Mask) ==
MaskVT.getScalarSizeInBits() && "Mask must be zero/all-bits"
) ? static_cast<void> (0) : __assert_fail ("MaskVT.isInteger() && DAG.ComputeNumSignBits(Mask) == MaskVT.getScalarSizeInBits() && \"Mask must be zero/all-bits\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 38138, __PRETTY_FUNCTION__))
38137 DAG.ComputeNumSignBits(Mask) == MaskVT.getScalarSizeInBits() &&((MaskVT.isInteger() && DAG.ComputeNumSignBits(Mask) ==
MaskVT.getScalarSizeInBits() && "Mask must be zero/all-bits"
) ? static_cast<void> (0) : __assert_fail ("MaskVT.isInteger() && DAG.ComputeNumSignBits(Mask) == MaskVT.getScalarSizeInBits() && \"Mask must be zero/all-bits\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 38138, __PRETTY_FUNCTION__))
38138 "Mask must be zero/all-bits")((MaskVT.isInteger() && DAG.ComputeNumSignBits(Mask) ==
MaskVT.getScalarSizeInBits() && "Mask must be zero/all-bits"
) ? static_cast<void> (0) : __assert_fail ("MaskVT.isInteger() && DAG.ComputeNumSignBits(Mask) == MaskVT.getScalarSizeInBits() && \"Mask must be zero/all-bits\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 38138, __PRETTY_FUNCTION__))
;
38139
38140 if (X.getValueType() != MaskVT || Y.getValueType() != MaskVT)
38141 return SDValue();
38142 if (!DAG.getTargetLoweringInfo().isOperationLegal(ISD::SUB, MaskVT))
38143 return SDValue();
38144
38145 auto IsNegV = [](SDNode *N, SDValue V) {
38146 return N->getOpcode() == ISD::SUB && N->getOperand(1) == V &&
38147 ISD::isBuildVectorAllZeros(N->getOperand(0).getNode());
38148 };
38149
38150 SDValue V;
38151 if (IsNegV(Y.getNode(), X))
38152 V = X;
38153 else if (IsNegV(X.getNode(), Y))
38154 V = Y;
38155 else
38156 return SDValue();
38157
38158 SDValue SubOp1 = DAG.getNode(ISD::XOR, DL, MaskVT, V, Mask);
38159 SDValue SubOp2 = Mask;
38160
38161 // If the negate was on the false side of the select, then
38162 // the operands of the SUB need to be swapped. PR 27251.
38163 // This is because the pattern being matched above is
38164 // (vselect M, (sub (0, X), X) -> (sub (xor X, M), M)
38165 // but if the pattern matched was
38166 // (vselect M, X, (sub (0, X))), that is really negation of the pattern
38167 // above, -(vselect M, (sub 0, X), X), and therefore the replacement
38168 // pattern also needs to be a negation of the replacement pattern above.
38169 // And -(sub X, Y) is just sub (Y, X), so swapping the operands of the
38170 // sub accomplishes the negation of the replacement pattern.
38171 if (V == Y)
38172 std::swap(SubOp1, SubOp2);
38173
38174 SDValue Res = DAG.getNode(ISD::SUB, DL, MaskVT, SubOp1, SubOp2);
38175 return DAG.getBitcast(VT, Res);
38176}
38177
38178// Try to fold:
38179// (or (and (m, y), (pandn m, x)))
38180// into:
38181// (vselect m, x, y)
38182// As a special case, try to fold:
38183// (or (and (m, (sub 0, x)), (pandn m, x)))
38184// into:
38185// (sub (xor X, M), M)
38186static SDValue combineLogicBlendIntoPBLENDV(SDNode *N, SelectionDAG &DAG,
38187 const X86Subtarget &Subtarget) {
38188 assert(N->getOpcode() == ISD::OR && "Unexpected Opcode")((N->getOpcode() == ISD::OR && "Unexpected Opcode"
) ? static_cast<void> (0) : __assert_fail ("N->getOpcode() == ISD::OR && \"Unexpected Opcode\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 38188, __PRETTY_FUNCTION__))
;
38189
38190 EVT VT = N->getValueType(0);
38191 if (!((VT.is128BitVector() && Subtarget.hasSSE2()) ||
38192 (VT.is256BitVector() && Subtarget.hasInt256())))
38193 return SDValue();
38194
38195 SDValue X, Y, Mask;
38196 if (!matchLogicBlend(N, X, Y, Mask))
38197 return SDValue();
38198
38199 // Validate that X, Y, and Mask are bitcasts, and see through them.
38200 Mask = peekThroughBitcasts(Mask);
38201 X = peekThroughBitcasts(X);
38202 Y = peekThroughBitcasts(Y);
38203
38204 EVT MaskVT = Mask.getValueType();
38205 unsigned EltBits = MaskVT.getScalarSizeInBits();
38206
38207 // TODO: Attempt to handle floating point cases as well?
38208 if (!MaskVT.isInteger() || DAG.ComputeNumSignBits(Mask) != EltBits)
38209 return SDValue();
38210
38211 SDLoc DL(N);
38212
38213 // Attempt to combine to conditional negate: (sub (xor X, M), M)
38214 if (SDValue Res = combineLogicBlendIntoConditionalNegate(VT, Mask, X, Y, DL,
38215 DAG, Subtarget))
38216 return Res;
38217
38218 // PBLENDVB is only available on SSE 4.1.
38219 if (!Subtarget.hasSSE41())
38220 return SDValue();
38221
38222 MVT BlendVT = VT.is256BitVector() ? MVT::v32i8 : MVT::v16i8;
38223
38224 X = DAG.getBitcast(BlendVT, X);
38225 Y = DAG.getBitcast(BlendVT, Y);
38226 Mask = DAG.getBitcast(BlendVT, Mask);
38227 Mask = DAG.getSelect(DL, BlendVT, Mask, Y, X);
38228 return DAG.getBitcast(VT, Mask);
38229}
38230
38231// Helper function for combineOrCmpEqZeroToCtlzSrl
38232// Transforms:
38233// seteq(cmp x, 0)
38234// into:
38235// srl(ctlz x), log2(bitsize(x))
38236// Input pattern is checked by caller.
38237static SDValue lowerX86CmpEqZeroToCtlzSrl(SDValue Op, EVT ExtTy,
38238 SelectionDAG &DAG) {
38239 SDValue Cmp = Op.getOperand(1);
38240 EVT VT = Cmp.getOperand(0).getValueType();
38241 unsigned Log2b = Log2_32(VT.getSizeInBits());
38242 SDLoc dl(Op);
38243 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Cmp->getOperand(0));
38244 // The result of the shift is true or false, and on X86, the 32-bit
38245 // encoding of shr and lzcnt is more desirable.
38246 SDValue Trunc = DAG.getZExtOrTrunc(Clz, dl, MVT::i32);
38247 SDValue Scc = DAG.getNode(ISD::SRL, dl, MVT::i32, Trunc,
38248 DAG.getConstant(Log2b, dl, MVT::i8));
38249 return DAG.getZExtOrTrunc(Scc, dl, ExtTy);
38250}
38251
38252// Try to transform:
38253// zext(or(setcc(eq, (cmp x, 0)), setcc(eq, (cmp y, 0))))
38254// into:
38255// srl(or(ctlz(x), ctlz(y)), log2(bitsize(x))
38256// Will also attempt to match more generic cases, eg:
38257// zext(or(or(setcc(eq, cmp 0), setcc(eq, cmp 0)), setcc(eq, cmp 0)))
38258// Only applies if the target supports the FastLZCNT feature.
38259static SDValue combineOrCmpEqZeroToCtlzSrl(SDNode *N, SelectionDAG &DAG,
38260 TargetLowering::DAGCombinerInfo &DCI,
38261 const X86Subtarget &Subtarget) {
38262 if (DCI.isBeforeLegalize() || !Subtarget.getTargetLowering()->isCtlzFast())
38263 return SDValue();
38264
38265 auto isORCandidate = [](SDValue N) {
38266 return (N->getOpcode() == ISD::OR && N->hasOneUse());
38267 };
38268
38269 // Check the zero extend is extending to 32-bit or more. The code generated by
38270 // srl(ctlz) for 16-bit or less variants of the pattern would require extra
38271 // instructions to clear the upper bits.
38272 if (!N->hasOneUse() || !N->getSimpleValueType(0).bitsGE(MVT::i32) ||
38273 !isORCandidate(N->getOperand(0)))
38274 return SDValue();
38275
38276 // Check the node matches: setcc(eq, cmp 0)
38277 auto isSetCCCandidate = [](SDValue N) {
38278 return N->getOpcode() == X86ISD::SETCC && N->hasOneUse() &&
38279 X86::CondCode(N->getConstantOperandVal(0)) == X86::COND_E &&
38280 N->getOperand(1).getOpcode() == X86ISD::CMP &&
38281 isNullConstant(N->getOperand(1).getOperand(1)) &&
38282 N->getOperand(1).getValueType().bitsGE(MVT::i32);
38283 };
38284
38285 SDNode *OR = N->getOperand(0).getNode();
38286 SDValue LHS = OR->getOperand(0);
38287 SDValue RHS = OR->getOperand(1);
38288
38289 // Save nodes matching or(or, setcc(eq, cmp 0)).
38290 SmallVector<SDNode *, 2> ORNodes;
38291 while (((isORCandidate(LHS) && isSetCCCandidate(RHS)) ||
38292 (isORCandidate(RHS) && isSetCCCandidate(LHS)))) {
38293 ORNodes.push_back(OR);
38294 OR = (LHS->getOpcode() == ISD::OR) ? LHS.getNode() : RHS.getNode();
38295 LHS = OR->getOperand(0);
38296 RHS = OR->getOperand(1);
38297 }
38298
38299 // The last OR node should match or(setcc(eq, cmp 0), setcc(eq, cmp 0)).
38300 if (!(isSetCCCandidate(LHS) && isSetCCCandidate(RHS)) ||
38301 !isORCandidate(SDValue(OR, 0)))
38302 return SDValue();
38303
38304 // We have a or(setcc(eq, cmp 0), setcc(eq, cmp 0)) pattern, try to lower it
38305 // to
38306 // or(srl(ctlz),srl(ctlz)).
38307 // The dag combiner can then fold it into:
38308 // srl(or(ctlz, ctlz)).
38309 EVT VT = OR->getValueType(0);
38310 SDValue NewLHS = lowerX86CmpEqZeroToCtlzSrl(LHS, VT, DAG);
38311 SDValue Ret, NewRHS;
38312 if (NewLHS && (NewRHS = lowerX86CmpEqZeroToCtlzSrl(RHS, VT, DAG)))
38313 Ret = DAG.getNode(ISD::OR, SDLoc(OR), VT, NewLHS, NewRHS);
38314
38315 if (!Ret)
38316 return SDValue();
38317
38318 // Try to lower nodes matching the or(or, setcc(eq, cmp 0)) pattern.
38319 while (ORNodes.size() > 0) {
38320 OR = ORNodes.pop_back_val();
38321 LHS = OR->getOperand(0);
38322 RHS = OR->getOperand(1);
38323 // Swap rhs with lhs to match or(setcc(eq, cmp, 0), or).
38324 if (RHS->getOpcode() == ISD::OR)
38325 std::swap(LHS, RHS);
38326 NewRHS = lowerX86CmpEqZeroToCtlzSrl(RHS, VT, DAG);
38327 if (!NewRHS)
38328 return SDValue();
38329 Ret = DAG.getNode(ISD::OR, SDLoc(OR), VT, Ret, NewRHS);
38330 }
38331
38332 if (Ret)
38333 Ret = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0), Ret);
38334
38335 return Ret;
38336}
38337
38338static SDValue combineOr(SDNode *N, SelectionDAG &DAG,
38339 TargetLowering::DAGCombinerInfo &DCI,
38340 const X86Subtarget &Subtarget) {
38341 SDValue N0 = N->getOperand(0);
38342 SDValue N1 = N->getOperand(1);
38343 EVT VT = N->getValueType(0);
38344
38345 // If this is SSE1 only convert to FOR to avoid scalarization.
38346 if (Subtarget.hasSSE1() && !Subtarget.hasSSE2() && VT == MVT::v4i32) {
38347 return DAG.getBitcast(MVT::v4i32,
38348 DAG.getNode(X86ISD::FOR, SDLoc(N), MVT::v4f32,
38349 DAG.getBitcast(MVT::v4f32, N0),
38350 DAG.getBitcast(MVT::v4f32, N1)));
38351 }
38352
38353 if (DCI.isBeforeLegalizeOps())
38354 return SDValue();
38355
38356 if (SDValue R = combineCompareEqual(N, DAG, DCI, Subtarget))
38357 return R;
38358
38359 if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
38360 return FPLogic;
38361
38362 if (SDValue R = canonicalizeBitSelect(N, DAG, Subtarget))
38363 return R;
38364
38365 if (SDValue R = combineLogicBlendIntoPBLENDV(N, DAG, Subtarget))
38366 return R;
38367
38368 // Attempt to recursively combine an OR of shuffles.
38369 if (VT.isVector() && (VT.getScalarSizeInBits() % 8) == 0) {
38370 SDValue Op(N, 0);
38371 if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
38372 return Res;
38373 }
38374
38375 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
38376 return SDValue();
38377
38378 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
38379 bool OptForSize = DAG.getMachineFunction().getFunction().hasOptSize();
38380 unsigned Bits = VT.getScalarSizeInBits();
38381
38382 // SHLD/SHRD instructions have lower register pressure, but on some
38383 // platforms they have higher latency than the equivalent
38384 // series of shifts/or that would otherwise be generated.
38385 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
38386 // have higher latencies and we are not optimizing for size.
38387 if (!OptForSize && Subtarget.isSHLDSlow())
38388 return SDValue();
38389
38390 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
38391 std::swap(N0, N1);
38392 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
38393 return SDValue();
38394 if (!N0.hasOneUse() || !N1.hasOneUse())
38395 return SDValue();
38396
38397 SDValue ShAmt0 = N0.getOperand(1);
38398 if (ShAmt0.getValueType() != MVT::i8)
38399 return SDValue();
38400 SDValue ShAmt1 = N1.getOperand(1);
38401 if (ShAmt1.getValueType() != MVT::i8)
38402 return SDValue();
38403
38404 // Peek through any modulo shift masks.
38405 SDValue ShMsk0;
38406 if (ShAmt0.getOpcode() == ISD::AND &&
38407 isa<ConstantSDNode>(ShAmt0.getOperand(1)) &&
38408 ShAmt0.getConstantOperandVal(1) == (Bits - 1)) {
38409 ShMsk0 = ShAmt0;
38410 ShAmt0 = ShAmt0.getOperand(0);
38411 }
38412 SDValue ShMsk1;
38413 if (ShAmt1.getOpcode() == ISD::AND &&
38414 isa<ConstantSDNode>(ShAmt1.getOperand(1)) &&
38415 ShAmt1.getConstantOperandVal(1) == (Bits - 1)) {
38416 ShMsk1 = ShAmt1;
38417 ShAmt1 = ShAmt1.getOperand(0);
38418 }
38419
38420 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
38421 ShAmt0 = ShAmt0.getOperand(0);
38422 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
38423 ShAmt1 = ShAmt1.getOperand(0);
38424
38425 SDLoc DL(N);
38426 unsigned Opc = ISD::FSHL;
38427 SDValue Op0 = N0.getOperand(0);
38428 SDValue Op1 = N1.getOperand(0);
38429 if (ShAmt0.getOpcode() == ISD::SUB || ShAmt0.getOpcode() == ISD::XOR) {
38430 Opc = ISD::FSHR;
38431 std::swap(Op0, Op1);
38432 std::swap(ShAmt0, ShAmt1);
38433 std::swap(ShMsk0, ShMsk1);
38434 }
38435
38436 auto GetFunnelShift = [&DAG, &DL, VT, Opc](SDValue Op0, SDValue Op1,
38437 SDValue Amt) {
38438 if (Opc == ISD::FSHR)
38439 std::swap(Op0, Op1);
38440 return DAG.getNode(Opc, DL, VT, Op0, Op1,
38441 DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, Amt));
38442 };
38443
38444 // OR( SHL( X, C ), SRL( Y, 32 - C ) ) -> FSHL( X, Y, C )
38445 // OR( SRL( X, C ), SHL( Y, 32 - C ) ) -> FSHR( Y, X, C )
38446 // OR( SHL( X, C ), SRL( SRL( Y, 1 ), XOR( C, 31 ) ) ) -> FSHL( X, Y, C )
38447 // OR( SRL( X, C ), SHL( SHL( Y, 1 ), XOR( C, 31 ) ) ) -> FSHR( Y, X, C )
38448 // OR( SHL( X, AND( C, 31 ) ), SRL( Y, AND( 0 - C, 31 ) ) ) -> FSHL( X, Y, C )
38449 // OR( SRL( X, AND( C, 31 ) ), SHL( Y, AND( 0 - C, 31 ) ) ) -> FSHR( Y, X, C )
38450 if (ShAmt1.getOpcode() == ISD::SUB) {
38451 SDValue Sum = ShAmt1.getOperand(0);
38452 if (auto *SumC = dyn_cast<ConstantSDNode>(Sum)) {
38453 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
38454 if (ShAmt1Op1.getOpcode() == ISD::AND &&
38455 isa<ConstantSDNode>(ShAmt1Op1.getOperand(1)) &&
38456 ShAmt1Op1.getConstantOperandVal(1) == (Bits - 1)) {
38457 ShMsk1 = ShAmt1Op1;
38458 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
38459 }
38460 if (ShAmt1Op1.getOpcode() == ISD::TRUNCATE)
38461 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
38462 if ((SumC->getAPIntValue() == Bits ||
38463 (SumC->getAPIntValue() == 0 && ShMsk1)) &&
38464 ShAmt1Op1 == ShAmt0)
38465 return GetFunnelShift(Op0, Op1, ShAmt0);
38466 }
38467 } else if (auto *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
38468 auto *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
38469 if (ShAmt0C && (ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue()) == Bits)
38470 return GetFunnelShift(Op0, Op1, ShAmt0);
38471 } else if (ShAmt1.getOpcode() == ISD::XOR) {
38472 SDValue Mask = ShAmt1.getOperand(1);
38473 if (auto *MaskC = dyn_cast<ConstantSDNode>(Mask)) {
38474 unsigned InnerShift = (ISD::FSHL == Opc ? ISD::SRL : ISD::SHL);
38475 SDValue ShAmt1Op0 = ShAmt1.getOperand(0);
38476 if (ShAmt1Op0.getOpcode() == ISD::TRUNCATE)
38477 ShAmt1Op0 = ShAmt1Op0.getOperand(0);
38478 if (MaskC->getSExtValue() == (Bits - 1) &&
38479 (ShAmt1Op0 == ShAmt0 || ShAmt1Op0 == ShMsk0)) {
38480 if (Op1.getOpcode() == InnerShift &&
38481 isa<ConstantSDNode>(Op1.getOperand(1)) &&
38482 Op1.getConstantOperandVal(1) == 1) {
38483 return GetFunnelShift(Op0, Op1.getOperand(0), ShAmt0);
38484 }
38485 // Test for ADD( Y, Y ) as an equivalent to SHL( Y, 1 ).
38486 if (InnerShift == ISD::SHL && Op1.getOpcode() == ISD::ADD &&
38487 Op1.getOperand(0) == Op1.getOperand(1)) {
38488 return GetFunnelShift(Op0, Op1.getOperand(0), ShAmt0);
38489 }
38490 }
38491 }
38492 }
38493
38494 return SDValue();
38495}
38496
38497/// Try to turn tests against the signbit in the form of:
38498/// XOR(TRUNCATE(SRL(X, size(X)-1)), 1)
38499/// into:
38500/// SETGT(X, -1)
38501static SDValue foldXorTruncShiftIntoCmp(SDNode *N, SelectionDAG &DAG) {
38502 // This is only worth doing if the output type is i8 or i1.
38503 EVT ResultType = N->getValueType(0);
38504 if (ResultType != MVT::i8 && ResultType != MVT::i1)
38505 return SDValue();
38506
38507 SDValue N0 = N->getOperand(0);
38508 SDValue N1 = N->getOperand(1);
38509
38510 // We should be performing an xor against a truncated shift.
38511 if (N0.getOpcode() != ISD::TRUNCATE || !N0.hasOneUse())
38512 return SDValue();
38513
38514 // Make sure we are performing an xor against one.
38515 if (!isOneConstant(N1))
38516 return SDValue();
38517
38518 // SetCC on x86 zero extends so only act on this if it's a logical shift.
38519 SDValue Shift = N0.getOperand(0);
38520 if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse())
38521 return SDValue();
38522
38523 // Make sure we are truncating from one of i16, i32 or i64.
38524 EVT ShiftTy = Shift.getValueType();
38525 if (ShiftTy != MVT::i16 && ShiftTy != MVT::i32 && ShiftTy != MVT::i64)
38526 return SDValue();
38527
38528 // Make sure the shift amount extracts the sign bit.
38529 if (!isa<ConstantSDNode>(Shift.getOperand(1)) ||
38530 Shift.getConstantOperandVal(1) != ShiftTy.getSizeInBits() - 1)
38531 return SDValue();
38532
38533 // Create a greater-than comparison against -1.
38534 // N.B. Using SETGE against 0 works but we want a canonical looking
38535 // comparison, using SETGT matches up with what TranslateX86CC.
38536 SDLoc DL(N);
38537 SDValue ShiftOp = Shift.getOperand(0);
38538 EVT ShiftOpTy = ShiftOp.getValueType();
38539 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
38540 EVT SetCCResultType = TLI.getSetCCResultType(DAG.getDataLayout(),
38541 *DAG.getContext(), ResultType);
38542 SDValue Cond = DAG.getSetCC(DL, SetCCResultType, ShiftOp,
38543 DAG.getConstant(-1, DL, ShiftOpTy), ISD::SETGT);
38544 if (SetCCResultType != ResultType)
38545 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, ResultType, Cond);
38546 return Cond;
38547}
38548
38549/// Turn vector tests of the signbit in the form of:
38550/// xor (sra X, elt_size(X)-1), -1
38551/// into:
38552/// pcmpgt X, -1
38553///
38554/// This should be called before type legalization because the pattern may not
38555/// persist after that.
38556static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
38557 const X86Subtarget &Subtarget) {
38558 EVT VT = N->getValueType(0);
38559 if (!VT.isSimple())
38560 return SDValue();
38561
38562 switch (VT.getSimpleVT().SimpleTy) {
38563 default: return SDValue();
38564 case MVT::v16i8:
38565 case MVT::v8i16:
38566 case MVT::v4i32: if (!Subtarget.hasSSE2()) return SDValue(); break;
38567 case MVT::v2i64: if (!Subtarget.hasSSE42()) return SDValue(); break;
38568 case MVT::v32i8:
38569 case MVT::v16i16:
38570 case MVT::v8i32:
38571 case MVT::v4i64: if (!Subtarget.hasAVX2()) return SDValue(); break;
38572 }
38573
38574 // There must be a shift right algebraic before the xor, and the xor must be a
38575 // 'not' operation.
38576 SDValue Shift = N->getOperand(0);
38577 SDValue Ones = N->getOperand(1);
38578 if (Shift.getOpcode() != ISD::SRA || !Shift.hasOneUse() ||
38579 !ISD::isBuildVectorAllOnes(Ones.getNode()))
38580 return SDValue();
38581
38582 // The shift should be smearing the sign bit across each vector element.
38583 auto *ShiftBV = dyn_cast<BuildVectorSDNode>(Shift.getOperand(1));
38584 if (!ShiftBV)
38585 return SDValue();
38586
38587 EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
38588 auto *ShiftAmt = ShiftBV->getConstantSplatNode();
38589 if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
38590 return SDValue();
38591
38592 // Create a greater-than comparison against -1. We don't use the more obvious
38593 // greater-than-or-equal-to-zero because SSE/AVX don't have that instruction.
38594 return DAG.getNode(X86ISD::PCMPGT, SDLoc(N), VT, Shift.getOperand(0), Ones);
38595}
38596
38597/// Check if truncation with saturation form type \p SrcVT to \p DstVT
38598/// is valid for the given \p Subtarget.
38599static bool isSATValidOnAVX512Subtarget(EVT SrcVT, EVT DstVT,
38600 const X86Subtarget &Subtarget) {
38601 if (!Subtarget.hasAVX512())
38602 return false;
38603
38604 // FIXME: Scalar type may be supported if we move it to vector register.
38605 if (!SrcVT.isVector())
38606 return false;
38607
38608 EVT SrcElVT = SrcVT.getScalarType();
38609 EVT DstElVT = DstVT.getScalarType();
38610 if (DstElVT != MVT::i8 && DstElVT != MVT::i16 && DstElVT != MVT::i32)
38611 return false;
38612 if (SrcVT.is512BitVector() || Subtarget.hasVLX())
38613 return SrcElVT.getSizeInBits() >= 32 || Subtarget.hasBWI();
38614 return false;
38615}
38616
38617/// Detect patterns of truncation with unsigned saturation:
38618///
38619/// 1. (truncate (umin (x, unsigned_max_of_dest_type)) to dest_type).
38620/// Return the source value x to be truncated or SDValue() if the pattern was
38621/// not matched.
38622///
38623/// 2. (truncate (smin (smax (x, C1), C2)) to dest_type),
38624/// where C1 >= 0 and C2 is unsigned max of destination type.
38625///
38626/// (truncate (smax (smin (x, C2), C1)) to dest_type)
38627/// where C1 >= 0, C2 is unsigned max of destination type and C1 <= C2.
38628///
38629/// These two patterns are equivalent to:
38630/// (truncate (umin (smax(x, C1), unsigned_max_of_dest_type)) to dest_type)
38631/// So return the smax(x, C1) value to be truncated or SDValue() if the
38632/// pattern was not matched.
38633static SDValue detectUSatPattern(SDValue In, EVT VT, SelectionDAG &DAG,
38634 const SDLoc &DL) {
38635 EVT InVT = In.getValueType();
38636
38637 // Saturation with truncation. We truncate from InVT to VT.
38638 assert(InVT.getScalarSizeInBits() > VT.getScalarSizeInBits() &&((InVT.getScalarSizeInBits() > VT.getScalarSizeInBits() &&
"Unexpected types for truncate operation") ? static_cast<
void> (0) : __assert_fail ("InVT.getScalarSizeInBits() > VT.getScalarSizeInBits() && \"Unexpected types for truncate operation\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 38639, __PRETTY_FUNCTION__))
38639 "Unexpected types for truncate operation")((InVT.getScalarSizeInBits() > VT.getScalarSizeInBits() &&
"Unexpected types for truncate operation") ? static_cast<
void> (0) : __assert_fail ("InVT.getScalarSizeInBits() > VT.getScalarSizeInBits() && \"Unexpected types for truncate operation\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 38639, __PRETTY_FUNCTION__))
;
38640
38641 // Match min/max and return limit value as a parameter.
38642 auto MatchMinMax = [](SDValue V, unsigned Opcode, APInt &Limit) -> SDValue {
38643 if (V.getOpcode() == Opcode &&
38644 ISD::isConstantSplatVector(V.getOperand(1).getNode(), Limit))
38645 return V.getOperand(0);
38646 return SDValue();
38647 };
38648
38649 APInt C1, C2;
38650 if (SDValue UMin = MatchMinMax(In, ISD::UMIN, C2))
38651 // C2 should be equal to UINT32_MAX / UINT16_MAX / UINT8_MAX according
38652 // the element size of the destination type.
38653 if (C2.isMask(VT.getScalarSizeInBits()))
38654 return UMin;
38655
38656 if (SDValue SMin = MatchMinMax(In, ISD::SMIN, C2))
38657 if (MatchMinMax(SMin, ISD::SMAX, C1))
38658 if (C1.isNonNegative() && C2.isMask(VT.getScalarSizeInBits()))
38659 return SMin;
38660
38661 if (SDValue SMax = MatchMinMax(In, ISD::SMAX, C1))
38662 if (SDValue SMin = MatchMinMax(SMax, ISD::SMIN, C2))
38663 if (C1.isNonNegative() && C2.isMask(VT.getScalarSizeInBits()) &&
38664 C2.uge(C1)) {
38665 return DAG.getNode(ISD::SMAX, DL, InVT, SMin, In.getOperand(1));
38666 }
38667
38668 return SDValue();
38669}
38670
38671/// Detect patterns of truncation with signed saturation:
38672/// (truncate (smin ((smax (x, signed_min_of_dest_type)),
38673/// signed_max_of_dest_type)) to dest_type)
38674/// or:
38675/// (truncate (smax ((smin (x, signed_max_of_dest_type)),
38676/// signed_min_of_dest_type)) to dest_type).
38677/// With MatchPackUS, the smax/smin range is [0, unsigned_max_of_dest_type].
38678/// Return the source value to be truncated or SDValue() if the pattern was not
38679/// matched.
38680static SDValue detectSSatPattern(SDValue In, EVT VT, bool MatchPackUS = false) {
38681 unsigned NumDstBits = VT.getScalarSizeInBits();
38682 unsigned NumSrcBits = In.getScalarValueSizeInBits();
38683 assert(NumSrcBits > NumDstBits && "Unexpected types for truncate operation")((NumSrcBits > NumDstBits && "Unexpected types for truncate operation"
) ? static_cast<void> (0) : __assert_fail ("NumSrcBits > NumDstBits && \"Unexpected types for truncate operation\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 38683, __PRETTY_FUNCTION__))
;
38684
38685 auto MatchMinMax = [](SDValue V, unsigned Opcode,
38686 const APInt &Limit) -> SDValue {
38687 APInt C;
38688 if (V.getOpcode() == Opcode &&
38689 ISD::isConstantSplatVector(V.getOperand(1).getNode(), C) && C == Limit)
38690 return V.getOperand(0);
38691 return SDValue();
38692 };
38693
38694 APInt SignedMax, SignedMin;
38695 if (MatchPackUS) {
38696 SignedMax = APInt::getAllOnesValue(NumDstBits).zext(NumSrcBits);
38697 SignedMin = APInt(NumSrcBits, 0);
38698 } else {
38699 SignedMax = APInt::getSignedMaxValue(NumDstBits).sext(NumSrcBits);
38700 SignedMin = APInt::getSignedMinValue(NumDstBits).sext(NumSrcBits);
38701 }
38702
38703 if (SDValue SMin = MatchMinMax(In, ISD::SMIN, SignedMax))
38704 if (SDValue SMax = MatchMinMax(SMin, ISD::SMAX, SignedMin))
38705 return SMax;
38706
38707 if (SDValue SMax = MatchMinMax(In, ISD::SMAX, SignedMin))
38708 if (SDValue SMin = MatchMinMax(SMax, ISD::SMIN, SignedMax))
38709 return SMin;
38710
38711 return SDValue();
38712}
38713
38714/// Detect a pattern of truncation with signed saturation.
38715/// The types should allow to use VPMOVSS* instruction on AVX512.
38716/// Return the source value to be truncated or SDValue() if the pattern was not
38717/// matched.
38718static SDValue detectAVX512SSatPattern(SDValue In, EVT VT,
38719 const X86Subtarget &Subtarget,
38720 const TargetLowering &TLI) {
38721 if (!TLI.isTypeLegal(In.getValueType()))
38722 return SDValue();
38723 if (!isSATValidOnAVX512Subtarget(In.getValueType(), VT, Subtarget))
38724 return SDValue();
38725 return detectSSatPattern(In, VT);
38726}
38727
38728/// Detect a pattern of truncation with saturation:
38729/// (truncate (umin (x, unsigned_max_of_dest_type)) to dest_type).
38730/// The types should allow to use VPMOVUS* instruction on AVX512.
38731/// Return the source value to be truncated or SDValue() if the pattern was not
38732/// matched.
38733static SDValue detectAVX512USatPattern(SDValue In, EVT VT, SelectionDAG &DAG,
38734 const SDLoc &DL,
38735 const X86Subtarget &Subtarget,
38736 const TargetLowering &TLI) {
38737 if (!TLI.isTypeLegal(In.getValueType()))
38738 return SDValue();
38739 if (!isSATValidOnAVX512Subtarget(In.getValueType(), VT, Subtarget))
38740 return SDValue();
38741 return detectUSatPattern(In, VT, DAG, DL);
38742}
38743
38744static SDValue combineTruncateWithSat(SDValue In, EVT VT, const SDLoc &DL,
38745 SelectionDAG &DAG,
38746 const X86Subtarget &Subtarget) {
38747 EVT SVT = VT.getScalarType();
38748 EVT InVT = In.getValueType();
38749 EVT InSVT = InVT.getScalarType();
38750 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
38751 if (TLI.isTypeLegal(InVT) && TLI.isTypeLegal(VT) &&
38752 isSATValidOnAVX512Subtarget(InVT, VT, Subtarget)) {
38753 if (auto SSatVal = detectSSatPattern(In, VT))
38754 return DAG.getNode(X86ISD::VTRUNCS, DL, VT, SSatVal);
38755 if (auto USatVal = detectUSatPattern(In, VT, DAG, DL))
38756 return DAG.getNode(X86ISD::VTRUNCUS, DL, VT, USatVal);
38757 }
38758 if (VT.isVector() && isPowerOf2_32(VT.getVectorNumElements()) &&
38759 !Subtarget.hasAVX512() &&
38760 (SVT == MVT::i8 || SVT == MVT::i16) &&
38761 (InSVT == MVT::i16 || InSVT == MVT::i32)) {
38762 if (auto USatVal = detectSSatPattern(In, VT, true)) {
38763 // vXi32 -> vXi8 must be performed as PACKUSWB(PACKSSDW,PACKSSDW).
38764 if (SVT == MVT::i8 && InSVT == MVT::i32) {
38765 EVT MidVT = EVT::getVectorVT(*DAG.getContext(), MVT::i16,
38766 VT.getVectorNumElements());
38767 SDValue Mid = truncateVectorWithPACK(X86ISD::PACKSS, MidVT, USatVal, DL,
38768 DAG, Subtarget);
38769 if (Mid)
38770 return truncateVectorWithPACK(X86ISD::PACKUS, VT, Mid, DL, DAG,
38771 Subtarget);
38772 } else if (SVT == MVT::i8 || Subtarget.hasSSE41())
38773 return truncateVectorWithPACK(X86ISD::PACKUS, VT, USatVal, DL, DAG,
38774 Subtarget);
38775 }
38776 if (auto SSatVal = detectSSatPattern(In, VT))
38777 return truncateVectorWithPACK(X86ISD::PACKSS, VT, SSatVal, DL, DAG,
38778 Subtarget);
38779 }
38780 return SDValue();
38781}
38782
38783/// This function detects the AVG pattern between vectors of unsigned i8/i16,
38784/// which is c = (a + b + 1) / 2, and replace this operation with the efficient
38785/// X86ISD::AVG instruction.
38786static SDValue detectAVGPattern(SDValue In, EVT VT, SelectionDAG &DAG,
38787 const X86Subtarget &Subtarget,
38788 const SDLoc &DL) {
38789 if (!VT.isVector())
38790 return SDValue();
38791 EVT InVT = In.getValueType();
38792 unsigned NumElems = VT.getVectorNumElements();
38793
38794 EVT ScalarVT = VT.getVectorElementType();
38795 if (!((ScalarVT == MVT::i8 || ScalarVT == MVT::i16) &&
38796 NumElems >= 2 && isPowerOf2_32(NumElems)))
38797 return SDValue();
38798
38799 // InScalarVT is the intermediate type in AVG pattern and it should be greater
38800 // than the original input type (i8/i16).
38801 EVT InScalarVT = InVT.getVectorElementType();
38802 if (InScalarVT.getSizeInBits() <= ScalarVT.getSizeInBits())
38803 return SDValue();
38804
38805 if (!Subtarget.hasSSE2())
38806 return SDValue();
38807
38808 // Detect the following pattern:
38809 //
38810 // %1 = zext <N x i8> %a to <N x i32>
38811 // %2 = zext <N x i8> %b to <N x i32>
38812 // %3 = add nuw nsw <N x i32> %1, <i32 1 x N>
38813 // %4 = add nuw nsw <N x i32> %3, %2
38814 // %5 = lshr <N x i32> %N, <i32 1 x N>
38815 // %6 = trunc <N x i32> %5 to <N x i8>
38816 //
38817 // In AVX512, the last instruction can also be a trunc store.
38818 if (In.getOpcode() != ISD::SRL)
38819 return SDValue();
38820
38821 // A lambda checking the given SDValue is a constant vector and each element
38822 // is in the range [Min, Max].
38823 auto IsConstVectorInRange = [](SDValue V, unsigned Min, unsigned Max) {
38824 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(V);
38825 if (!BV || !BV->isConstant())
38826 return false;
38827 for (SDValue Op : V->ops()) {
38828 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
38829 if (!C)
38830 return false;
38831 const APInt &Val = C->getAPIntValue();
38832 if (Val.ult(Min) || Val.ugt(Max))
38833 return false;
38834 }
38835 return true;
38836 };
38837
38838 // Check if each element of the vector is left-shifted by one.
38839 auto LHS = In.getOperand(0);
38840 auto RHS = In.getOperand(1);
38841 if (!IsConstVectorInRange(RHS, 1, 1))
38842 return SDValue();
38843 if (LHS.getOpcode() != ISD::ADD)
38844 return SDValue();
38845
38846 // Detect a pattern of a + b + 1 where the order doesn't matter.
38847 SDValue Operands[3];
38848 Operands[0] = LHS.getOperand(0);
38849 Operands[1] = LHS.getOperand(1);
38850
38851 auto AVGBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
38852 ArrayRef<SDValue> Ops) {
38853 return DAG.getNode(X86ISD::AVG, DL, Ops[0].getValueType(), Ops);
38854 };
38855
38856 // Take care of the case when one of the operands is a constant vector whose
38857 // element is in the range [1, 256].
38858 if (IsConstVectorInRange(Operands[1], 1, ScalarVT == MVT::i8 ? 256 : 65536) &&
38859 Operands[0].getOpcode() == ISD::ZERO_EXTEND &&
38860 Operands[0].getOperand(0).getValueType() == VT) {
38861 // The pattern is detected. Subtract one from the constant vector, then
38862 // demote it and emit X86ISD::AVG instruction.
38863 SDValue VecOnes = DAG.getConstant(1, DL, InVT);
38864 Operands[1] = DAG.getNode(ISD::SUB, DL, InVT, Operands[1], VecOnes);
38865 Operands[1] = DAG.getNode(ISD::TRUNCATE, DL, VT, Operands[1]);
38866 return SplitOpsAndApply(DAG, Subtarget, DL, VT,
38867 { Operands[0].getOperand(0), Operands[1] },
38868 AVGBuilder);
38869 }
38870
38871 // Matches 'add like' patterns: add(Op0,Op1) + zext(or(Op0,Op1)).
38872 // Match the or case only if its 'add-like' - can be replaced by an add.
38873 auto FindAddLike = [&](SDValue V, SDValue &Op0, SDValue &Op1) {
38874 if (ISD::ADD == V.getOpcode()) {
38875 Op0 = V.getOperand(0);
38876 Op1 = V.getOperand(1);
38877 return true;
38878 }
38879 if (ISD::ZERO_EXTEND != V.getOpcode())
38880 return false;
38881 V = V.getOperand(0);
38882 if (V.getValueType() != VT || ISD::OR != V.getOpcode() ||
38883 !DAG.haveNoCommonBitsSet(V.getOperand(0), V.getOperand(1)))
38884 return false;
38885 Op0 = V.getOperand(0);
38886 Op1 = V.getOperand(1);
38887 return true;
38888 };
38889
38890 SDValue Op0, Op1;
38891 if (FindAddLike(Operands[0], Op0, Op1))
38892 std::swap(Operands[0], Operands[1]);
38893 else if (!FindAddLike(Operands[1], Op0, Op1))
38894 return SDValue();
38895 Operands[2] = Op0;
38896 Operands[1] = Op1;
38897
38898 // Now we have three operands of two additions. Check that one of them is a
38899 // constant vector with ones, and the other two can be promoted from i8/i16.
38900 for (int i = 0; i < 3; ++i) {
38901 if (!IsConstVectorInRange(Operands[i], 1, 1))
38902 continue;
38903 std::swap(Operands[i], Operands[2]);
38904
38905 // Check if Operands[0] and Operands[1] are results of type promotion.
38906 for (int j = 0; j < 2; ++j)
38907 if (Operands[j].getValueType() != VT) {
38908 if (Operands[j].getOpcode() != ISD::ZERO_EXTEND ||
38909 Operands[j].getOperand(0).getValueType() != VT)
38910 return SDValue();
38911 Operands[j] = Operands[j].getOperand(0);
38912 }
38913
38914 // The pattern is detected, emit X86ISD::AVG instruction(s).
38915 return SplitOpsAndApply(DAG, Subtarget, DL, VT, {Operands[0], Operands[1]},
38916 AVGBuilder);
38917 }
38918
38919 return SDValue();
38920}
38921
38922static SDValue combineLoad(SDNode *N, SelectionDAG &DAG,
38923 TargetLowering::DAGCombinerInfo &DCI,
38924 const X86Subtarget &Subtarget) {
38925 LoadSDNode *Ld = cast<LoadSDNode>(N);
38926 EVT RegVT = Ld->getValueType(0);
38927 EVT MemVT = Ld->getMemoryVT();
38928 SDLoc dl(Ld);
38929 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
38930
38931 // For chips with slow 32-byte unaligned loads, break the 32-byte operation
38932 // into two 16-byte operations. Also split non-temporal aligned loads on
38933 // pre-AVX2 targets as 32-byte loads will lower to regular temporal loads.
38934 ISD::LoadExtType Ext = Ld->getExtensionType();
38935 bool Fast;
38936 unsigned AddressSpace = Ld->getAddressSpace();
38937 unsigned Alignment = Ld->getAlignment();
38938 if (RegVT.is256BitVector() && !DCI.isBeforeLegalizeOps() &&
38939 Ext == ISD::NON_EXTLOAD &&
38940 ((Ld->isNonTemporal() && !Subtarget.hasInt256() && Alignment >= 16) ||
38941 (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), RegVT,
38942 AddressSpace, Alignment, &Fast) && !Fast))) {
38943 unsigned NumElems = RegVT.getVectorNumElements();
38944 if (NumElems < 2)
38945 return SDValue();
38946
38947 SDValue Ptr = Ld->getBasePtr();
38948
38949 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
38950 NumElems/2);
38951 SDValue Load1 =
38952 DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
38953 Alignment, Ld->getMemOperand()->getFlags());
38954
38955 Ptr = DAG.getMemBasePlusOffset(Ptr, 16, dl);
38956 SDValue Load2 =
38957 DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
38958 Ld->getPointerInfo().getWithOffset(16),
38959 MinAlign(Alignment, 16U), Ld->getMemOperand()->getFlags());
38960 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
38961 Load1.getValue(1),
38962 Load2.getValue(1));
38963
38964 SDValue NewVec = DAG.getNode(ISD::CONCAT_VECTORS, dl, RegVT, Load1, Load2);
38965 return DCI.CombineTo(N, NewVec, TF, true);
38966 }
38967
38968 // Bool vector load - attempt to cast to an integer, as we have good
38969 // (vXiY *ext(vXi1 bitcast(iX))) handling.
38970 if (Ext == ISD::NON_EXTLOAD && !Subtarget.hasAVX512() && RegVT.isVector() &&
38971 RegVT.getScalarType() == MVT::i1 && DCI.isBeforeLegalize()) {
38972 unsigned NumElts = RegVT.getVectorNumElements();
38973 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), NumElts);
38974 if (TLI.isTypeLegal(IntVT)) {
38975 SDValue IntLoad = DAG.getLoad(IntVT, dl, Ld->getChain(), Ld->getBasePtr(),
38976 Ld->getPointerInfo(), Alignment,
38977 Ld->getMemOperand()->getFlags());
38978 SDValue BoolVec = DAG.getBitcast(RegVT, IntLoad);
38979 return DCI.CombineTo(N, BoolVec, IntLoad.getValue(1), true);
38980 }
38981 }
38982
38983 return SDValue();
38984}
38985
38986/// If V is a build vector of boolean constants and exactly one of those
38987/// constants is true, return the operand index of that true element.
38988/// Otherwise, return -1.
38989static int getOneTrueElt(SDValue V) {
38990 // This needs to be a build vector of booleans.
38991 // TODO: Checking for the i1 type matches the IR definition for the mask,
38992 // but the mask check could be loosened to i8 or other types. That might
38993 // also require checking more than 'allOnesValue'; eg, the x86 HW
38994 // instructions only require that the MSB is set for each mask element.
38995 // The ISD::MSTORE comments/definition do not specify how the mask operand
38996 // is formatted.
38997 auto *BV = dyn_cast<BuildVectorSDNode>(V);
38998 if (!BV || BV->getValueType(0).getVectorElementType() != MVT::i1)
38999 return -1;
39000
39001 int TrueIndex = -1;
39002 unsigned NumElts = BV->getValueType(0).getVectorNumElements();
39003 for (unsigned i = 0; i < NumElts; ++i) {
39004 const SDValue &Op = BV->getOperand(i);
39005 if (Op.isUndef())
39006 continue;
39007 auto *ConstNode = dyn_cast<ConstantSDNode>(Op);
39008 if (!ConstNode)
39009 return -1;
39010 if (ConstNode->getAPIntValue().isAllOnesValue()) {
39011 // If we already found a one, this is too many.
39012 if (TrueIndex >= 0)
39013 return -1;
39014 TrueIndex = i;
39015 }
39016 }
39017 return TrueIndex;
39018}
39019
39020/// Given a masked memory load/store operation, return true if it has one mask
39021/// bit set. If it has one mask bit set, then also return the memory address of
39022/// the scalar element to load/store, the vector index to insert/extract that
39023/// scalar element, and the alignment for the scalar memory access.
39024static bool getParamsForOneTrueMaskedElt(MaskedLoadStoreSDNode *MaskedOp,
39025 SelectionDAG &DAG, SDValue &Addr,
39026 SDValue &Index, unsigned &Alignment) {
39027 int TrueMaskElt = getOneTrueElt(MaskedOp->getMask());
39028 if (TrueMaskElt < 0)
39029 return false;
39030
39031 // Get the address of the one scalar element that is specified by the mask
39032 // using the appropriate offset from the base pointer.
39033 EVT EltVT = MaskedOp->getMemoryVT().getVectorElementType();
39034 Addr = MaskedOp->getBasePtr();
39035 if (TrueMaskElt != 0) {
39036 unsigned Offset = TrueMaskElt * EltVT.getStoreSize();
39037 Addr = DAG.getMemBasePlusOffset(Addr, Offset, SDLoc(MaskedOp));
39038 }
39039
39040 Index = DAG.getIntPtrConstant(TrueMaskElt, SDLoc(MaskedOp));
39041 Alignment = MinAlign(MaskedOp->getAlignment(), EltVT.getStoreSize());
39042 return true;
39043}
39044
39045/// If exactly one element of the mask is set for a non-extending masked load,
39046/// it is a scalar load and vector insert.
39047/// Note: It is expected that the degenerate cases of an all-zeros or all-ones
39048/// mask have already been optimized in IR, so we don't bother with those here.
39049static SDValue
39050reduceMaskedLoadToScalarLoad(MaskedLoadSDNode *ML, SelectionDAG &DAG,
39051 TargetLowering::DAGCombinerInfo &DCI) {
39052 // TODO: This is not x86-specific, so it could be lifted to DAGCombiner.
39053 // However, some target hooks may need to be added to know when the transform
39054 // is profitable. Endianness would also have to be considered.
39055
39056 SDValue Addr, VecIndex;
39057 unsigned Alignment;
39058 if (!getParamsForOneTrueMaskedElt(ML, DAG, Addr, VecIndex, Alignment))
39059 return SDValue();
39060
39061 // Load the one scalar element that is specified by the mask using the
39062 // appropriate offset from the base pointer.
39063 SDLoc DL(ML);
39064 EVT VT = ML->getValueType(0);
39065 EVT EltVT = VT.getVectorElementType();
39066 SDValue Load =
39067 DAG.getLoad(EltVT, DL, ML->getChain(), Addr, ML->getPointerInfo(),
39068 Alignment, ML->getMemOperand()->getFlags());
39069
39070 // Insert the loaded element into the appropriate place in the vector.
39071 SDValue Insert = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT,
39072 ML->getPassThru(), Load, VecIndex);
39073 return DCI.CombineTo(ML, Insert, Load.getValue(1), true);
39074}
39075
39076static SDValue
39077combineMaskedLoadConstantMask(MaskedLoadSDNode *ML, SelectionDAG &DAG,
39078 TargetLowering::DAGCombinerInfo &DCI) {
39079 if (!ISD::isBuildVectorOfConstantSDNodes(ML->getMask().getNode()))
39080 return SDValue();
39081
39082 SDLoc DL(ML);
39083 EVT VT = ML->getValueType(0);
39084
39085 // If we are loading the first and last elements of a vector, it is safe and
39086 // always faster to load the whole vector. Replace the masked load with a
39087 // vector load and select.
39088 unsigned NumElts = VT.getVectorNumElements();
39089 BuildVectorSDNode *MaskBV = cast<BuildVectorSDNode>(ML->getMask());
39090 bool LoadFirstElt = !isNullConstant(MaskBV->getOperand(0));
39091 bool LoadLastElt = !isNullConstant(MaskBV->getOperand(NumElts - 1));
39092 if (LoadFirstElt && LoadLastElt) {
39093 SDValue VecLd = DAG.getLoad(VT, DL, ML->getChain(), ML->getBasePtr(),
39094 ML->getMemOperand());
39095 SDValue Blend = DAG.getSelect(DL, VT, ML->getMask(), VecLd,
39096 ML->getPassThru());
39097 return DCI.CombineTo(ML, Blend, VecLd.getValue(1), true);
39098 }
39099
39100 // Convert a masked load with a constant mask into a masked load and a select.
39101 // This allows the select operation to use a faster kind of select instruction
39102 // (for example, vblendvps -> vblendps).
39103
39104 // Don't try this if the pass-through operand is already undefined. That would
39105 // cause an infinite loop because that's what we're about to create.
39106 if (ML->getPassThru().isUndef())
39107 return SDValue();
39108
39109 // The new masked load has an undef pass-through operand. The select uses the
39110 // original pass-through operand.
39111 SDValue NewML = DAG.getMaskedLoad(VT, DL, ML->getChain(), ML->getBasePtr(),
39112 ML->getMask(), DAG.getUNDEF(VT),
39113 ML->getMemoryVT(), ML->getMemOperand(),
39114 ML->getExtensionType());
39115 SDValue Blend = DAG.getSelect(DL, VT, ML->getMask(), NewML,
39116 ML->getPassThru());
39117
39118 return DCI.CombineTo(ML, Blend, NewML.getValue(1), true);
39119}
39120
39121static SDValue combineMaskedLoad(SDNode *N, SelectionDAG &DAG,
39122 TargetLowering::DAGCombinerInfo &DCI,
39123 const X86Subtarget &Subtarget) {
39124 MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
39125
39126 // TODO: Expanding load with constant mask may be optimized as well.
39127 if (Mld->isExpandingLoad())
39128 return SDValue();
39129
39130 if (Mld->getExtensionType() == ISD::NON_EXTLOAD) {
39131 if (SDValue ScalarLoad = reduceMaskedLoadToScalarLoad(Mld, DAG, DCI))
39132 return ScalarLoad;
39133 // TODO: Do some AVX512 subsets benefit from this transform?
39134 if (!Subtarget.hasAVX512())
39135 if (SDValue Blend = combineMaskedLoadConstantMask(Mld, DAG, DCI))
39136 return Blend;
39137 }
39138
39139 if (Mld->getExtensionType() != ISD::EXTLOAD)
39140 return SDValue();
39141
39142 // Resolve extending loads.
39143 EVT VT = Mld->getValueType(0);
39144 unsigned NumElems = VT.getVectorNumElements();
39145 EVT LdVT = Mld->getMemoryVT();
39146 SDLoc dl(Mld);
39147
39148 assert(LdVT != VT && "Cannot extend to the same type")((LdVT != VT && "Cannot extend to the same type") ? static_cast
<void> (0) : __assert_fail ("LdVT != VT && \"Cannot extend to the same type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 39148, __PRETTY_FUNCTION__))
;
39149 unsigned ToSz = VT.getScalarSizeInBits();
39150 unsigned FromSz = LdVT.getScalarSizeInBits();
39151 // From/To sizes and ElemCount must be pow of two.
39152 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&((isPowerOf2_32(NumElems * FromSz * ToSz) && "Unexpected size for extending masked load"
) ? static_cast<void> (0) : __assert_fail ("isPowerOf2_32(NumElems * FromSz * ToSz) && \"Unexpected size for extending masked load\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 39153, __PRETTY_FUNCTION__))
39153 "Unexpected size for extending masked load")((isPowerOf2_32(NumElems * FromSz * ToSz) && "Unexpected size for extending masked load"
) ? static_cast<void> (0) : __assert_fail ("isPowerOf2_32(NumElems * FromSz * ToSz) && \"Unexpected size for extending masked load\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 39153, __PRETTY_FUNCTION__))
;
39154
39155 unsigned SizeRatio = ToSz / FromSz;
39156 assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits())((SizeRatio * NumElems * FromSz == VT.getSizeInBits()) ? static_cast
<void> (0) : __assert_fail ("SizeRatio * NumElems * FromSz == VT.getSizeInBits()"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 39156, __PRETTY_FUNCTION__))
;
39157
39158 // Create a type on which we perform the shuffle.
39159 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
39160 LdVT.getScalarType(), NumElems*SizeRatio);
39161 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits())((WideVecVT.getSizeInBits() == VT.getSizeInBits()) ? static_cast
<void> (0) : __assert_fail ("WideVecVT.getSizeInBits() == VT.getSizeInBits()"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 39161, __PRETTY_FUNCTION__))
;
39162
39163 // Convert PassThru value.
39164 SDValue WidePassThru = DAG.getBitcast(WideVecVT, Mld->getPassThru());
39165 if (!Mld->getPassThru().isUndef()) {
39166 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
39167 for (unsigned i = 0; i != NumElems; ++i)
39168 ShuffleVec[i] = i * SizeRatio;
39169
39170 // Can't shuffle using an illegal type.
39171 assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&((DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
"WideVecVT should be legal") ? static_cast<void> (0) :
__assert_fail ("DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) && \"WideVecVT should be legal\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 39172, __PRETTY_FUNCTION__))
39172 "WideVecVT should be legal")((DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
"WideVecVT should be legal") ? static_cast<void> (0) :
__assert_fail ("DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) && \"WideVecVT should be legal\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 39172, __PRETTY_FUNCTION__))
;
39173 WidePassThru = DAG.getVectorShuffle(WideVecVT, dl, WidePassThru,
39174 DAG.getUNDEF(WideVecVT), ShuffleVec);
39175 }
39176
39177 // Prepare the new mask.
39178 SDValue NewMask;
39179 SDValue Mask = Mld->getMask();
39180 if (Mask.getValueType() == VT) {
39181 // Mask and original value have the same type.
39182 NewMask = DAG.getBitcast(WideVecVT, Mask);
39183 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
39184 for (unsigned i = 0; i != NumElems; ++i)
39185 ShuffleVec[i] = i * SizeRatio;
39186 for (unsigned i = NumElems; i != NumElems * SizeRatio; ++i)
39187 ShuffleVec[i] = NumElems * SizeRatio;
39188 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
39189 DAG.getConstant(0, dl, WideVecVT),
39190 ShuffleVec);
39191 } else {
39192 assert(Mask.getValueType().getVectorElementType() == MVT::i1)((Mask.getValueType().getVectorElementType() == MVT::i1) ? static_cast
<void> (0) : __assert_fail ("Mask.getValueType().getVectorElementType() == MVT::i1"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 39192, __PRETTY_FUNCTION__))
;
39193 unsigned WidenNumElts = NumElems*SizeRatio;
39194 unsigned MaskNumElts = VT.getVectorNumElements();
39195 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
39196 WidenNumElts);
39197
39198 unsigned NumConcat = WidenNumElts / MaskNumElts;
39199 SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
39200 SmallVector<SDValue, 16> Ops(NumConcat, ZeroVal);
39201 Ops[0] = Mask;
39202 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
39203 }
39204
39205 SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
39206 Mld->getBasePtr(), NewMask, WidePassThru,
39207 Mld->getMemoryVT(), Mld->getMemOperand(),
39208 ISD::NON_EXTLOAD);
39209
39210 SDValue SlicedVec = DAG.getBitcast(WideVecVT, WideLd);
39211 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
39212 for (unsigned i = 0; i != NumElems; ++i)
39213 ShuffleVec[i * SizeRatio] = i;
39214
39215 // Can't shuffle using an illegal type.
39216 assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&((DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
"WideVecVT should be legal") ? static_cast<void> (0) :
__assert_fail ("DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) && \"WideVecVT should be legal\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 39217, __PRETTY_FUNCTION__))
39217 "WideVecVT should be legal")((DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
"WideVecVT should be legal") ? static_cast<void> (0) :
__assert_fail ("DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) && \"WideVecVT should be legal\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 39217, __PRETTY_FUNCTION__))
;
39218 SlicedVec = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
39219 DAG.getUNDEF(WideVecVT), ShuffleVec);
39220 SlicedVec = DAG.getBitcast(VT, SlicedVec);
39221
39222 return DCI.CombineTo(N, SlicedVec, WideLd.getValue(1), true);
39223}
39224
39225/// If exactly one element of the mask is set for a non-truncating masked store,
39226/// it is a vector extract and scalar store.
39227/// Note: It is expected that the degenerate cases of an all-zeros or all-ones
39228/// mask have already been optimized in IR, so we don't bother with those here.
39229static SDValue reduceMaskedStoreToScalarStore(MaskedStoreSDNode *MS,
39230 SelectionDAG &DAG) {
39231 // TODO: This is not x86-specific, so it could be lifted to DAGCombiner.
39232 // However, some target hooks may need to be added to know when the transform
39233 // is profitable. Endianness would also have to be considered.
39234
39235 SDValue Addr, VecIndex;
39236 unsigned Alignment;
39237 if (!getParamsForOneTrueMaskedElt(MS, DAG, Addr, VecIndex, Alignment))
39238 return SDValue();
39239
39240 // Extract the one scalar element that is actually being stored.
39241 SDLoc DL(MS);
39242 EVT VT = MS->getValue().getValueType();
39243 EVT EltVT = VT.getVectorElementType();
39244 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT,
39245 MS->getValue(), VecIndex);
39246
39247 // Store that element at the appropriate offset from the base pointer.
39248 return DAG.getStore(MS->getChain(), DL, Extract, Addr, MS->getPointerInfo(),
39249 Alignment, MS->getMemOperand()->getFlags());
39250}
39251
39252static SDValue combineMaskedStore(SDNode *N, SelectionDAG &DAG,
39253 TargetLowering::DAGCombinerInfo &DCI,
39254 const X86Subtarget &Subtarget) {
39255 MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
39256 if (Mst->isCompressingStore())
39257 return SDValue();
39258
39259 EVT VT = Mst->getValue().getValueType();
39260 EVT StVT = Mst->getMemoryVT();
39261 SDLoc dl(Mst);
39262 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
39263
39264 if (!Mst->isTruncatingStore()) {
39265 if (SDValue ScalarStore = reduceMaskedStoreToScalarStore(Mst, DAG))
39266 return ScalarStore;
39267
39268 // If the mask value has been legalized to a non-boolean vector, try to
39269 // simplify ops leading up to it. We only demand the MSB of each lane.
39270 SDValue Mask = Mst->getMask();
39271 if (Mask.getScalarValueSizeInBits() != 1) {
39272 APInt DemandedMask(APInt::getSignMask(VT.getScalarSizeInBits()));
39273 if (TLI.SimplifyDemandedBits(Mask, DemandedMask, DCI))
39274 return SDValue(N, 0);
39275 }
39276
39277 // TODO: AVX512 targets should also be able to simplify something like the
39278 // pattern above, but that pattern will be different. It will either need to
39279 // match setcc more generally or match PCMPGTM later (in tablegen?).
39280
39281 SDValue Value = Mst->getValue();
39282 if (Value.getOpcode() == ISD::TRUNCATE && Value.getNode()->hasOneUse() &&
39283 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
39284 Mst->getMemoryVT())) {
39285 return DAG.getMaskedStore(Mst->getChain(), SDLoc(N), Value.getOperand(0),
39286 Mst->getBasePtr(), Mask,
39287 Mst->getMemoryVT(), Mst->getMemOperand(), true);
39288 }
39289
39290 return SDValue();
39291 }
39292
39293 // Resolve truncating stores.
39294 unsigned NumElems = VT.getVectorNumElements();
39295
39296 assert(StVT != VT && "Cannot truncate to the same type")((StVT != VT && "Cannot truncate to the same type") ?
static_cast<void> (0) : __assert_fail ("StVT != VT && \"Cannot truncate to the same type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 39296, __PRETTY_FUNCTION__))
;
39297 unsigned FromSz = VT.getScalarSizeInBits();
39298 unsigned ToSz = StVT.getScalarSizeInBits();
39299
39300 // The truncating store is legal in some cases. For example
39301 // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
39302 // are designated for truncate store.
39303 // In this case we don't need any further transformations.
39304 if (TLI.isTruncStoreLegal(VT, StVT))
39305 return SDValue();
39306
39307 // From/To sizes and ElemCount must be pow of two.
39308 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&((isPowerOf2_32(NumElems * FromSz * ToSz) && "Unexpected size for truncating masked store"
) ? static_cast<void> (0) : __assert_fail ("isPowerOf2_32(NumElems * FromSz * ToSz) && \"Unexpected size for truncating masked store\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 39309, __PRETTY_FUNCTION__))
39309 "Unexpected size for truncating masked store")((isPowerOf2_32(NumElems * FromSz * ToSz) && "Unexpected size for truncating masked store"
) ? static_cast<void> (0) : __assert_fail ("isPowerOf2_32(NumElems * FromSz * ToSz) && \"Unexpected size for truncating masked store\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 39309, __PRETTY_FUNCTION__))
;
39310 // We are going to use the original vector elt for storing.
39311 // Accumulated smaller vector elements must be a multiple of the store size.
39312 assert (((NumElems * FromSz) % ToSz) == 0 &&((((NumElems * FromSz) % ToSz) == 0 && "Unexpected ratio for truncating masked store"
) ? static_cast<void> (0) : __assert_fail ("((NumElems * FromSz) % ToSz) == 0 && \"Unexpected ratio for truncating masked store\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 39313, __PRETTY_FUNCTION__))
39313 "Unexpected ratio for truncating masked store")((((NumElems * FromSz) % ToSz) == 0 && "Unexpected ratio for truncating masked store"
) ? static_cast<void> (0) : __assert_fail ("((NumElems * FromSz) % ToSz) == 0 && \"Unexpected ratio for truncating masked store\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 39313, __PRETTY_FUNCTION__))
;
39314
39315 unsigned SizeRatio = FromSz / ToSz;
39316 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits())((SizeRatio * NumElems * ToSz == VT.getSizeInBits()) ? static_cast
<void> (0) : __assert_fail ("SizeRatio * NumElems * ToSz == VT.getSizeInBits()"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 39316, __PRETTY_FUNCTION__))
;
39317
39318 // Create a type on which we perform the shuffle.
39319 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
39320 StVT.getScalarType(), NumElems*SizeRatio);
39321
39322 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits())((WideVecVT.getSizeInBits() == VT.getSizeInBits()) ? static_cast
<void> (0) : __assert_fail ("WideVecVT.getSizeInBits() == VT.getSizeInBits()"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 39322, __PRETTY_FUNCTION__))
;
39323
39324 SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
39325 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
39326 for (unsigned i = 0; i != NumElems; ++i)
39327 ShuffleVec[i] = i * SizeRatio;
39328
39329 // Can't shuffle using an illegal type.
39330 assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&((DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
"WideVecVT should be legal") ? static_cast<void> (0) :
__assert_fail ("DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) && \"WideVecVT should be legal\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 39331, __PRETTY_FUNCTION__))
39331 "WideVecVT should be legal")((DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
"WideVecVT should be legal") ? static_cast<void> (0) :
__assert_fail ("DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) && \"WideVecVT should be legal\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 39331, __PRETTY_FUNCTION__))
;
39332
39333 SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
39334 DAG.getUNDEF(WideVecVT),
39335 ShuffleVec);
39336
39337 SDValue NewMask;
39338 SDValue Mask = Mst->getMask();
39339 if (Mask.getValueType() == VT) {
39340 // Mask and original value have the same type.
39341 NewMask = DAG.getBitcast(WideVecVT, Mask);
39342 for (unsigned i = 0; i != NumElems; ++i)
39343 ShuffleVec[i] = i * SizeRatio;
39344 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
39345 ShuffleVec[i] = NumElems*SizeRatio;
39346 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
39347 DAG.getConstant(0, dl, WideVecVT),
39348 ShuffleVec);
39349 } else {
39350 assert(Mask.getValueType().getVectorElementType() == MVT::i1)((Mask.getValueType().getVectorElementType() == MVT::i1) ? static_cast
<void> (0) : __assert_fail ("Mask.getValueType().getVectorElementType() == MVT::i1"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 39350, __PRETTY_FUNCTION__))
;
39351 unsigned WidenNumElts = NumElems*SizeRatio;
39352 unsigned MaskNumElts = VT.getVectorNumElements();
39353 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
39354 WidenNumElts);
39355
39356 unsigned NumConcat = WidenNumElts / MaskNumElts;
39357 SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
39358 SmallVector<SDValue, 16> Ops(NumConcat, ZeroVal);
39359 Ops[0] = Mask;
39360 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
39361 }
39362
39363 return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal,
39364 Mst->getBasePtr(), NewMask, StVT,
39365 Mst->getMemOperand(), false);
39366}
39367
39368static SDValue combineStore(SDNode *N, SelectionDAG &DAG,
39369 const X86Subtarget &Subtarget) {
39370 StoreSDNode *St = cast<StoreSDNode>(N);
39371 EVT VT = St->getValue().getValueType();
39372 EVT StVT = St->getMemoryVT();
39373 SDLoc dl(St);
39374 SDValue StoredVal = St->getOperand(1);
39375 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
39376
39377 // Convert a store of vXi1 into a store of iX and a bitcast.
39378 if (!Subtarget.hasAVX512() && VT == StVT && VT.isVector() &&
39379 VT.getVectorElementType() == MVT::i1) {
39380
39381 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), VT.getVectorNumElements());
39382 StoredVal = DAG.getBitcast(NewVT, StoredVal);
39383
39384 return DAG.getStore(St->getChain(), dl, StoredVal, St->getBasePtr(),
39385 St->getPointerInfo(), St->getAlignment(),
39386 St->getMemOperand()->getFlags());
39387 }
39388
39389 // If this is a store of a scalar_to_vector to v1i1, just use a scalar store.
39390 // This will avoid a copy to k-register.
39391 if (VT == MVT::v1i1 && VT == StVT && Subtarget.hasAVX512() &&
39392 StoredVal.getOpcode() == ISD::SCALAR_TO_VECTOR &&
39393 StoredVal.getOperand(0).getValueType() == MVT::i8) {
39394 return DAG.getStore(St->getChain(), dl, StoredVal.getOperand(0),
39395 St->getBasePtr(), St->getPointerInfo(),
39396 St->getAlignment(), St->getMemOperand()->getFlags());
39397 }
39398
39399 // Widen v2i1/v4i1 stores to v8i1.
39400 if ((VT == MVT::v2i1 || VT == MVT::v4i1) && VT == StVT &&
39401 Subtarget.hasAVX512()) {
39402 unsigned NumConcats = 8 / VT.getVectorNumElements();
39403 SmallVector<SDValue, 4> Ops(NumConcats, DAG.getUNDEF(VT));
39404 Ops[0] = StoredVal;
39405 StoredVal = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i1, Ops);
39406 return DAG.getStore(St->getChain(), dl, StoredVal, St->getBasePtr(),
39407 St->getPointerInfo(), St->getAlignment(),
39408 St->getMemOperand()->getFlags());
39409 }
39410
39411 // Turn vXi1 stores of constants into a scalar store.
39412 if ((VT == MVT::v8i1 || VT == MVT::v16i1 || VT == MVT::v32i1 ||
39413 VT == MVT::v64i1) && VT == StVT && TLI.isTypeLegal(VT) &&
39414 ISD::isBuildVectorOfConstantSDNodes(StoredVal.getNode())) {
39415 // If its a v64i1 store without 64-bit support, we need two stores.
39416 if (VT == MVT::v64i1 && !Subtarget.is64Bit()) {
39417 SDValue Lo = DAG.getBuildVector(MVT::v32i1, dl,
39418 StoredVal->ops().slice(0, 32));
39419 Lo = combinevXi1ConstantToInteger(Lo, DAG);
39420 SDValue Hi = DAG.getBuildVector(MVT::v32i1, dl,
39421 StoredVal->ops().slice(32, 32));
39422 Hi = combinevXi1ConstantToInteger(Hi, DAG);
39423
39424 unsigned Alignment = St->getAlignment();
39425
39426 SDValue Ptr0 = St->getBasePtr();
39427 SDValue Ptr1 = DAG.getMemBasePlusOffset(Ptr0, 4, dl);
39428
39429 SDValue Ch0 =
39430 DAG.getStore(St->getChain(), dl, Lo, Ptr0, St->getPointerInfo(),
39431 Alignment, St->getMemOperand()->getFlags());
39432 SDValue Ch1 =
39433 DAG.getStore(St->getChain(), dl, Hi, Ptr1,
39434 St->getPointerInfo().getWithOffset(4),
39435 MinAlign(Alignment, 4U),
39436 St->getMemOperand()->getFlags());
39437 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
39438 }
39439
39440 StoredVal = combinevXi1ConstantToInteger(StoredVal, DAG);
39441 return DAG.getStore(St->getChain(), dl, StoredVal, St->getBasePtr(),
39442 St->getPointerInfo(), St->getAlignment(),
39443 St->getMemOperand()->getFlags());
39444 }
39445
39446 // If we are saving a concatenation of two XMM registers and 32-byte stores
39447 // are slow, such as on Sandy Bridge, perform two 16-byte stores.
39448 bool Fast;
39449 unsigned AddressSpace = St->getAddressSpace();
39450 unsigned Alignment = St->getAlignment();
39451 if (VT.is256BitVector() && StVT == VT &&
39452 TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
39453 AddressSpace, Alignment, &Fast) &&
39454 !Fast) {
39455 unsigned NumElems = VT.getVectorNumElements();
39456 if (NumElems < 2)
39457 return SDValue();
39458
39459 return split256BitStore(St, DAG);
39460 }
39461
39462 // Optimize trunc store (of multiple scalars) to shuffle and store.
39463 // First, pack all of the elements in one place. Next, store to memory
39464 // in fewer chunks.
39465 if (St->isTruncatingStore() && VT.isVector()) {
39466 // Check if we can detect an AVG pattern from the truncation. If yes,
39467 // replace the trunc store by a normal store with the result of X86ISD::AVG
39468 // instruction.
39469 if (SDValue Avg = detectAVGPattern(St->getValue(), St->getMemoryVT(), DAG,
39470 Subtarget, dl))
39471 return DAG.getStore(St->getChain(), dl, Avg, St->getBasePtr(),
39472 St->getPointerInfo(), St->getAlignment(),
39473 St->getMemOperand()->getFlags());
39474
39475 if (SDValue Val =
39476 detectAVX512SSatPattern(St->getValue(), St->getMemoryVT(), Subtarget,
39477 TLI))
39478 return EmitTruncSStore(true /* Signed saturation */, St->getChain(),
39479 dl, Val, St->getBasePtr(),
39480 St->getMemoryVT(), St->getMemOperand(), DAG);
39481 if (SDValue Val = detectAVX512USatPattern(St->getValue(), St->getMemoryVT(),
39482 DAG, dl, Subtarget, TLI))
39483 return EmitTruncSStore(false /* Unsigned saturation */, St->getChain(),
39484 dl, Val, St->getBasePtr(),
39485 St->getMemoryVT(), St->getMemOperand(), DAG);
39486
39487 unsigned NumElems = VT.getVectorNumElements();
39488 assert(StVT != VT && "Cannot truncate to the same type")((StVT != VT && "Cannot truncate to the same type") ?
static_cast<void> (0) : __assert_fail ("StVT != VT && \"Cannot truncate to the same type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 39488, __PRETTY_FUNCTION__))
;
39489 unsigned FromSz = VT.getScalarSizeInBits();
39490 unsigned ToSz = StVT.getScalarSizeInBits();
39491
39492 // The truncating store is legal in some cases. For example
39493 // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
39494 // are designated for truncate store.
39495 // In this case we don't need any further transformations.
39496 if (TLI.isTruncStoreLegalOrCustom(VT, StVT))
39497 return SDValue();
39498
39499 // From, To sizes and ElemCount must be pow of two
39500 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
39501 // We are going to use the original vector elt for storing.
39502 // Accumulated smaller vector elements must be a multiple of the store size.
39503 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
39504
39505 unsigned SizeRatio = FromSz / ToSz;
39506
39507 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits())((SizeRatio * NumElems * ToSz == VT.getSizeInBits()) ? static_cast
<void> (0) : __assert_fail ("SizeRatio * NumElems * ToSz == VT.getSizeInBits()"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 39507, __PRETTY_FUNCTION__))
;
39508
39509 // Create a type on which we perform the shuffle
39510 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
39511 StVT.getScalarType(), NumElems*SizeRatio);
39512
39513 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits())((WideVecVT.getSizeInBits() == VT.getSizeInBits()) ? static_cast
<void> (0) : __assert_fail ("WideVecVT.getSizeInBits() == VT.getSizeInBits()"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 39513, __PRETTY_FUNCTION__))
;
39514
39515 SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
39516 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
39517 for (unsigned i = 0; i != NumElems; ++i)
39518 ShuffleVec[i] = i * SizeRatio;
39519
39520 // Can't shuffle using an illegal type.
39521 if (!TLI.isTypeLegal(WideVecVT))
39522 return SDValue();
39523
39524 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
39525 DAG.getUNDEF(WideVecVT),
39526 ShuffleVec);
39527 // At this point all of the data is stored at the bottom of the
39528 // register. We now need to save it to mem.
39529
39530 // Find the largest store unit
39531 MVT StoreType = MVT::i8;
39532 for (MVT Tp : MVT::integer_valuetypes()) {
39533 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
39534 StoreType = Tp;
39535 }
39536
39537 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
39538 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
39539 (64 <= NumElems * ToSz))
39540 StoreType = MVT::f64;
39541
39542 // Bitcast the original vector into a vector of store-size units
39543 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
39544 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
39545 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits())((StoreVecVT.getSizeInBits() == VT.getSizeInBits()) ? static_cast
<void> (0) : __assert_fail ("StoreVecVT.getSizeInBits() == VT.getSizeInBits()"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 39545, __PRETTY_FUNCTION__))
;
39546 SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
39547 SmallVector<SDValue, 8> Chains;
39548 SDValue Ptr = St->getBasePtr();
39549
39550 // Perform one or more big stores into memory.
39551 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
39552 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
39553 StoreType, ShuffWide,
39554 DAG.getIntPtrConstant(i, dl));
39555 SDValue Ch =
39556 DAG.getStore(St->getChain(), dl, SubVec, Ptr, St->getPointerInfo(),
39557 St->getAlignment(), St->getMemOperand()->getFlags());
39558 Ptr = DAG.getMemBasePlusOffset(Ptr, StoreType.getStoreSize(), dl);
39559 Chains.push_back(Ch);
39560 }
39561
39562 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
39563 }
39564
39565 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
39566 // the FP state in cases where an emms may be missing.
39567 // A preferable solution to the general problem is to figure out the right
39568 // places to insert EMMS. This qualifies as a quick hack.
39569
39570 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
39571 if (VT.getSizeInBits() != 64)
39572 return SDValue();
39573
39574 const Function &F = DAG.getMachineFunction().getFunction();
39575 bool NoImplicitFloatOps = F.hasFnAttribute(Attribute::NoImplicitFloat);
39576 bool F64IsLegal =
39577 !Subtarget.useSoftFloat() && !NoImplicitFloatOps && Subtarget.hasSSE2();
39578 if ((VT.isVector() ||
39579 (VT == MVT::i64 && F64IsLegal && !Subtarget.is64Bit())) &&
39580 isa<LoadSDNode>(St->getValue()) &&
39581 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
39582 St->getChain().hasOneUse() && !St->isVolatile()) {
39583 LoadSDNode *Ld = cast<LoadSDNode>(St->getValue().getNode());
39584 SmallVector<SDValue, 8> Ops;
39585
39586 if (!ISD::isNormalLoad(Ld))
39587 return SDValue();
39588
39589 // If this is not the MMX case, i.e. we are just turning i64 load/store
39590 // into f64 load/store, avoid the transformation if there are multiple
39591 // uses of the loaded value.
39592 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
39593 return SDValue();
39594
39595 SDLoc LdDL(Ld);
39596 SDLoc StDL(N);
39597 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
39598 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
39599 // pair instead.
39600 if (Subtarget.is64Bit() || F64IsLegal) {
39601 MVT LdVT = (Subtarget.is64Bit() &&
39602 (!VT.isFloatingPoint() || !F64IsLegal)) ? MVT::i64 : MVT::f64;
39603 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
39604 Ld->getMemOperand());
39605
39606 // Make sure new load is placed in same chain order.
39607 DAG.makeEquivalentMemoryOrdering(Ld, NewLd);
39608 return DAG.getStore(St->getChain(), StDL, NewLd, St->getBasePtr(),
39609 St->getMemOperand());
39610 }
39611
39612 // Otherwise, lower to two pairs of 32-bit loads / stores.
39613 SDValue LoAddr = Ld->getBasePtr();
39614 SDValue HiAddr = DAG.getMemBasePlusOffset(LoAddr, 4, LdDL);
39615
39616 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
39617 Ld->getPointerInfo(), Ld->getAlignment(),
39618 Ld->getMemOperand()->getFlags());
39619 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
39620 Ld->getPointerInfo().getWithOffset(4),
39621 MinAlign(Ld->getAlignment(), 4),
39622 Ld->getMemOperand()->getFlags());
39623 // Make sure new loads are placed in same chain order.
39624 DAG.makeEquivalentMemoryOrdering(Ld, LoLd);
39625 DAG.makeEquivalentMemoryOrdering(Ld, HiLd);
39626
39627 LoAddr = St->getBasePtr();
39628 HiAddr = DAG.getMemBasePlusOffset(LoAddr, 4, StDL);
39629
39630 SDValue LoSt =
39631 DAG.getStore(St->getChain(), StDL, LoLd, LoAddr, St->getPointerInfo(),
39632 St->getAlignment(), St->getMemOperand()->getFlags());
39633 SDValue HiSt = DAG.getStore(St->getChain(), StDL, HiLd, HiAddr,
39634 St->getPointerInfo().getWithOffset(4),
39635 MinAlign(St->getAlignment(), 4),
39636 St->getMemOperand()->getFlags());
39637 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
39638 }
39639
39640 // This is similar to the above case, but here we handle a scalar 64-bit
39641 // integer store that is extracted from a vector on a 32-bit target.
39642 // If we have SSE2, then we can treat it like a floating-point double
39643 // to get past legalization. The execution dependencies fixup pass will
39644 // choose the optimal machine instruction for the store if this really is
39645 // an integer or v2f32 rather than an f64.
39646 if (VT == MVT::i64 && F64IsLegal && !Subtarget.is64Bit() &&
39647 St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
39648 SDValue OldExtract = St->getOperand(1);
39649 SDValue ExtOp0 = OldExtract.getOperand(0);
39650 unsigned VecSize = ExtOp0.getValueSizeInBits();
39651 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
39652 SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
39653 SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
39654 BitCast, OldExtract.getOperand(1));
39655 return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
39656 St->getPointerInfo(), St->getAlignment(),
39657 St->getMemOperand()->getFlags());
39658 }
39659
39660 return SDValue();
39661}
39662
39663/// Return 'true' if this vector operation is "horizontal"
39664/// and return the operands for the horizontal operation in LHS and RHS. A
39665/// horizontal operation performs the binary operation on successive elements
39666/// of its first operand, then on successive elements of its second operand,
39667/// returning the resulting values in a vector. For example, if
39668/// A = < float a0, float a1, float a2, float a3 >
39669/// and
39670/// B = < float b0, float b1, float b2, float b3 >
39671/// then the result of doing a horizontal operation on A and B is
39672/// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
39673/// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
39674/// A horizontal-op B, for some already available A and B, and if so then LHS is
39675/// set to A, RHS to B, and the routine returns 'true'.
39676static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, SelectionDAG &DAG,
39677 const X86Subtarget &Subtarget,
39678 bool IsCommutative) {
39679 // If either operand is undef, bail out. The binop should be simplified.
39680 if (LHS.isUndef() || RHS.isUndef())
39681 return false;
39682
39683 // Look for the following pattern:
39684 // A = < float a0, float a1, float a2, float a3 >
39685 // B = < float b0, float b1, float b2, float b3 >
39686 // and
39687 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
39688 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
39689 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
39690 // which is A horizontal-op B.
39691
39692 MVT VT = LHS.getSimpleValueType();
39693 assert((VT.is128BitVector() || VT.is256BitVector()) &&(((VT.is128BitVector() || VT.is256BitVector()) && "Unsupported vector type for horizontal add/sub"
) ? static_cast<void> (0) : __assert_fail ("(VT.is128BitVector() || VT.is256BitVector()) && \"Unsupported vector type for horizontal add/sub\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 39694, __PRETTY_FUNCTION__))
39694 "Unsupported vector type for horizontal add/sub")(((VT.is128BitVector() || VT.is256BitVector()) && "Unsupported vector type for horizontal add/sub"
) ? static_cast<void> (0) : __assert_fail ("(VT.is128BitVector() || VT.is256BitVector()) && \"Unsupported vector type for horizontal add/sub\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 39694, __PRETTY_FUNCTION__))
;
39695 unsigned NumElts = VT.getVectorNumElements();
39696
39697 // TODO - can we make a general helper method that does all of this for us?
39698 auto GetShuffle = [&](SDValue Op, SDValue &N0, SDValue &N1,
39699 SmallVectorImpl<int> &ShuffleMask) {
39700 if (Op.getOpcode() == ISD::VECTOR_SHUFFLE) {
39701 if (!Op.getOperand(0).isUndef())
39702 N0 = Op.getOperand(0);
39703 if (!Op.getOperand(1).isUndef())
39704 N1 = Op.getOperand(1);
39705 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
39706 ShuffleMask.append(Mask.begin(), Mask.end());
39707 return;
39708 }
39709 bool UseSubVector = false;
39710 if (Op.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
39711 Op.getOperand(0).getValueType().is256BitVector() &&
39712 llvm::isNullConstant(Op.getOperand(1))) {
39713 Op = Op.getOperand(0);
39714 UseSubVector = true;
39715 }
39716 bool IsUnary;
39717 SmallVector<SDValue, 2> SrcOps;
39718 SmallVector<int, 16> SrcShuffleMask;
39719 SDValue BC = peekThroughBitcasts(Op);
39720 if (isTargetShuffle(BC.getOpcode()) &&
39721 getTargetShuffleMask(BC.getNode(), BC.getSimpleValueType(), false,
39722 SrcOps, SrcShuffleMask, IsUnary)) {
39723 if (!UseSubVector && SrcShuffleMask.size() == NumElts &&
39724 SrcOps.size() <= 2) {
39725 N0 = SrcOps.size() > 0 ? SrcOps[0] : SDValue();
39726 N1 = SrcOps.size() > 1 ? SrcOps[1] : SDValue();
39727 ShuffleMask.append(SrcShuffleMask.begin(), SrcShuffleMask.end());
39728 }
39729 if (UseSubVector && (SrcShuffleMask.size() == (NumElts * 2)) &&
39730 SrcOps.size() == 1) {
39731 N0 = extract128BitVector(SrcOps[0], 0, DAG, SDLoc(Op));
39732 N1 = extract128BitVector(SrcOps[0], NumElts, DAG, SDLoc(Op));
39733 ArrayRef<int> Mask = ArrayRef<int>(SrcShuffleMask).slice(0, NumElts);
39734 ShuffleMask.append(Mask.begin(), Mask.end());
39735 }
39736 }
39737 };
39738
39739 // View LHS in the form
39740 // LHS = VECTOR_SHUFFLE A, B, LMask
39741 // If LHS is not a shuffle, then pretend it is the identity shuffle:
39742 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
39743 // NOTE: A default initialized SDValue represents an UNDEF of type VT.
39744 SDValue A, B;
39745 SmallVector<int, 16> LMask;
39746 GetShuffle(LHS, A, B, LMask);
39747
39748 // Likewise, view RHS in the form
39749 // RHS = VECTOR_SHUFFLE C, D, RMask
39750 SDValue C, D;
39751 SmallVector<int, 16> RMask;
39752 GetShuffle(RHS, C, D, RMask);
39753
39754 // At least one of the operands should be a vector shuffle.
39755 unsigned NumShuffles = (LMask.empty() ? 0 : 1) + (RMask.empty() ? 0 : 1);
39756 if (NumShuffles == 0)
39757 return false;
39758
39759 if (LMask.empty()) {
39760 A = LHS;
39761 for (unsigned i = 0; i != NumElts; ++i)
39762 LMask.push_back(i);
39763 }
39764
39765 if (RMask.empty()) {
39766 C = RHS;
39767 for (unsigned i = 0; i != NumElts; ++i)
39768 RMask.push_back(i);
39769 }
39770
39771 // If A and B occur in reverse order in RHS, then canonicalize by commuting
39772 // RHS operands and shuffle mask.
39773 if (A != C) {
39774 std::swap(C, D);
39775 ShuffleVectorSDNode::commuteMask(RMask);
39776 }
39777 // Check that the shuffles are both shuffling the same vectors.
39778 if (!(A == C && B == D))
39779 return false;
39780
39781 // LHS and RHS are now:
39782 // LHS = shuffle A, B, LMask
39783 // RHS = shuffle A, B, RMask
39784 // Check that the masks correspond to performing a horizontal operation.
39785 // AVX defines horizontal add/sub to operate independently on 128-bit lanes,
39786 // so we just repeat the inner loop if this is a 256-bit op.
39787 unsigned Num128BitChunks = VT.getSizeInBits() / 128;
39788 unsigned NumEltsPer128BitChunk = NumElts / Num128BitChunks;
39789 assert((NumEltsPer128BitChunk % 2 == 0) &&(((NumEltsPer128BitChunk % 2 == 0) && "Vector type should have an even number of elements in each lane"
) ? static_cast<void> (0) : __assert_fail ("(NumEltsPer128BitChunk % 2 == 0) && \"Vector type should have an even number of elements in each lane\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 39790, __PRETTY_FUNCTION__))
39790 "Vector type should have an even number of elements in each lane")(((NumEltsPer128BitChunk % 2 == 0) && "Vector type should have an even number of elements in each lane"
) ? static_cast<void> (0) : __assert_fail ("(NumEltsPer128BitChunk % 2 == 0) && \"Vector type should have an even number of elements in each lane\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 39790, __PRETTY_FUNCTION__))
;
39791 for (unsigned j = 0; j != NumElts; j += NumEltsPer128BitChunk) {
39792 for (unsigned i = 0; i != NumEltsPer128BitChunk; ++i) {
39793 // Ignore undefined components.
39794 int LIdx = LMask[i + j], RIdx = RMask[i + j];
39795 if (LIdx < 0 || RIdx < 0 ||
39796 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
39797 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
39798 continue;
39799
39800 // The low half of the 128-bit result must choose from A.
39801 // The high half of the 128-bit result must choose from B,
39802 // unless B is undef. In that case, we are always choosing from A.
39803 unsigned NumEltsPer64BitChunk = NumEltsPer128BitChunk / 2;
39804 unsigned Src = B.getNode() ? i >= NumEltsPer64BitChunk : 0;
39805
39806 // Check that successive elements are being operated on. If not, this is
39807 // not a horizontal operation.
39808 int Index = 2 * (i % NumEltsPer64BitChunk) + NumElts * Src + j;
39809 if (!(LIdx == Index && RIdx == Index + 1) &&
39810 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
39811 return false;
39812 }
39813 }
39814
39815 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
39816 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
39817
39818 if (!shouldUseHorizontalOp(LHS == RHS && NumShuffles < 2, DAG, Subtarget))
39819 return false;
39820
39821 LHS = DAG.getBitcast(VT, LHS);
39822 RHS = DAG.getBitcast(VT, RHS);
39823 return true;
39824}
39825
39826/// Do target-specific dag combines on floating-point adds/subs.
39827static SDValue combineFaddFsub(SDNode *N, SelectionDAG &DAG,
39828 const X86Subtarget &Subtarget) {
39829 EVT VT = N->getValueType(0);
39830 SDValue LHS = N->getOperand(0);
39831 SDValue RHS = N->getOperand(1);
39832 bool IsFadd = N->getOpcode() == ISD::FADD;
39833 auto HorizOpcode = IsFadd ? X86ISD::FHADD : X86ISD::FHSUB;
39834 assert((IsFadd || N->getOpcode() == ISD::FSUB) && "Wrong opcode")(((IsFadd || N->getOpcode() == ISD::FSUB) && "Wrong opcode"
) ? static_cast<void> (0) : __assert_fail ("(IsFadd || N->getOpcode() == ISD::FSUB) && \"Wrong opcode\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 39834, __PRETTY_FUNCTION__))
;
39835
39836 // Try to synthesize horizontal add/sub from adds/subs of shuffles.
39837 if (((Subtarget.hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
39838 (Subtarget.hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
39839 isHorizontalBinOp(LHS, RHS, DAG, Subtarget, IsFadd))
39840 return DAG.getNode(HorizOpcode, SDLoc(N), VT, LHS, RHS);
39841
39842 return SDValue();
39843}
39844
39845/// Attempt to pre-truncate inputs to arithmetic ops if it will simplify
39846/// the codegen.
39847/// e.g. TRUNC( BINOP( X, Y ) ) --> BINOP( TRUNC( X ), TRUNC( Y ) )
39848/// TODO: This overlaps with the generic combiner's visitTRUNCATE. Remove
39849/// anything that is guaranteed to be transformed by DAGCombiner.
39850static SDValue combineTruncatedArithmetic(SDNode *N, SelectionDAG &DAG,
39851 const X86Subtarget &Subtarget,
39852 const SDLoc &DL) {
39853 assert(N->getOpcode() == ISD::TRUNCATE && "Wrong opcode")((N->getOpcode() == ISD::TRUNCATE && "Wrong opcode"
) ? static_cast<void> (0) : __assert_fail ("N->getOpcode() == ISD::TRUNCATE && \"Wrong opcode\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 39853, __PRETTY_FUNCTION__))
;
39854 SDValue Src = N->getOperand(0);
39855 unsigned SrcOpcode = Src.getOpcode();
39856 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
39857
39858 EVT VT = N->getValueType(0);
39859 EVT SrcVT = Src.getValueType();
39860
39861 auto IsFreeTruncation = [VT](SDValue Op) {
39862 unsigned TruncSizeInBits = VT.getScalarSizeInBits();
39863
39864 // See if this has been extended from a smaller/equal size to
39865 // the truncation size, allowing a truncation to combine with the extend.
39866 unsigned Opcode = Op.getOpcode();
39867 if ((Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND ||
39868 Opcode == ISD::ZERO_EXTEND) &&
39869 Op.getOperand(0).getScalarValueSizeInBits() <= TruncSizeInBits)
39870 return true;
39871
39872 // See if this is a single use constant which can be constant folded.
39873 // NOTE: We don't peek throught bitcasts here because there is currently
39874 // no support for constant folding truncate+bitcast+vector_of_constants. So
39875 // we'll just send up with a truncate on both operands which will
39876 // get turned back into (truncate (binop)) causing an infinite loop.
39877 return ISD::isBuildVectorOfConstantSDNodes(Op.getNode());
39878 };
39879
39880 auto TruncateArithmetic = [&](SDValue N0, SDValue N1) {
39881 SDValue Trunc0 = DAG.getNode(ISD::TRUNCATE, DL, VT, N0);
39882 SDValue Trunc1 = DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
39883 return DAG.getNode(SrcOpcode, DL, VT, Trunc0, Trunc1);
39884 };
39885
39886 // Don't combine if the operation has other uses.
39887 if (!Src.hasOneUse())
39888 return SDValue();
39889
39890 // Only support vector truncation for now.
39891 // TODO: i64 scalar math would benefit as well.
39892 if (!VT.isVector())
39893 return SDValue();
39894
39895 // In most cases its only worth pre-truncating if we're only facing the cost
39896 // of one truncation.
39897 // i.e. if one of the inputs will constant fold or the input is repeated.
39898 switch (SrcOpcode) {
39899 case ISD::AND:
39900 case ISD::XOR:
39901 case ISD::OR: {
39902 SDValue Op0 = Src.getOperand(0);
39903 SDValue Op1 = Src.getOperand(1);
39904 if (TLI.isOperationLegalOrPromote(SrcOpcode, VT) &&
39905 (Op0 == Op1 || IsFreeTruncation(Op0) || IsFreeTruncation(Op1)))
39906 return TruncateArithmetic(Op0, Op1);
39907 break;
39908 }
39909
39910 case ISD::MUL:
39911 // X86 is rubbish at scalar and vector i64 multiplies (until AVX512DQ) - its
39912 // better to truncate if we have the chance.
39913 if (SrcVT.getScalarType() == MVT::i64 &&
39914 TLI.isOperationLegal(SrcOpcode, VT) &&
39915 !TLI.isOperationLegal(SrcOpcode, SrcVT))
39916 return TruncateArithmetic(Src.getOperand(0), Src.getOperand(1));
39917 LLVM_FALLTHROUGH[[clang::fallthrough]];
39918 case ISD::ADD: {
39919 SDValue Op0 = Src.getOperand(0);
39920 SDValue Op1 = Src.getOperand(1);
39921 if (TLI.isOperationLegal(SrcOpcode, VT) &&
39922 (Op0 == Op1 || IsFreeTruncation(Op0) || IsFreeTruncation(Op1)))
39923 return TruncateArithmetic(Op0, Op1);
39924 break;
39925 }
39926 case ISD::SUB: {
39927 // TODO: ISD::SUB We are conservative and require both sides to be freely
39928 // truncatable to avoid interfering with combineSubToSubus.
39929 SDValue Op0 = Src.getOperand(0);
39930 SDValue Op1 = Src.getOperand(1);
39931 if (TLI.isOperationLegal(SrcOpcode, VT) &&
39932 (Op0 == Op1 || (IsFreeTruncation(Op0) && IsFreeTruncation(Op1))))
39933 return TruncateArithmetic(Op0, Op1);
39934 break;
39935 }
39936 }
39937
39938 return SDValue();
39939}
39940
39941/// Truncate using ISD::AND mask and X86ISD::PACKUS.
39942/// e.g. trunc <8 x i32> X to <8 x i16> -->
39943/// MaskX = X & 0xffff (clear high bits to prevent saturation)
39944/// packus (extract_subv MaskX, 0), (extract_subv MaskX, 1)
39945static SDValue combineVectorTruncationWithPACKUS(SDNode *N, const SDLoc &DL,
39946 const X86Subtarget &Subtarget,
39947 SelectionDAG &DAG) {
39948 SDValue In = N->getOperand(0);
39949 EVT InVT = In.getValueType();
39950 EVT OutVT = N->getValueType(0);
39951
39952 APInt Mask = APInt::getLowBitsSet(InVT.getScalarSizeInBits(),
39953 OutVT.getScalarSizeInBits());
39954 In = DAG.getNode(ISD::AND, DL, InVT, In, DAG.getConstant(Mask, DL, InVT));
39955 return truncateVectorWithPACK(X86ISD::PACKUS, OutVT, In, DL, DAG, Subtarget);
39956}
39957
39958/// Truncate a group of v4i32 into v8i16 using X86ISD::PACKSS.
39959static SDValue combineVectorTruncationWithPACKSS(SDNode *N, const SDLoc &DL,
39960 const X86Subtarget &Subtarget,
39961 SelectionDAG &DAG) {
39962 SDValue In = N->getOperand(0);
39963 EVT InVT = In.getValueType();
39964 EVT OutVT = N->getValueType(0);
39965 In = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, InVT, In,
39966 DAG.getValueType(OutVT));
39967 return truncateVectorWithPACK(X86ISD::PACKSS, OutVT, In, DL, DAG, Subtarget);
39968}
39969
39970/// This function transforms truncation from vXi32/vXi64 to vXi8/vXi16 into
39971/// X86ISD::PACKUS/X86ISD::PACKSS operations. We do it here because after type
39972/// legalization the truncation will be translated into a BUILD_VECTOR with each
39973/// element that is extracted from a vector and then truncated, and it is
39974/// difficult to do this optimization based on them.
39975static SDValue combineVectorTruncation(SDNode *N, SelectionDAG &DAG,
39976 const X86Subtarget &Subtarget) {
39977 EVT OutVT = N->getValueType(0);
39978 if (!OutVT.isVector())
39979 return SDValue();
39980
39981 SDValue In = N->getOperand(0);
39982 if (!In.getValueType().isSimple())
39983 return SDValue();
39984
39985 EVT InVT = In.getValueType();
39986 unsigned NumElems = OutVT.getVectorNumElements();
39987
39988 // TODO: On AVX2, the behavior of X86ISD::PACKUS is different from that on
39989 // SSE2, and we need to take care of it specially.
39990 // AVX512 provides vpmovdb.
39991 if (!Subtarget.hasSSE2() || Subtarget.hasAVX2())
39992 return SDValue();
39993
39994 EVT OutSVT = OutVT.getVectorElementType();
39995 EVT InSVT = InVT.getVectorElementType();
39996 if (!((InSVT == MVT::i32 || InSVT == MVT::i64) &&
39997 (OutSVT == MVT::i8 || OutSVT == MVT::i16) && isPowerOf2_32(NumElems) &&
39998 NumElems >= 8))
39999 return SDValue();
40000
40001 // SSSE3's pshufb results in less instructions in the cases below.
40002 if (Subtarget.hasSSSE3() && NumElems == 8 &&
40003 ((OutSVT == MVT::i8 && InSVT != MVT::i64) ||
40004 (InSVT == MVT::i32 && OutSVT == MVT::i16)))
40005 return SDValue();
40006
40007 SDLoc DL(N);
40008 // SSE2 provides PACKUS for only 2 x v8i16 -> v16i8 and SSE4.1 provides PACKUS
40009 // for 2 x v4i32 -> v8i16. For SSSE3 and below, we need to use PACKSS to
40010 // truncate 2 x v4i32 to v8i16.
40011 if (Subtarget.hasSSE41() || OutSVT == MVT::i8)
40012 return combineVectorTruncationWithPACKUS(N, DL, Subtarget, DAG);
40013 if (InSVT == MVT::i32)
40014 return combineVectorTruncationWithPACKSS(N, DL, Subtarget, DAG);
40015
40016 return SDValue();
40017}
40018
40019/// This function transforms vector truncation of 'extended sign-bits' or
40020/// 'extended zero-bits' values.
40021/// vXi16/vXi32/vXi64 to vXi8/vXi16/vXi32 into X86ISD::PACKSS/PACKUS operations.
40022static SDValue combineVectorSignBitsTruncation(SDNode *N, const SDLoc &DL,
40023 SelectionDAG &DAG,
40024 const X86Subtarget &Subtarget) {
40025 // Requires SSE2 but AVX512 has fast truncate.
40026 if (!Subtarget.hasSSE2() || Subtarget.hasAVX512())
40027 return SDValue();
40028
40029 if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple())
40030 return SDValue();
40031
40032 SDValue In = N->getOperand(0);
40033 if (!In.getValueType().isSimple())
40034 return SDValue();
40035
40036 MVT VT = N->getValueType(0).getSimpleVT();
40037 MVT SVT = VT.getScalarType();
40038
40039 MVT InVT = In.getValueType().getSimpleVT();
40040 MVT InSVT = InVT.getScalarType();
40041
40042 // Check we have a truncation suited for PACKSS/PACKUS.
40043 if (!VT.is128BitVector() && !VT.is256BitVector())
40044 return SDValue();
40045 if (SVT != MVT::i8 && SVT != MVT::i16 && SVT != MVT::i32)
40046 return SDValue();
40047 if (InSVT != MVT::i16 && InSVT != MVT::i32 && InSVT != MVT::i64)
40048 return SDValue();
40049
40050 unsigned NumPackedSignBits = std::min<unsigned>(SVT.getSizeInBits(), 16);
40051 unsigned NumPackedZeroBits = Subtarget.hasSSE41() ? NumPackedSignBits : 8;
40052
40053 // Use PACKUS if the input has zero-bits that extend all the way to the
40054 // packed/truncated value. e.g. masks, zext_in_reg, etc.
40055 KnownBits Known = DAG.computeKnownBits(In);
40056 unsigned NumLeadingZeroBits = Known.countMinLeadingZeros();
40057 if (NumLeadingZeroBits >= (InSVT.getSizeInBits() - NumPackedZeroBits))
40058 return truncateVectorWithPACK(X86ISD::PACKUS, VT, In, DL, DAG, Subtarget);
40059
40060 // Use PACKSS if the input has sign-bits that extend all the way to the
40061 // packed/truncated value. e.g. Comparison result, sext_in_reg, etc.
40062 unsigned NumSignBits = DAG.ComputeNumSignBits(In);
40063 if (NumSignBits > (InSVT.getSizeInBits() - NumPackedSignBits))
40064 return truncateVectorWithPACK(X86ISD::PACKSS, VT, In, DL, DAG, Subtarget);
40065
40066 return SDValue();
40067}
40068
40069// Try to form a MULHU or MULHS node by looking for
40070// (trunc (srl (mul ext, ext), 16))
40071// TODO: This is X86 specific because we want to be able to handle wide types
40072// before type legalization. But we can only do it if the vector will be
40073// legalized via widening/splitting. Type legalization can't handle promotion
40074// of a MULHU/MULHS. There isn't a way to convey this to the generic DAG
40075// combiner.
40076static SDValue combinePMULH(SDValue Src, EVT VT, const SDLoc &DL,
40077 SelectionDAG &DAG, const X86Subtarget &Subtarget) {
40078 // First instruction should be a right shift of a multiply.
40079 if (Src.getOpcode() != ISD::SRL ||
40080 Src.getOperand(0).getOpcode() != ISD::MUL)
40081 return SDValue();
40082
40083 if (!Subtarget.hasSSE2())
40084 return SDValue();
40085
40086 // Only handle vXi16 types that are at least 128-bits unless they will be
40087 // widened.
40088 if (!VT.isVector() || VT.getVectorElementType() != MVT::i16 ||
40089 (!ExperimentalVectorWideningLegalization &&
40090 VT.getVectorNumElements() < 8))
40091 return SDValue();
40092
40093 // Input type should be vXi32.
40094 EVT InVT = Src.getValueType();
40095 if (InVT.getVectorElementType() != MVT::i32)
40096 return SDValue();
40097
40098 // Need a shift by 16.
40099 APInt ShiftAmt;
40100 if (!ISD::isConstantSplatVector(Src.getOperand(1).getNode(), ShiftAmt) ||
40101 ShiftAmt != 16)
40102 return SDValue();
40103
40104 SDValue LHS = Src.getOperand(0).getOperand(0);
40105 SDValue RHS = Src.getOperand(0).getOperand(1);
40106
40107 unsigned ExtOpc = LHS.getOpcode();
40108 if ((ExtOpc != ISD::SIGN_EXTEND && ExtOpc != ISD::ZERO_EXTEND) ||
40109 RHS.getOpcode() != ExtOpc)
40110 return SDValue();
40111
40112 // Peek through the extends.
40113 LHS = LHS.getOperand(0);
40114 RHS = RHS.getOperand(0);
40115
40116 // Ensure the input types match.
40117 if (LHS.getValueType() != VT || RHS.getValueType() != VT)
40118 return SDValue();
40119
40120 unsigned Opc = ExtOpc == ISD::SIGN_EXTEND ? ISD::MULHS : ISD::MULHU;
40121 return DAG.getNode(Opc, DL, VT, LHS, RHS);
40122}
40123
40124// Attempt to match PMADDUBSW, which multiplies corresponding unsigned bytes
40125// from one vector with signed bytes from another vector, adds together
40126// adjacent pairs of 16-bit products, and saturates the result before
40127// truncating to 16-bits.
40128//
40129// Which looks something like this:
40130// (i16 (ssat (add (mul (zext (even elts (i8 A))), (sext (even elts (i8 B)))),
40131// (mul (zext (odd elts (i8 A)), (sext (odd elts (i8 B))))))))
40132static SDValue detectPMADDUBSW(SDValue In, EVT VT, SelectionDAG &DAG,
40133 const X86Subtarget &Subtarget,
40134 const SDLoc &DL) {
40135 if (!VT.isVector() || !Subtarget.hasSSSE3())
40136 return SDValue();
40137
40138 unsigned NumElems = VT.getVectorNumElements();
40139 EVT ScalarVT = VT.getVectorElementType();
40140 if (ScalarVT != MVT::i16 || NumElems < 8 || !isPowerOf2_32(NumElems))
40141 return SDValue();
40142
40143 SDValue SSatVal = detectSSatPattern(In, VT);
40144 if (!SSatVal || SSatVal.getOpcode() != ISD::ADD)
40145 return SDValue();
40146
40147 // Ok this is a signed saturation of an ADD. See if this ADD is adding pairs
40148 // of multiplies from even/odd elements.
40149 SDValue N0 = SSatVal.getOperand(0);
40150 SDValue N1 = SSatVal.getOperand(1);
40151
40152 if (N0.getOpcode() != ISD::MUL || N1.getOpcode() != ISD::MUL)
40153 return SDValue();
40154
40155 SDValue N00 = N0.getOperand(0);
40156 SDValue N01 = N0.getOperand(1);
40157 SDValue N10 = N1.getOperand(0);
40158 SDValue N11 = N1.getOperand(1);
40159
40160 // TODO: Handle constant vectors and use knownbits/computenumsignbits?
40161 // Canonicalize zero_extend to LHS.
40162 if (N01.getOpcode() == ISD::ZERO_EXTEND)
40163 std::swap(N00, N01);
40164 if (N11.getOpcode() == ISD::ZERO_EXTEND)
40165 std::swap(N10, N11);
40166
40167 // Ensure we have a zero_extend and a sign_extend.
40168 if (N00.getOpcode() != ISD::ZERO_EXTEND ||
40169 N01.getOpcode() != ISD::SIGN_EXTEND ||
40170 N10.getOpcode() != ISD::ZERO_EXTEND ||
40171 N11.getOpcode() != ISD::SIGN_EXTEND)
40172 return SDValue();
40173
40174 // Peek through the extends.
40175 N00 = N00.getOperand(0);
40176 N01 = N01.getOperand(0);
40177 N10 = N10.getOperand(0);
40178 N11 = N11.getOperand(0);
40179
40180 // Ensure the extend is from vXi8.
40181 if (N00.getValueType().getVectorElementType() != MVT::i8 ||
40182 N01.getValueType().getVectorElementType() != MVT::i8 ||
40183 N10.getValueType().getVectorElementType() != MVT::i8 ||
40184 N11.getValueType().getVectorElementType() != MVT::i8)
40185 return SDValue();
40186
40187 // All inputs should be build_vectors.
40188 if (N00.getOpcode() != ISD::BUILD_VECTOR ||
40189 N01.getOpcode() != ISD::BUILD_VECTOR ||
40190 N10.getOpcode() != ISD::BUILD_VECTOR ||
40191 N11.getOpcode() != ISD::BUILD_VECTOR)
40192 return SDValue();
40193
40194 // N00/N10 are zero extended. N01/N11 are sign extended.
40195
40196 // For each element, we need to ensure we have an odd element from one vector
40197 // multiplied by the odd element of another vector and the even element from
40198 // one of the same vectors being multiplied by the even element from the
40199 // other vector. So we need to make sure for each element i, this operator
40200 // is being performed:
40201 // A[2 * i] * B[2 * i] + A[2 * i + 1] * B[2 * i + 1]
40202 SDValue ZExtIn, SExtIn;
40203 for (unsigned i = 0; i != NumElems; ++i) {
40204 SDValue N00Elt = N00.getOperand(i);
40205 SDValue N01Elt = N01.getOperand(i);
40206 SDValue N10Elt = N10.getOperand(i);
40207 SDValue N11Elt = N11.getOperand(i);
40208 // TODO: Be more tolerant to undefs.
40209 if (N00Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
40210 N01Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
40211 N10Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
40212 N11Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
40213 return SDValue();
40214 auto *ConstN00Elt = dyn_cast<ConstantSDNode>(N00Elt.getOperand(1));
40215 auto *ConstN01Elt = dyn_cast<ConstantSDNode>(N01Elt.getOperand(1));
40216 auto *ConstN10Elt = dyn_cast<ConstantSDNode>(N10Elt.getOperand(1));
40217 auto *ConstN11Elt = dyn_cast<ConstantSDNode>(N11Elt.getOperand(1));
40218 if (!ConstN00Elt || !ConstN01Elt || !ConstN10Elt || !ConstN11Elt)
40219 return SDValue();
40220 unsigned IdxN00 = ConstN00Elt->getZExtValue();
40221 unsigned IdxN01 = ConstN01Elt->getZExtValue();
40222 unsigned IdxN10 = ConstN10Elt->getZExtValue();
40223 unsigned IdxN11 = ConstN11Elt->getZExtValue();
40224 // Add is commutative so indices can be reordered.
40225 if (IdxN00 > IdxN10) {
40226 std::swap(IdxN00, IdxN10);
40227 std::swap(IdxN01, IdxN11);
40228 }
40229 // N0 indices be the even element. N1 indices must be the next odd element.
40230 if (IdxN00 != 2 * i || IdxN10 != 2 * i + 1 ||
40231 IdxN01 != 2 * i || IdxN11 != 2 * i + 1)
40232 return SDValue();
40233 SDValue N00In = N00Elt.getOperand(0);
40234 SDValue N01In = N01Elt.getOperand(0);
40235 SDValue N10In = N10Elt.getOperand(0);
40236 SDValue N11In = N11Elt.getOperand(0);
40237 // First time we find an input capture it.
40238 if (!ZExtIn) {
40239 ZExtIn = N00In;
40240 SExtIn = N01In;
40241 }
40242 if (ZExtIn != N00In || SExtIn != N01In ||
40243 ZExtIn != N10In || SExtIn != N11In)
40244 return SDValue();
40245 }
40246
40247 auto PMADDBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
40248 ArrayRef<SDValue> Ops) {
40249 // Shrink by adding truncate nodes and let DAGCombine fold with the
40250 // sources.
40251 EVT InVT = Ops[0].getValueType();
40252 assert(InVT.getScalarType() == MVT::i8 &&((InVT.getScalarType() == MVT::i8 && "Unexpected scalar element type"
) ? static_cast<void> (0) : __assert_fail ("InVT.getScalarType() == MVT::i8 && \"Unexpected scalar element type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 40253, __PRETTY_FUNCTION__))
40253 "Unexpected scalar element type")((InVT.getScalarType() == MVT::i8 && "Unexpected scalar element type"
) ? static_cast<void> (0) : __assert_fail ("InVT.getScalarType() == MVT::i8 && \"Unexpected scalar element type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 40253, __PRETTY_FUNCTION__))
;
40254 assert(InVT == Ops[1].getValueType() && "Operands' types mismatch")((InVT == Ops[1].getValueType() && "Operands' types mismatch"
) ? static_cast<void> (0) : __assert_fail ("InVT == Ops[1].getValueType() && \"Operands' types mismatch\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 40254, __PRETTY_FUNCTION__))
;
40255 EVT ResVT = EVT::getVectorVT(*DAG.getContext(), MVT::i16,
40256 InVT.getVectorNumElements() / 2);
40257 return DAG.getNode(X86ISD::VPMADDUBSW, DL, ResVT, Ops[0], Ops[1]);
40258 };
40259 return SplitOpsAndApply(DAG, Subtarget, DL, VT, { ZExtIn, SExtIn },
40260 PMADDBuilder);
40261}
40262
40263static SDValue combineTruncate(SDNode *N, SelectionDAG &DAG,
40264 const X86Subtarget &Subtarget) {
40265 EVT VT = N->getValueType(0);
40266 SDValue Src = N->getOperand(0);
40267 SDLoc DL(N);
40268
40269 // Attempt to pre-truncate inputs to arithmetic ops instead.
40270 if (SDValue V = combineTruncatedArithmetic(N, DAG, Subtarget, DL))
40271 return V;
40272
40273 // Try to detect AVG pattern first.
40274 if (SDValue Avg = detectAVGPattern(Src, VT, DAG, Subtarget, DL))
40275 return Avg;
40276
40277 // Try to detect PMADD
40278 if (SDValue PMAdd = detectPMADDUBSW(Src, VT, DAG, Subtarget, DL))
40279 return PMAdd;
40280
40281 // Try to combine truncation with signed/unsigned saturation.
40282 if (SDValue Val = combineTruncateWithSat(Src, VT, DL, DAG, Subtarget))
40283 return Val;
40284
40285 // Try to combine PMULHUW/PMULHW for vXi16.
40286 if (SDValue V = combinePMULH(Src, VT, DL, DAG, Subtarget))
40287 return V;
40288
40289 // The bitcast source is a direct mmx result.
40290 // Detect bitcasts between i32 to x86mmx
40291 if (Src.getOpcode() == ISD::BITCAST && VT == MVT::i32) {
40292 SDValue BCSrc = Src.getOperand(0);
40293 if (BCSrc.getValueType() == MVT::x86mmx)
40294 return DAG.getNode(X86ISD::MMX_MOVD2W, DL, MVT::i32, BCSrc);
40295 }
40296
40297 // Try to truncate extended sign/zero bits with PACKSS/PACKUS.
40298 if (SDValue V = combineVectorSignBitsTruncation(N, DL, DAG, Subtarget))
40299 return V;
40300
40301 return combineVectorTruncation(N, DAG, Subtarget);
40302}
40303
40304/// Returns the negated value if the node \p N flips sign of FP value.
40305///
40306/// FP-negation node may have different forms: FNEG(x), FXOR (x, 0x80000000)
40307/// or FSUB(0, x)
40308/// AVX512F does not have FXOR, so FNEG is lowered as
40309/// (bitcast (xor (bitcast x), (bitcast ConstantFP(0x80000000)))).
40310/// In this case we go though all bitcasts.
40311/// This also recognizes splat of a negated value and returns the splat of that
40312/// value.
40313static SDValue isFNEG(SelectionDAG &DAG, SDNode *N) {
40314 if (N->getOpcode() == ISD::FNEG)
40315 return N->getOperand(0);
40316
40317 SDValue Op = peekThroughBitcasts(SDValue(N, 0));
40318 auto VT = Op->getValueType(0);
40319 if (auto SVOp = dyn_cast<ShuffleVectorSDNode>(Op.getNode())) {
40320 // For a VECTOR_SHUFFLE(VEC1, VEC2), if the VEC2 is undef, then the negate
40321 // of this is VECTOR_SHUFFLE(-VEC1, UNDEF). The mask can be anything here.
40322 if (!SVOp->getOperand(1).isUndef())
40323 return SDValue();
40324 if (SDValue NegOp0 = isFNEG(DAG, SVOp->getOperand(0).getNode()))
40325 return DAG.getVectorShuffle(VT, SDLoc(SVOp), NegOp0, DAG.getUNDEF(VT),
40326 SVOp->getMask());
40327 return SDValue();
40328 }
40329 unsigned Opc = Op.getOpcode();
40330 if (Opc == ISD::INSERT_VECTOR_ELT) {
40331 // Negate of INSERT_VECTOR_ELT(UNDEF, V, INDEX) is INSERT_VECTOR_ELT(UNDEF,
40332 // -V, INDEX).
40333 SDValue InsVector = Op.getOperand(0);
40334 SDValue InsVal = Op.getOperand(1);
40335 if (!InsVector.isUndef())
40336 return SDValue();
40337 if (SDValue NegInsVal = isFNEG(DAG, InsVal.getNode()))
40338 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(Op), VT, InsVector,
40339 NegInsVal, Op.getOperand(2));
40340 return SDValue();
40341 }
40342
40343 if (Opc != X86ISD::FXOR && Opc != ISD::XOR && Opc != ISD::FSUB)
40344 return SDValue();
40345
40346 SDValue Op1 = peekThroughBitcasts(Op.getOperand(1));
40347 if (!Op1.getValueType().isFloatingPoint())
40348 return SDValue();
40349
40350 SDValue Op0 = peekThroughBitcasts(Op.getOperand(0));
40351
40352 // For XOR and FXOR, we want to check if constant bits of Op1 are sign bit
40353 // masks. For FSUB, we have to check if constant bits of Op0 are sign bit
40354 // masks and hence we swap the operands.
40355 if (Opc == ISD::FSUB)
40356 std::swap(Op0, Op1);
40357
40358 APInt UndefElts;
40359 SmallVector<APInt, 16> EltBits;
40360 // Extract constant bits and see if they are all sign bit masks. Ignore the
40361 // undef elements.
40362 if (getTargetConstantBitsFromNode(Op1, Op1.getScalarValueSizeInBits(),
40363 UndefElts, EltBits,
40364 /* AllowWholeUndefs */ true,
40365 /* AllowPartialUndefs */ false)) {
40366 for (unsigned I = 0, E = EltBits.size(); I < E; I++)
40367 if (!UndefElts[I] && !EltBits[I].isSignMask())
40368 return SDValue();
40369
40370 return peekThroughBitcasts(Op0);
40371 }
40372
40373 return SDValue();
40374}
40375
40376/// Do target-specific dag combines on floating point negations.
40377static SDValue combineFneg(SDNode *N, SelectionDAG &DAG,
40378 const X86Subtarget &Subtarget) {
40379 EVT OrigVT = N->getValueType(0);
40380 SDValue Arg = isFNEG(DAG, N);
40381 if (!Arg)
40382 return SDValue();
40383
40384 EVT VT = Arg.getValueType();
40385 EVT SVT = VT.getScalarType();
40386 SDLoc DL(N);
40387
40388 // Let legalize expand this if it isn't a legal type yet.
40389 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
40390 return SDValue();
40391
40392 // If we're negating a FMUL node on a target with FMA, then we can avoid the
40393 // use of a constant by performing (-0 - A*B) instead.
40394 // FIXME: Check rounding control flags as well once it becomes available.
40395 if (Arg.getOpcode() == ISD::FMUL && (SVT == MVT::f32 || SVT == MVT::f64) &&
40396 Arg->getFlags().hasNoSignedZeros() && Subtarget.hasAnyFMA()) {
40397 SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
40398 SDValue NewNode = DAG.getNode(X86ISD::FNMSUB, DL, VT, Arg.getOperand(0),
40399 Arg.getOperand(1), Zero);
40400 return DAG.getBitcast(OrigVT, NewNode);
40401 }
40402
40403 // If we're negating an FMA node, then we can adjust the
40404 // instruction to include the extra negation.
40405 unsigned NewOpcode = 0;
40406 if (Arg.hasOneUse() && Subtarget.hasAnyFMA()) {
40407 switch (Arg.getOpcode()) {
40408 case ISD::FMA: NewOpcode = X86ISD::FNMSUB; break;
40409 case X86ISD::FMSUB: NewOpcode = X86ISD::FNMADD; break;
40410 case X86ISD::FNMADD: NewOpcode = X86ISD::FMSUB; break;
40411 case X86ISD::FNMSUB: NewOpcode = ISD::FMA; break;
40412 case X86ISD::FMADD_RND: NewOpcode = X86ISD::FNMSUB_RND; break;
40413 case X86ISD::FMSUB_RND: NewOpcode = X86ISD::FNMADD_RND; break;
40414 case X86ISD::FNMADD_RND: NewOpcode = X86ISD::FMSUB_RND; break;
40415 case X86ISD::FNMSUB_RND: NewOpcode = X86ISD::FMADD_RND; break;
40416 // We can't handle scalar intrinsic node here because it would only
40417 // invert one element and not the whole vector. But we could try to handle
40418 // a negation of the lower element only.
40419 }
40420 }
40421 if (NewOpcode)
40422 return DAG.getBitcast(OrigVT, DAG.getNode(NewOpcode, DL, VT,
40423 Arg.getNode()->ops()));
40424
40425 return SDValue();
40426}
40427
40428static SDValue lowerX86FPLogicOp(SDNode *N, SelectionDAG &DAG,
40429 const X86Subtarget &Subtarget) {
40430 MVT VT = N->getSimpleValueType(0);
40431 // If we have integer vector types available, use the integer opcodes.
40432 if (!VT.isVector() || !Subtarget.hasSSE2())
40433 return SDValue();
40434
40435 SDLoc dl(N);
40436
40437 unsigned IntBits = VT.getScalarSizeInBits();
40438 MVT IntSVT = MVT::getIntegerVT(IntBits);
40439 MVT IntVT = MVT::getVectorVT(IntSVT, VT.getSizeInBits() / IntBits);
40440
40441 SDValue Op0 = DAG.getBitcast(IntVT, N->getOperand(0));
40442 SDValue Op1 = DAG.getBitcast(IntVT, N->getOperand(1));
40443 unsigned IntOpcode;
40444 switch (N->getOpcode()) {
40445 default: llvm_unreachable("Unexpected FP logic op")::llvm::llvm_unreachable_internal("Unexpected FP logic op", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 40445)
;
40446 case X86ISD::FOR: IntOpcode = ISD::OR; break;
40447 case X86ISD::FXOR: IntOpcode = ISD::XOR; break;
40448 case X86ISD::FAND: IntOpcode = ISD::AND; break;
40449 case X86ISD::FANDN: IntOpcode = X86ISD::ANDNP; break;
40450 }
40451 SDValue IntOp = DAG.getNode(IntOpcode, dl, IntVT, Op0, Op1);
40452 return DAG.getBitcast(VT, IntOp);
40453}
40454
40455
40456/// Fold a xor(setcc cond, val), 1 --> setcc (inverted(cond), val)
40457static SDValue foldXor1SetCC(SDNode *N, SelectionDAG &DAG) {
40458 if (N->getOpcode() != ISD::XOR)
40459 return SDValue();
40460
40461 SDValue LHS = N->getOperand(0);
40462 auto *RHSC = dyn_cast<ConstantSDNode>(N->getOperand(1));
40463 if (!RHSC || RHSC->getZExtValue() != 1 || LHS->getOpcode() != X86ISD::SETCC)
40464 return SDValue();
40465
40466 X86::CondCode NewCC = X86::GetOppositeBranchCondition(
40467 X86::CondCode(LHS->getConstantOperandVal(0)));
40468 SDLoc DL(N);
40469 return getSETCC(NewCC, LHS->getOperand(1), DL, DAG);
40470}
40471
40472static SDValue combineXor(SDNode *N, SelectionDAG &DAG,
40473 TargetLowering::DAGCombinerInfo &DCI,
40474 const X86Subtarget &Subtarget) {
40475 // If this is SSE1 only convert to FXOR to avoid scalarization.
40476 if (Subtarget.hasSSE1() && !Subtarget.hasSSE2() &&
40477 N->getValueType(0) == MVT::v4i32) {
40478 return DAG.getBitcast(
40479 MVT::v4i32, DAG.getNode(X86ISD::FXOR, SDLoc(N), MVT::v4f32,
40480 DAG.getBitcast(MVT::v4f32, N->getOperand(0)),
40481 DAG.getBitcast(MVT::v4f32, N->getOperand(1))));
40482 }
40483
40484 if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
40485 return Cmp;
40486
40487 if (DCI.isBeforeLegalizeOps())
40488 return SDValue();
40489
40490 if (SDValue SetCC = foldXor1SetCC(N, DAG))
40491 return SetCC;
40492
40493 if (SDValue RV = foldXorTruncShiftIntoCmp(N, DAG))
40494 return RV;
40495
40496 if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
40497 return FPLogic;
40498
40499 return combineFneg(N, DAG, Subtarget);
40500}
40501
40502static SDValue combineBEXTR(SDNode *N, SelectionDAG &DAG,
40503 TargetLowering::DAGCombinerInfo &DCI,
40504 const X86Subtarget &Subtarget) {
40505 SDValue Op0 = N->getOperand(0);
40506 SDValue Op1 = N->getOperand(1);
40507 EVT VT = N->getValueType(0);
40508 unsigned NumBits = VT.getSizeInBits();
40509
40510 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
40511
40512 // TODO - Constant Folding.
40513 if (auto *Cst1 = dyn_cast<ConstantSDNode>(Op1)) {
40514 // Reduce Cst1 to the bottom 16-bits.
40515 // NOTE: SimplifyDemandedBits won't do this for constants.
40516 const APInt &Val1 = Cst1->getAPIntValue();
40517 APInt MaskedVal1 = Val1 & 0xFFFF;
40518 if (MaskedVal1 != Val1)
40519 return DAG.getNode(X86ISD::BEXTR, SDLoc(N), VT, Op0,
40520 DAG.getConstant(MaskedVal1, SDLoc(N), VT));
40521 }
40522
40523 // Only bottom 16-bits of the control bits are required.
40524 APInt DemandedMask(APInt::getLowBitsSet(NumBits, 16));
40525 if (TLI.SimplifyDemandedBits(Op1, DemandedMask, DCI))
40526 return SDValue(N, 0);
40527
40528 return SDValue();
40529}
40530
40531static bool isNullFPScalarOrVectorConst(SDValue V) {
40532 return isNullFPConstant(V) || ISD::isBuildVectorAllZeros(V.getNode());
40533}
40534
40535/// If a value is a scalar FP zero or a vector FP zero (potentially including
40536/// undefined elements), return a zero constant that may be used to fold away
40537/// that value. In the case of a vector, the returned constant will not contain
40538/// undefined elements even if the input parameter does. This makes it suitable
40539/// to be used as a replacement operand with operations (eg, bitwise-and) where
40540/// an undef should not propagate.
40541static SDValue getNullFPConstForNullVal(SDValue V, SelectionDAG &DAG,
40542 const X86Subtarget &Subtarget) {
40543 if (!isNullFPScalarOrVectorConst(V))
40544 return SDValue();
40545
40546 if (V.getValueType().isVector())
40547 return getZeroVector(V.getSimpleValueType(), Subtarget, DAG, SDLoc(V));
40548
40549 return V;
40550}
40551
40552static SDValue combineFAndFNotToFAndn(SDNode *N, SelectionDAG &DAG,
40553 const X86Subtarget &Subtarget) {
40554 SDValue N0 = N->getOperand(0);
40555 SDValue N1 = N->getOperand(1);
40556 EVT VT = N->getValueType(0);
40557 SDLoc DL(N);
40558
40559 // Vector types are handled in combineANDXORWithAllOnesIntoANDNP().
40560 if (!((VT == MVT::f32 && Subtarget.hasSSE1()) ||
40561 (VT == MVT::f64 && Subtarget.hasSSE2()) ||
40562 (VT == MVT::v4f32 && Subtarget.hasSSE1() && !Subtarget.hasSSE2())))
40563 return SDValue();
40564
40565 auto isAllOnesConstantFP = [](SDValue V) {
40566 if (V.getSimpleValueType().isVector())
40567 return ISD::isBuildVectorAllOnes(V.getNode());
40568 auto *C = dyn_cast<ConstantFPSDNode>(V);
40569 return C && C->getConstantFPValue()->isAllOnesValue();
40570 };
40571
40572 // fand (fxor X, -1), Y --> fandn X, Y
40573 if (N0.getOpcode() == X86ISD::FXOR && isAllOnesConstantFP(N0.getOperand(1)))
40574 return DAG.getNode(X86ISD::FANDN, DL, VT, N0.getOperand(0), N1);
40575
40576 // fand X, (fxor Y, -1) --> fandn Y, X
40577 if (N1.getOpcode() == X86ISD::FXOR && isAllOnesConstantFP(N1.getOperand(1)))
40578 return DAG.getNode(X86ISD::FANDN, DL, VT, N1.getOperand(0), N0);
40579
40580 return SDValue();
40581}
40582
40583/// Do target-specific dag combines on X86ISD::FAND nodes.
40584static SDValue combineFAnd(SDNode *N, SelectionDAG &DAG,
40585 const X86Subtarget &Subtarget) {
40586 // FAND(0.0, x) -> 0.0
40587 if (SDValue V = getNullFPConstForNullVal(N->getOperand(0), DAG, Subtarget))
40588 return V;
40589
40590 // FAND(x, 0.0) -> 0.0
40591 if (SDValue V = getNullFPConstForNullVal(N->getOperand(1), DAG, Subtarget))
40592 return V;
40593
40594 if (SDValue V = combineFAndFNotToFAndn(N, DAG, Subtarget))
40595 return V;
40596
40597 return lowerX86FPLogicOp(N, DAG, Subtarget);
40598}
40599
40600/// Do target-specific dag combines on X86ISD::FANDN nodes.
40601static SDValue combineFAndn(SDNode *N, SelectionDAG &DAG,
40602 const X86Subtarget &Subtarget) {
40603 // FANDN(0.0, x) -> x
40604 if (isNullFPScalarOrVectorConst(N->getOperand(0)))
40605 return N->getOperand(1);
40606
40607 // FANDN(x, 0.0) -> 0.0
40608 if (SDValue V = getNullFPConstForNullVal(N->getOperand(1), DAG, Subtarget))
40609 return V;
40610
40611 return lowerX86FPLogicOp(N, DAG, Subtarget);
40612}
40613
40614/// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
40615static SDValue combineFOr(SDNode *N, SelectionDAG &DAG,
40616 const X86Subtarget &Subtarget) {
40617 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR)((N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD
::FXOR) ? static_cast<void> (0) : __assert_fail ("N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 40617, __PRETTY_FUNCTION__))
;
40618
40619 // F[X]OR(0.0, x) -> x
40620 if (isNullFPScalarOrVectorConst(N->getOperand(0)))
40621 return N->getOperand(1);
40622
40623 // F[X]OR(x, 0.0) -> x
40624 if (isNullFPScalarOrVectorConst(N->getOperand(1)))
40625 return N->getOperand(0);
40626
40627 if (SDValue NewVal = combineFneg(N, DAG, Subtarget))
40628 return NewVal;
40629
40630 return lowerX86FPLogicOp(N, DAG, Subtarget);
40631}
40632
40633/// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
40634static SDValue combineFMinFMax(SDNode *N, SelectionDAG &DAG) {
40635 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX)((N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD
::FMAX) ? static_cast<void> (0) : __assert_fail ("N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 40635, __PRETTY_FUNCTION__))
;
40636
40637 // Only perform optimizations if UnsafeMath is used.
40638 if (!DAG.getTarget().Options.UnsafeFPMath)
40639 return SDValue();
40640
40641 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
40642 // into FMINC and FMAXC, which are Commutative operations.
40643 unsigned NewOp = 0;
40644 switch (N->getOpcode()) {
40645 default: llvm_unreachable("unknown opcode")::llvm::llvm_unreachable_internal("unknown opcode", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 40645)
;
40646 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
40647 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
40648 }
40649
40650 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
40651 N->getOperand(0), N->getOperand(1));
40652}
40653
40654static SDValue combineFMinNumFMaxNum(SDNode *N, SelectionDAG &DAG,
40655 const X86Subtarget &Subtarget) {
40656 if (Subtarget.useSoftFloat())
40657 return SDValue();
40658
40659 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
40660
40661 EVT VT = N->getValueType(0);
40662 if (!((Subtarget.hasSSE1() && VT == MVT::f32) ||
40663 (Subtarget.hasSSE2() && VT == MVT::f64) ||
40664 (VT.isVector() && TLI.isTypeLegal(VT))))
40665 return SDValue();
40666
40667 SDValue Op0 = N->getOperand(0);
40668 SDValue Op1 = N->getOperand(1);
40669 SDLoc DL(N);
40670 auto MinMaxOp = N->getOpcode() == ISD::FMAXNUM ? X86ISD::FMAX : X86ISD::FMIN;
40671
40672 // If we don't have to respect NaN inputs, this is a direct translation to x86
40673 // min/max instructions.
40674 if (DAG.getTarget().Options.NoNaNsFPMath || N->getFlags().hasNoNaNs())
40675 return DAG.getNode(MinMaxOp, DL, VT, Op0, Op1, N->getFlags());
40676
40677 // If one of the operands is known non-NaN use the native min/max instructions
40678 // with the non-NaN input as second operand.
40679 if (DAG.isKnownNeverNaN(Op1))
40680 return DAG.getNode(MinMaxOp, DL, VT, Op0, Op1, N->getFlags());
40681 if (DAG.isKnownNeverNaN(Op0))
40682 return DAG.getNode(MinMaxOp, DL, VT, Op1, Op0, N->getFlags());
40683
40684 // If we have to respect NaN inputs, this takes at least 3 instructions.
40685 // Favor a library call when operating on a scalar and minimizing code size.
40686 if (!VT.isVector() && DAG.getMachineFunction().getFunction().hasMinSize())
40687 return SDValue();
40688
40689 EVT SetCCType = TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
40690 VT);
40691
40692 // There are 4 possibilities involving NaN inputs, and these are the required
40693 // outputs:
40694 // Op1
40695 // Num NaN
40696 // ----------------
40697 // Num | Max | Op0 |
40698 // Op0 ----------------
40699 // NaN | Op1 | NaN |
40700 // ----------------
40701 //
40702 // The SSE FP max/min instructions were not designed for this case, but rather
40703 // to implement:
40704 // Min = Op1 < Op0 ? Op1 : Op0
40705 // Max = Op1 > Op0 ? Op1 : Op0
40706 //
40707 // So they always return Op0 if either input is a NaN. However, we can still
40708 // use those instructions for fmaxnum by selecting away a NaN input.
40709
40710 // If either operand is NaN, the 2nd source operand (Op0) is passed through.
40711 SDValue MinOrMax = DAG.getNode(MinMaxOp, DL, VT, Op1, Op0);
40712 SDValue IsOp0Nan = DAG.getSetCC(DL, SetCCType, Op0, Op0, ISD::SETUO);
40713
40714 // If Op0 is a NaN, select Op1. Otherwise, select the max. If both operands
40715 // are NaN, the NaN value of Op1 is the result.
40716 return DAG.getSelect(DL, VT, IsOp0Nan, Op1, MinOrMax);
40717}
40718
40719static SDValue combineX86INT_TO_FP(SDNode *N, SelectionDAG &DAG,
40720 TargetLowering::DAGCombinerInfo &DCI) {
40721 EVT VT = N->getValueType(0);
40722 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
40723
40724 APInt KnownUndef, KnownZero;
40725 APInt DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements());
40726 if (TLI.SimplifyDemandedVectorElts(SDValue(N, 0), DemandedElts, KnownUndef,
40727 KnownZero, DCI))
40728 return SDValue(N, 0);
40729
40730 return SDValue();
40731}
40732
40733/// Do target-specific dag combines on X86ISD::ANDNP nodes.
40734static SDValue combineAndnp(SDNode *N, SelectionDAG &DAG,
40735 TargetLowering::DAGCombinerInfo &DCI,
40736 const X86Subtarget &Subtarget) {
40737 MVT VT = N->getSimpleValueType(0);
40738
40739 // ANDNP(0, x) -> x
40740 if (ISD::isBuildVectorAllZeros(N->getOperand(0).getNode()))
40741 return N->getOperand(1);
40742
40743 // ANDNP(x, 0) -> 0
40744 if (ISD::isBuildVectorAllZeros(N->getOperand(1).getNode()))
40745 return DAG.getConstant(0, SDLoc(N), VT);
40746
40747 // Turn ANDNP back to AND if input is inverted.
40748 if (VT.isVector() && N->getOperand(0).getOpcode() == ISD::XOR &&
40749 ISD::isBuildVectorAllOnes(N->getOperand(0).getOperand(1).getNode())) {
40750 return DAG.getNode(ISD::AND, SDLoc(N), VT,
40751 N->getOperand(0).getOperand(0), N->getOperand(1));
40752 }
40753
40754 // Attempt to recursively combine a bitmask ANDNP with shuffles.
40755 if (VT.isVector() && (VT.getScalarSizeInBits() % 8) == 0) {
40756 SDValue Op(N, 0);
40757 if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
40758 return Res;
40759 }
40760
40761 return SDValue();
40762}
40763
40764static SDValue combineBT(SDNode *N, SelectionDAG &DAG,
40765 TargetLowering::DAGCombinerInfo &DCI) {
40766 SDValue N0 = N->getOperand(0);
40767 SDValue N1 = N->getOperand(1);
40768
40769 // BT ignores high bits in the bit index operand.
40770 unsigned BitWidth = N1.getValueSizeInBits();
40771 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
40772 if (SDValue DemandedN1 = DAG.GetDemandedBits(N1, DemandedMask))
40773 return DAG.getNode(X86ISD::BT, SDLoc(N), MVT::i32, N0, DemandedN1);
40774
40775 return SDValue();
40776}
40777
40778// Try to combine sext_in_reg of a cmov of constants by extending the constants.
40779static SDValue combineSextInRegCmov(SDNode *N, SelectionDAG &DAG) {
40780 assert(N->getOpcode() == ISD::SIGN_EXTEND_INREG)((N->getOpcode() == ISD::SIGN_EXTEND_INREG) ? static_cast<
void> (0) : __assert_fail ("N->getOpcode() == ISD::SIGN_EXTEND_INREG"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 40780, __PRETTY_FUNCTION__))
;
40781
40782 EVT DstVT = N->getValueType(0);
40783
40784 SDValue N0 = N->getOperand(0);
40785 SDValue N1 = N->getOperand(1);
40786 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
40787
40788 if (ExtraVT != MVT::i8 && ExtraVT != MVT::i16)
40789 return SDValue();
40790
40791 // Look through single use any_extends / truncs.
40792 SDValue IntermediateBitwidthOp;
40793 if ((N0.getOpcode() == ISD::ANY_EXTEND || N0.getOpcode() == ISD::TRUNCATE) &&
40794 N0.hasOneUse()) {
40795 IntermediateBitwidthOp = N0;
40796 N0 = N0.getOperand(0);
40797 }
40798
40799 // See if we have a single use cmov.
40800 if (N0.getOpcode() != X86ISD::CMOV || !N0.hasOneUse())
40801 return SDValue();
40802
40803 SDValue CMovOp0 = N0.getOperand(0);
40804 SDValue CMovOp1 = N0.getOperand(1);
40805
40806 // Make sure both operands are constants.
40807 if (!isa<ConstantSDNode>(CMovOp0.getNode()) ||
40808 !isa<ConstantSDNode>(CMovOp1.getNode()))
40809 return SDValue();
40810
40811 SDLoc DL(N);
40812
40813 // If we looked through an any_extend/trunc above, add one to the constants.
40814 if (IntermediateBitwidthOp) {
40815 unsigned IntermediateOpc = IntermediateBitwidthOp.getOpcode();
40816 CMovOp0 = DAG.getNode(IntermediateOpc, DL, DstVT, CMovOp0);
40817 CMovOp1 = DAG.getNode(IntermediateOpc, DL, DstVT, CMovOp1);
40818 }
40819
40820 CMovOp0 = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, DstVT, CMovOp0, N1);
40821 CMovOp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, DstVT, CMovOp1, N1);
40822
40823 EVT CMovVT = DstVT;
40824 // We do not want i16 CMOV's. Promote to i32 and truncate afterwards.
40825 if (DstVT == MVT::i16) {
40826 CMovVT = MVT::i32;
40827 CMovOp0 = DAG.getNode(ISD::ZERO_EXTEND, DL, CMovVT, CMovOp0);
40828 CMovOp1 = DAG.getNode(ISD::ZERO_EXTEND, DL, CMovVT, CMovOp1);
40829 }
40830
40831 SDValue CMov = DAG.getNode(X86ISD::CMOV, DL, CMovVT, CMovOp0, CMovOp1,
40832 N0.getOperand(2), N0.getOperand(3));
40833
40834 if (CMovVT != DstVT)
40835 CMov = DAG.getNode(ISD::TRUNCATE, DL, DstVT, CMov);
40836
40837 return CMov;
40838}
40839
40840static SDValue combineSignExtendInReg(SDNode *N, SelectionDAG &DAG,
40841 const X86Subtarget &Subtarget) {
40842 assert(N->getOpcode() == ISD::SIGN_EXTEND_INREG)((N->getOpcode() == ISD::SIGN_EXTEND_INREG) ? static_cast<
void> (0) : __assert_fail ("N->getOpcode() == ISD::SIGN_EXTEND_INREG"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 40842, __PRETTY_FUNCTION__))
;
40843
40844 if (SDValue V = combineSextInRegCmov(N, DAG))
40845 return V;
40846
40847 EVT VT = N->getValueType(0);
40848 SDValue N0 = N->getOperand(0);
40849 SDValue N1 = N->getOperand(1);
40850 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
40851 SDLoc dl(N);
40852
40853 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
40854 // both SSE and AVX2 since there is no sign-extended shift right
40855 // operation on a vector with 64-bit elements.
40856 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
40857 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
40858 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
40859 N0.getOpcode() == ISD::SIGN_EXTEND)) {
40860 SDValue N00 = N0.getOperand(0);
40861
40862 // EXTLOAD has a better solution on AVX2,
40863 // it may be replaced with X86ISD::VSEXT node.
40864 if (N00.getOpcode() == ISD::LOAD && Subtarget.hasInt256())
40865 if (!ISD::isNormalLoad(N00.getNode()))
40866 return SDValue();
40867
40868 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
40869 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
40870 N00, N1);
40871 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
40872 }
40873 }
40874 return SDValue();
40875}
40876
40877/// sext(add_nsw(x, C)) --> add(sext(x), C_sext)
40878/// zext(add_nuw(x, C)) --> add(zext(x), C_zext)
40879/// Promoting a sign/zero extension ahead of a no overflow 'add' exposes
40880/// opportunities to combine math ops, use an LEA, or use a complex addressing
40881/// mode. This can eliminate extend, add, and shift instructions.
40882static SDValue promoteExtBeforeAdd(SDNode *Ext, SelectionDAG &DAG,
40883 const X86Subtarget &Subtarget) {
40884 if (Ext->getOpcode() != ISD::SIGN_EXTEND &&
40885 Ext->getOpcode() != ISD::ZERO_EXTEND)
40886 return SDValue();
40887
40888 // TODO: This should be valid for other integer types.
40889 EVT VT = Ext->getValueType(0);
40890 if (VT != MVT::i64)
40891 return SDValue();
40892
40893 SDValue Add = Ext->getOperand(0);
40894 if (Add.getOpcode() != ISD::ADD)
40895 return SDValue();
40896
40897 bool Sext = Ext->getOpcode() == ISD::SIGN_EXTEND;
40898 bool NSW = Add->getFlags().hasNoSignedWrap();
40899 bool NUW = Add->getFlags().hasNoUnsignedWrap();
40900
40901 // We need an 'add nsw' feeding into the 'sext' or 'add nuw' feeding
40902 // into the 'zext'
40903 if ((Sext && !NSW) || (!Sext && !NUW))
40904 return SDValue();
40905
40906 // Having a constant operand to the 'add' ensures that we are not increasing
40907 // the instruction count because the constant is extended for free below.
40908 // A constant operand can also become the displacement field of an LEA.
40909 auto *AddOp1 = dyn_cast<ConstantSDNode>(Add.getOperand(1));
40910 if (!AddOp1)
40911 return SDValue();
40912
40913 // Don't make the 'add' bigger if there's no hope of combining it with some
40914 // other 'add' or 'shl' instruction.
40915 // TODO: It may be profitable to generate simpler LEA instructions in place
40916 // of single 'add' instructions, but the cost model for selecting an LEA
40917 // currently has a high threshold.
40918 bool HasLEAPotential = false;
40919 for (auto *User : Ext->uses()) {
40920 if (User->getOpcode() == ISD::ADD || User->getOpcode() == ISD::SHL) {
40921 HasLEAPotential = true;
40922 break;
40923 }
40924 }
40925 if (!HasLEAPotential)
40926 return SDValue();
40927
40928 // Everything looks good, so pull the '{s|z}ext' ahead of the 'add'.
40929 int64_t AddConstant = Sext ? AddOp1->getSExtValue() : AddOp1->getZExtValue();
40930 SDValue AddOp0 = Add.getOperand(0);
40931 SDValue NewExt = DAG.getNode(Ext->getOpcode(), SDLoc(Ext), VT, AddOp0);
40932 SDValue NewConstant = DAG.getConstant(AddConstant, SDLoc(Add), VT);
40933
40934 // The wider add is guaranteed to not wrap because both operands are
40935 // sign-extended.
40936 SDNodeFlags Flags;
40937 Flags.setNoSignedWrap(NSW);
40938 Flags.setNoUnsignedWrap(NUW);
40939 return DAG.getNode(ISD::ADD, SDLoc(Add), VT, NewExt, NewConstant, Flags);
40940}
40941
40942// If we face {ANY,SIGN,ZERO}_EXTEND that is applied to a CMOV with constant
40943// operands and the result of CMOV is not used anywhere else - promote CMOV
40944// itself instead of promoting its result. This could be beneficial, because:
40945// 1) X86TargetLowering::EmitLoweredSelect later can do merging of two
40946// (or more) pseudo-CMOVs only when they go one-after-another and
40947// getting rid of result extension code after CMOV will help that.
40948// 2) Promotion of constant CMOV arguments is free, hence the
40949// {ANY,SIGN,ZERO}_EXTEND will just be deleted.
40950// 3) 16-bit CMOV encoding is 4 bytes, 32-bit CMOV is 3-byte, so this
40951// promotion is also good in terms of code-size.
40952// (64-bit CMOV is 4-bytes, that's why we don't do 32-bit => 64-bit
40953// promotion).
40954static SDValue combineToExtendCMOV(SDNode *Extend, SelectionDAG &DAG) {
40955 SDValue CMovN = Extend->getOperand(0);
40956 if (CMovN.getOpcode() != X86ISD::CMOV || !CMovN.hasOneUse())
40957 return SDValue();
40958
40959 EVT TargetVT = Extend->getValueType(0);
40960 unsigned ExtendOpcode = Extend->getOpcode();
40961 SDLoc DL(Extend);
40962
40963 EVT VT = CMovN.getValueType();
40964 SDValue CMovOp0 = CMovN.getOperand(0);
40965 SDValue CMovOp1 = CMovN.getOperand(1);
40966
40967 if (!isa<ConstantSDNode>(CMovOp0.getNode()) ||
40968 !isa<ConstantSDNode>(CMovOp1.getNode()))
40969 return SDValue();
40970
40971 // Only extend to i32 or i64.
40972 if (TargetVT != MVT::i32 && TargetVT != MVT::i64)
40973 return SDValue();
40974
40975 // Only extend from i16 unless its a sign_extend from i32. Zext/aext from i32
40976 // are free.
40977 if (VT != MVT::i16 && !(ExtendOpcode == ISD::SIGN_EXTEND && VT == MVT::i32))
40978 return SDValue();
40979
40980 // If this a zero extend to i64, we should only extend to i32 and use a free
40981 // zero extend to finish.
40982 EVT ExtendVT = TargetVT;
40983 if (TargetVT == MVT::i64 && ExtendOpcode != ISD::SIGN_EXTEND)
40984 ExtendVT = MVT::i32;
40985
40986 CMovOp0 = DAG.getNode(ExtendOpcode, DL, ExtendVT, CMovOp0);
40987 CMovOp1 = DAG.getNode(ExtendOpcode, DL, ExtendVT, CMovOp1);
40988
40989 SDValue Res = DAG.getNode(X86ISD::CMOV, DL, ExtendVT, CMovOp0, CMovOp1,
40990 CMovN.getOperand(2), CMovN.getOperand(3));
40991
40992 // Finish extending if needed.
40993 if (ExtendVT != TargetVT)
40994 Res = DAG.getNode(ExtendOpcode, DL, TargetVT, Res);
40995
40996 return Res;
40997}
40998
40999// Convert (vXiY *ext(vXi1 bitcast(iX))) to extend_in_reg(broadcast(iX)).
41000// This is more or less the reverse of combineBitcastvxi1.
41001static SDValue
41002combineToExtendBoolVectorInReg(SDNode *N, SelectionDAG &DAG,
41003 TargetLowering::DAGCombinerInfo &DCI,
41004 const X86Subtarget &Subtarget) {
41005 unsigned Opcode = N->getOpcode();
41006 if (Opcode != ISD::SIGN_EXTEND && Opcode != ISD::ZERO_EXTEND &&
41007 Opcode != ISD::ANY_EXTEND)
41008 return SDValue();
41009 if (!DCI.isBeforeLegalizeOps())
41010 return SDValue();
41011 if (!Subtarget.hasSSE2() || Subtarget.hasAVX512())
41012 return SDValue();
41013
41014 SDValue N0 = N->getOperand(0);
41015 EVT VT = N->getValueType(0);
41016 EVT SVT = VT.getScalarType();
41017 EVT InSVT = N0.getValueType().getScalarType();
41018 unsigned EltSizeInBits = SVT.getSizeInBits();
41019
41020 // Input type must be extending a bool vector (bit-casted from a scalar
41021 // integer) to legal integer types.
41022 if (!VT.isVector())
41023 return SDValue();
41024 if (SVT != MVT::i64 && SVT != MVT::i32 && SVT != MVT::i16 && SVT != MVT::i8)
41025 return SDValue();
41026 if (InSVT != MVT::i1 || N0.getOpcode() != ISD::BITCAST)
41027 return SDValue();
41028
41029 SDValue N00 = N0.getOperand(0);
41030 EVT SclVT = N0.getOperand(0).getValueType();
41031 if (!SclVT.isScalarInteger())
41032 return SDValue();
41033
41034 SDLoc DL(N);
41035 SDValue Vec;
41036 SmallVector<int, 32> ShuffleMask;
41037 unsigned NumElts = VT.getVectorNumElements();
41038 assert(NumElts == SclVT.getSizeInBits() && "Unexpected bool vector size")((NumElts == SclVT.getSizeInBits() && "Unexpected bool vector size"
) ? static_cast<void> (0) : __assert_fail ("NumElts == SclVT.getSizeInBits() && \"Unexpected bool vector size\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 41038, __PRETTY_FUNCTION__))
;
41039
41040 // Broadcast the scalar integer to the vector elements.
41041 if (NumElts > EltSizeInBits) {
41042 // If the scalar integer is greater than the vector element size, then we
41043 // must split it down into sub-sections for broadcasting. For example:
41044 // i16 -> v16i8 (i16 -> v8i16 -> v16i8) with 2 sub-sections.
41045 // i32 -> v32i8 (i32 -> v8i32 -> v32i8) with 4 sub-sections.
41046 assert((NumElts % EltSizeInBits) == 0 && "Unexpected integer scale")(((NumElts % EltSizeInBits) == 0 && "Unexpected integer scale"
) ? static_cast<void> (0) : __assert_fail ("(NumElts % EltSizeInBits) == 0 && \"Unexpected integer scale\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 41046, __PRETTY_FUNCTION__))
;
41047 unsigned Scale = NumElts / EltSizeInBits;
41048 EVT BroadcastVT =
41049 EVT::getVectorVT(*DAG.getContext(), SclVT, EltSizeInBits);
41050 Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, BroadcastVT, N00);
41051 Vec = DAG.getBitcast(VT, Vec);
41052
41053 for (unsigned i = 0; i != Scale; ++i)
41054 ShuffleMask.append(EltSizeInBits, i);
41055 } else {
41056 // For smaller scalar integers, we can simply any-extend it to the vector
41057 // element size (we don't care about the upper bits) and broadcast it to all
41058 // elements.
41059 SDValue Scl = DAG.getAnyExtOrTrunc(N00, DL, SVT);
41060 Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, Scl);
41061 ShuffleMask.append(NumElts, 0);
41062 }
41063 Vec = DAG.getVectorShuffle(VT, DL, Vec, Vec, ShuffleMask);
41064
41065 // Now, mask the relevant bit in each element.
41066 SmallVector<SDValue, 32> Bits;
41067 for (unsigned i = 0; i != NumElts; ++i) {
41068 int BitIdx = (i % EltSizeInBits);
41069 APInt Bit = APInt::getBitsSet(EltSizeInBits, BitIdx, BitIdx + 1);
41070 Bits.push_back(DAG.getConstant(Bit, DL, SVT));
41071 }
41072 SDValue BitMask = DAG.getBuildVector(VT, DL, Bits);
41073 Vec = DAG.getNode(ISD::AND, DL, VT, Vec, BitMask);
41074
41075 // Compare against the bitmask and extend the result.
41076 EVT CCVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1, NumElts);
41077 Vec = DAG.getSetCC(DL, CCVT, Vec, BitMask, ISD::SETEQ);
41078 Vec = DAG.getSExtOrTrunc(Vec, DL, VT);
41079
41080 // For SEXT, this is now done, otherwise shift the result down for
41081 // zero-extension.
41082 if (Opcode == ISD::SIGN_EXTEND)
41083 return Vec;
41084 return DAG.getNode(ISD::SRL, DL, VT, Vec,
41085 DAG.getConstant(EltSizeInBits - 1, DL, VT));
41086}
41087
41088/// Convert a SEXT or ZEXT of a vector to a SIGN_EXTEND_VECTOR_INREG or
41089/// ZERO_EXTEND_VECTOR_INREG, this requires the splitting (or concatenating
41090/// with UNDEFs) of the input to vectors of the same size as the target type
41091/// which then extends the lowest elements.
41092static SDValue combineToExtendVectorInReg(SDNode *N, SelectionDAG &DAG,
41093 TargetLowering::DAGCombinerInfo &DCI,
41094 const X86Subtarget &Subtarget) {
41095 if (ExperimentalVectorWideningLegalization)
41096 return SDValue();
41097
41098 unsigned Opcode = N->getOpcode();
41099 if (Opcode != ISD::SIGN_EXTEND && Opcode != ISD::ZERO_EXTEND)
41100 return SDValue();
41101 if (!DCI.isBeforeLegalizeOps())
41102 return SDValue();
41103 if (!Subtarget.hasSSE2())
41104 return SDValue();
41105
41106 SDValue N0 = N->getOperand(0);
41107 EVT VT = N->getValueType(0);
41108 EVT SVT = VT.getScalarType();
41109 EVT InVT = N0.getValueType();
41110 EVT InSVT = InVT.getScalarType();
41111
41112 // FIXME: Generic DAGCombiner previously had a bug that would cause a
41113 // sign_extend of setcc to sometimes return the original node and tricked it
41114 // into thinking CombineTo was used which prevented the target combines from
41115 // running.
41116 // Earlying out here to avoid regressions like this
41117 // (v4i32 (sext (v4i1 (setcc (v4i16)))))
41118 // Becomes
41119 // (v4i32 (sext_invec (v8i16 (concat (v4i16 (setcc (v4i16))), undef))))
41120 // Type legalized to
41121 // (v4i32 (sext_invec (v8i16 (trunc_invec (v4i32 (setcc (v4i32)))))))
41122 // Leading to a packssdw+pmovsxwd
41123 // We could write a DAG combine to fix this, but really we shouldn't be
41124 // creating sext_invec that's forcing v8i16 into the DAG.
41125 if (N0.getOpcode() == ISD::SETCC)
41126 return SDValue();
41127
41128 // Input type must be a vector and we must be extending legal integer types.
41129 if (!VT.isVector() || VT.getVectorNumElements() < 2)
41130 return SDValue();
41131 if (SVT != MVT::i64 && SVT != MVT::i32 && SVT != MVT::i16)
41132 return SDValue();
41133 if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
41134 return SDValue();
41135
41136 // If the input/output types are both legal then we have at least AVX1 and
41137 // we will be able to use SIGN_EXTEND/ZERO_EXTEND directly.
41138 if (DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
41139 DAG.getTargetLoweringInfo().isTypeLegal(InVT))
41140 return SDValue();
41141
41142 SDLoc DL(N);
41143
41144 auto ExtendVecSize = [&DAG](const SDLoc &DL, SDValue N, unsigned Size) {
41145 EVT SrcVT = N.getValueType();
41146 EVT DstVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getScalarType(),
41147 Size / SrcVT.getScalarSizeInBits());
41148 SmallVector<SDValue, 8> Opnds(Size / SrcVT.getSizeInBits(),
41149 DAG.getUNDEF(SrcVT));
41150 Opnds[0] = N;
41151 return DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Opnds);
41152 };
41153
41154 // If target-size is less than 128-bits, extend to a type that would extend
41155 // to 128 bits, extend that and extract the original target vector.
41156 if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits())) {
41157 unsigned Scale = 128 / VT.getSizeInBits();
41158 EVT ExVT =
41159 EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
41160 SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
41161 SDValue SExt = DAG.getNode(Opcode, DL, ExVT, Ex);
41162 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
41163 DAG.getIntPtrConstant(0, DL));
41164 }
41165
41166 // If target-size is 128-bits (or 256-bits on AVX target), then convert to
41167 // ISD::*_EXTEND_VECTOR_INREG which ensures lowering to X86ISD::V*EXT.
41168 // Also use this if we don't have SSE41 to allow the legalizer do its job.
41169 if (!Subtarget.hasSSE41() || VT.is128BitVector() ||
41170 (VT.is256BitVector() && Subtarget.hasAVX()) ||
41171 (VT.is512BitVector() && Subtarget.useAVX512Regs())) {
41172 SDValue ExOp = ExtendVecSize(DL, N0, VT.getSizeInBits());
41173 Opcode = Opcode == ISD::SIGN_EXTEND ? ISD::SIGN_EXTEND_VECTOR_INREG
41174 : ISD::ZERO_EXTEND_VECTOR_INREG;
41175 return DAG.getNode(Opcode, DL, VT, ExOp);
41176 }
41177
41178 auto SplitAndExtendInReg = [&](unsigned SplitSize) {
41179 unsigned NumVecs = VT.getSizeInBits() / SplitSize;
41180 unsigned NumSubElts = SplitSize / SVT.getSizeInBits();
41181 EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
41182 EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
41183
41184 unsigned IROpc = Opcode == ISD::SIGN_EXTEND ? ISD::SIGN_EXTEND_VECTOR_INREG
41185 : ISD::ZERO_EXTEND_VECTOR_INREG;
41186
41187 SmallVector<SDValue, 8> Opnds;
41188 for (unsigned i = 0, Offset = 0; i != NumVecs; ++i, Offset += NumSubElts) {
41189 SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
41190 DAG.getIntPtrConstant(Offset, DL));
41191 SrcVec = ExtendVecSize(DL, SrcVec, SplitSize);
41192 SrcVec = DAG.getNode(IROpc, DL, SubVT, SrcVec);
41193 Opnds.push_back(SrcVec);
41194 }
41195 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
41196 };
41197
41198 // On pre-AVX targets, split into 128-bit nodes of
41199 // ISD::*_EXTEND_VECTOR_INREG.
41200 if (!Subtarget.hasAVX() && !(VT.getSizeInBits() % 128))
41201 return SplitAndExtendInReg(128);
41202
41203 // On pre-AVX512 targets, split into 256-bit nodes of
41204 // ISD::*_EXTEND_VECTOR_INREG.
41205 if (!Subtarget.useAVX512Regs() && !(VT.getSizeInBits() % 256))
41206 return SplitAndExtendInReg(256);
41207
41208 return SDValue();
41209}
41210
41211// Attempt to combine a (sext/zext (setcc)) to a setcc with a xmm/ymm/zmm
41212// result type.
41213static SDValue combineExtSetcc(SDNode *N, SelectionDAG &DAG,
41214 const X86Subtarget &Subtarget) {
41215 SDValue N0 = N->getOperand(0);
41216 EVT VT = N->getValueType(0);
41217 SDLoc dl(N);
41218
41219 // Only do this combine with AVX512 for vector extends.
41220 if (!Subtarget.hasAVX512() || !VT.isVector() || N0.getOpcode() != ISD::SETCC)
41221 return SDValue();
41222
41223 // Only combine legal element types.
41224 EVT SVT = VT.getVectorElementType();
41225 if (SVT != MVT::i8 && SVT != MVT::i16 && SVT != MVT::i32 &&
41226 SVT != MVT::i64 && SVT != MVT::f32 && SVT != MVT::f64)
41227 return SDValue();
41228
41229 // We can only do this if the vector size in 256 bits or less.
41230 unsigned Size = VT.getSizeInBits();
41231 if (Size > 256)
41232 return SDValue();
41233
41234 // Don't fold if the condition code can't be handled by PCMPEQ/PCMPGT since
41235 // that's the only integer compares with we have.
41236 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
41237 if (ISD::isUnsignedIntSetCC(CC))
41238 return SDValue();
41239
41240 // Only do this combine if the extension will be fully consumed by the setcc.
41241 EVT N00VT = N0.getOperand(0).getValueType();
41242 EVT MatchingVecType = N00VT.changeVectorElementTypeToInteger();
41243 if (Size != MatchingVecType.getSizeInBits())
41244 return SDValue();
41245
41246 SDValue Res = DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC);
41247
41248 if (N->getOpcode() == ISD::ZERO_EXTEND)
41249 Res = DAG.getZeroExtendInReg(Res, dl, N0.getValueType().getScalarType());
41250
41251 return Res;
41252}
41253
41254static SDValue combineSext(SDNode *N, SelectionDAG &DAG,
41255 TargetLowering::DAGCombinerInfo &DCI,
41256 const X86Subtarget &Subtarget) {
41257 SDValue N0 = N->getOperand(0);
41258 EVT VT = N->getValueType(0);
41259 EVT InVT = N0.getValueType();
41260 SDLoc DL(N);
41261
41262 if (SDValue NewCMov = combineToExtendCMOV(N, DAG))
41263 return NewCMov;
41264
41265 if (!DCI.isBeforeLegalizeOps())
41266 return SDValue();
41267
41268 if (SDValue V = combineExtSetcc(N, DAG, Subtarget))
41269 return V;
41270
41271 if (InVT == MVT::i1 && N0.getOpcode() == ISD::XOR &&
41272 isAllOnesConstant(N0.getOperand(1)) && N0.hasOneUse()) {
41273 // Invert and sign-extend a boolean is the same as zero-extend and subtract
41274 // 1 because 0 becomes -1 and 1 becomes 0. The subtract is efficiently
41275 // lowered with an LEA or a DEC. This is the same as: select Bool, 0, -1.
41276 // sext (xor Bool, -1) --> sub (zext Bool), 1
41277 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
41278 return DAG.getNode(ISD::SUB, DL, VT, Zext, DAG.getConstant(1, DL, VT));
41279 }
41280
41281 if (SDValue V = combineToExtendVectorInReg(N, DAG, DCI, Subtarget))
41282 return V;
41283
41284 if (SDValue V = combineToExtendBoolVectorInReg(N, DAG, DCI, Subtarget))
41285 return V;
41286
41287 if (VT.isVector())
41288 if (SDValue R = PromoteMaskArithmetic(N, DAG, Subtarget))
41289 return R;
41290
41291 if (SDValue NewAdd = promoteExtBeforeAdd(N, DAG, Subtarget))
41292 return NewAdd;
41293
41294 return SDValue();
41295}
41296
41297static unsigned negateFMAOpcode(unsigned Opcode, bool NegMul, bool NegAcc) {
41298 if (NegMul) {
41299 switch (Opcode) {
41300 default: llvm_unreachable("Unexpected opcode")::llvm::llvm_unreachable_internal("Unexpected opcode", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 41300)
;
41301 case ISD::FMA: Opcode = X86ISD::FNMADD; break;
41302 case X86ISD::FMADD_RND: Opcode = X86ISD::FNMADD_RND; break;
41303 case X86ISD::FMSUB: Opcode = X86ISD::FNMSUB; break;
41304 case X86ISD::FMSUB_RND: Opcode = X86ISD::FNMSUB_RND; break;
41305 case X86ISD::FNMADD: Opcode = ISD::FMA; break;
41306 case X86ISD::FNMADD_RND: Opcode = X86ISD::FMADD_RND; break;
41307 case X86ISD::FNMSUB: Opcode = X86ISD::FMSUB; break;
41308 case X86ISD::FNMSUB_RND: Opcode = X86ISD::FMSUB_RND; break;
41309 }
41310 }
41311
41312 if (NegAcc) {
41313 switch (Opcode) {
41314 default: llvm_unreachable("Unexpected opcode")::llvm::llvm_unreachable_internal("Unexpected opcode", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 41314)
;
41315 case ISD::FMA: Opcode = X86ISD::FMSUB; break;
41316 case X86ISD::FMADD_RND: Opcode = X86ISD::FMSUB_RND; break;
41317 case X86ISD::FMSUB: Opcode = ISD::FMA; break;
41318 case X86ISD::FMSUB_RND: Opcode = X86ISD::FMADD_RND; break;
41319 case X86ISD::FNMADD: Opcode = X86ISD::FNMSUB; break;
41320 case X86ISD::FNMADD_RND: Opcode = X86ISD::FNMSUB_RND; break;
41321 case X86ISD::FNMSUB: Opcode = X86ISD::FNMADD; break;
41322 case X86ISD::FNMSUB_RND: Opcode = X86ISD::FNMADD_RND; break;
41323 }
41324 }
41325
41326 return Opcode;
41327}
41328
41329static SDValue combineFMA(SDNode *N, SelectionDAG &DAG,
41330 const X86Subtarget &Subtarget) {
41331 SDLoc dl(N);
41332 EVT VT = N->getValueType(0);
41333
41334 // Let legalize expand this if it isn't a legal type yet.
41335 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
41336 return SDValue();
41337
41338 EVT ScalarVT = VT.getScalarType();
41339 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) || !Subtarget.hasAnyFMA())
41340 return SDValue();
41341
41342 SDValue A = N->getOperand(0);
41343 SDValue B = N->getOperand(1);
41344 SDValue C = N->getOperand(2);
41345
41346 auto invertIfNegative = [&DAG](SDValue &V) {
41347 if (SDValue NegVal = isFNEG(DAG, V.getNode())) {
41348 V = DAG.getBitcast(V.getValueType(), NegVal);
41349 return true;
41350 }
41351 // Look through extract_vector_elts. If it comes from an FNEG, create a
41352 // new extract from the FNEG input.
41353 if (V.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
41354 isNullConstant(V.getOperand(1))) {
41355 if (SDValue NegVal = isFNEG(DAG, V.getOperand(0).getNode())) {
41356 NegVal = DAG.getBitcast(V.getOperand(0).getValueType(), NegVal);
41357 V = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), V.getValueType(),
41358 NegVal, V.getOperand(1));
41359 return true;
41360 }
41361 }
41362
41363 return false;
41364 };
41365
41366 // Do not convert the passthru input of scalar intrinsics.
41367 // FIXME: We could allow negations of the lower element only.
41368 bool NegA = invertIfNegative(A);
41369 bool NegB = invertIfNegative(B);
41370 bool NegC = invertIfNegative(C);
41371
41372 if (!NegA && !NegB && !NegC)
41373 return SDValue();
41374
41375 unsigned NewOpcode = negateFMAOpcode(N->getOpcode(), NegA != NegB, NegC);
41376
41377 if (N->getNumOperands() == 4)
41378 return DAG.getNode(NewOpcode, dl, VT, A, B, C, N->getOperand(3));
41379 return DAG.getNode(NewOpcode, dl, VT, A, B, C);
41380}
41381
41382// Combine FMADDSUB(A, B, FNEG(C)) -> FMSUBADD(A, B, C)
41383static SDValue combineFMADDSUB(SDNode *N, SelectionDAG &DAG,
41384 const X86Subtarget &Subtarget) {
41385 SDLoc dl(N);
41386 EVT VT = N->getValueType(0);
41387
41388 SDValue NegVal = isFNEG(DAG, N->getOperand(2).getNode());
41389 if (!NegVal)
41390 return SDValue();
41391
41392 unsigned NewOpcode;
41393 switch (N->getOpcode()) {
41394 default: llvm_unreachable("Unexpected opcode!")::llvm::llvm_unreachable_internal("Unexpected opcode!", "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 41394)
;
41395 case X86ISD::FMADDSUB: NewOpcode = X86ISD::FMSUBADD; break;
41396 case X86ISD::FMADDSUB_RND: NewOpcode = X86ISD::FMSUBADD_RND; break;
41397 case X86ISD::FMSUBADD: NewOpcode = X86ISD::FMADDSUB; break;
41398 case X86ISD::FMSUBADD_RND: NewOpcode = X86ISD::FMADDSUB_RND; break;
41399 }
41400
41401 if (N->getNumOperands() == 4)
41402 return DAG.getNode(NewOpcode, dl, VT, N->getOperand(0), N->getOperand(1),
41403 NegVal, N->getOperand(3));
41404 return DAG.getNode(NewOpcode, dl, VT, N->getOperand(0), N->getOperand(1),
41405 NegVal);
41406}
41407
41408static SDValue combineZext(SDNode *N, SelectionDAG &DAG,
41409 TargetLowering::DAGCombinerInfo &DCI,
41410 const X86Subtarget &Subtarget) {
41411 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
41412 // (and (i32 x86isd::setcc_carry), 1)
41413 // This eliminates the zext. This transformation is necessary because
41414 // ISD::SETCC is always legalized to i8.
41415 SDLoc dl(N);
41416 SDValue N0 = N->getOperand(0);
41417 EVT VT = N->getValueType(0);
41418
41419 if (N0.getOpcode() == ISD::AND &&
41420 N0.hasOneUse() &&
41421 N0.getOperand(0).hasOneUse()) {
41422 SDValue N00 = N0.getOperand(0);
41423 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
41424 if (!isOneConstant(N0.getOperand(1)))
41425 return SDValue();
41426 return DAG.getNode(ISD::AND, dl, VT,
41427 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
41428 N00.getOperand(0), N00.getOperand(1)),
41429 DAG.getConstant(1, dl, VT));
41430 }
41431 }
41432
41433 if (N0.getOpcode() == ISD::TRUNCATE &&
41434 N0.hasOneUse() &&
41435 N0.getOperand(0).hasOneUse()) {
41436 SDValue N00 = N0.getOperand(0);
41437 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
41438 return DAG.getNode(ISD::AND, dl, VT,
41439 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
41440 N00.getOperand(0), N00.getOperand(1)),
41441 DAG.getConstant(1, dl, VT));
41442 }
41443 }
41444
41445 if (SDValue NewCMov = combineToExtendCMOV(N, DAG))
41446 return NewCMov;
41447
41448 if (DCI.isBeforeLegalizeOps())
41449 if (SDValue V = combineExtSetcc(N, DAG, Subtarget))
41450 return V;
41451
41452 if (SDValue V = combineToExtendVectorInReg(N, DAG, DCI, Subtarget))
41453 return V;
41454
41455 if (SDValue V = combineToExtendBoolVectorInReg(N, DAG, DCI, Subtarget))
41456 return V;
41457
41458 if (VT.isVector())
41459 if (SDValue R = PromoteMaskArithmetic(N, DAG, Subtarget))
41460 return R;
41461
41462 if (SDValue NewAdd = promoteExtBeforeAdd(N, DAG, Subtarget))
41463 return NewAdd;
41464
41465 if (SDValue R = combineOrCmpEqZeroToCtlzSrl(N, DAG, DCI, Subtarget))
41466 return R;
41467
41468 // TODO: Combine with any target/faux shuffle.
41469 if (N0.getOpcode() == X86ISD::PACKUS && N0.getValueSizeInBits() == 128 &&
41470 VT.getScalarSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits()) {
41471 SDValue N00 = N0.getOperand(0);
41472 SDValue N01 = N0.getOperand(1);
41473 unsigned NumSrcElts = N00.getValueType().getVectorNumElements();
41474 unsigned NumSrcEltBits = N00.getScalarValueSizeInBits();
41475 APInt ZeroMask = APInt::getHighBitsSet(NumSrcEltBits, NumSrcEltBits / 2);
41476 if ((N00.isUndef() || DAG.MaskedValueIsZero(N00, ZeroMask)) &&
41477 (N01.isUndef() || DAG.MaskedValueIsZero(N01, ZeroMask))) {
41478 return concatSubVectors(N00, N01, VT, NumSrcElts * 2, DAG, dl, 128);
41479 }
41480 }
41481
41482 return SDValue();
41483}
41484
41485/// Try to map a 128-bit or larger integer comparison to vector instructions
41486/// before type legalization splits it up into chunks.
41487static SDValue combineVectorSizedSetCCEquality(SDNode *SetCC, SelectionDAG &DAG,
41488 const X86Subtarget &Subtarget) {
41489 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get();
41490 assert((CC == ISD::SETNE || CC == ISD::SETEQ) && "Bad comparison predicate")(((CC == ISD::SETNE || CC == ISD::SETEQ) && "Bad comparison predicate"
) ? static_cast<void> (0) : __assert_fail ("(CC == ISD::SETNE || CC == ISD::SETEQ) && \"Bad comparison predicate\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 41490, __PRETTY_FUNCTION__))
;
41491
41492 // We're looking for an oversized integer equality comparison.
41493 SDValue X = SetCC->getOperand(0);
41494 SDValue Y = SetCC->getOperand(1);
41495 EVT OpVT = X.getValueType();
41496 unsigned OpSize = OpVT.getSizeInBits();
41497 if (!OpVT.isScalarInteger() || OpSize < 128)
41498 return SDValue();
41499
41500 // Ignore a comparison with zero because that gets special treatment in
41501 // EmitTest(). But make an exception for the special case of a pair of
41502 // logically-combined vector-sized operands compared to zero. This pattern may
41503 // be generated by the memcmp expansion pass with oversized integer compares
41504 // (see PR33325).
41505 bool IsOrXorXorCCZero = isNullConstant(Y) && X.getOpcode() == ISD::OR &&
41506 X.getOperand(0).getOpcode() == ISD::XOR &&
41507 X.getOperand(1).getOpcode() == ISD::XOR;
41508 if (isNullConstant(Y) && !IsOrXorXorCCZero)
41509 return SDValue();
41510
41511 // Don't perform this combine if constructing the vector will be expensive.
41512 auto IsVectorBitCastCheap = [](SDValue X) {
41513 X = peekThroughBitcasts(X);
41514 return isa<ConstantSDNode>(X) || X.getValueType().isVector() ||
41515 X.getOpcode() == ISD::LOAD;
41516 };
41517 if ((!IsVectorBitCastCheap(X) || !IsVectorBitCastCheap(Y)) &&
41518 !IsOrXorXorCCZero)
41519 return SDValue();
41520
41521 // TODO: Use PXOR + PTEST for SSE4.1 or later?
41522 EVT VT = SetCC->getValueType(0);
41523 SDLoc DL(SetCC);
41524 if ((OpSize == 128 && Subtarget.hasSSE2()) ||
41525 (OpSize == 256 && Subtarget.hasAVX2()) ||
41526 (OpSize == 512 && Subtarget.useAVX512Regs())) {
41527 EVT VecVT = OpSize == 512 ? MVT::v16i32 :
41528 OpSize == 256 ? MVT::v32i8 :
41529 MVT::v16i8;
41530 EVT CmpVT = OpSize == 512 ? MVT::v16i1 : VecVT;
41531 SDValue Cmp;
41532 if (IsOrXorXorCCZero) {
41533 // This is a bitwise-combined equality comparison of 2 pairs of vectors:
41534 // setcc i128 (or (xor A, B), (xor C, D)), 0, eq|ne
41535 // Use 2 vector equality compares and 'and' the results before doing a
41536 // MOVMSK.
41537 SDValue A = DAG.getBitcast(VecVT, X.getOperand(0).getOperand(0));
41538 SDValue B = DAG.getBitcast(VecVT, X.getOperand(0).getOperand(1));
41539 SDValue C = DAG.getBitcast(VecVT, X.getOperand(1).getOperand(0));
41540 SDValue D = DAG.getBitcast(VecVT, X.getOperand(1).getOperand(1));
41541 SDValue Cmp1 = DAG.getSetCC(DL, CmpVT, A, B, ISD::SETEQ);
41542 SDValue Cmp2 = DAG.getSetCC(DL, CmpVT, C, D, ISD::SETEQ);
41543 Cmp = DAG.getNode(ISD::AND, DL, CmpVT, Cmp1, Cmp2);
41544 } else {
41545 SDValue VecX = DAG.getBitcast(VecVT, X);
41546 SDValue VecY = DAG.getBitcast(VecVT, Y);
41547 Cmp = DAG.getSetCC(DL, CmpVT, VecX, VecY, ISD::SETEQ);
41548 }
41549 // For 512-bits we want to emit a setcc that will lower to kortest.
41550 if (OpSize == 512)
41551 return DAG.getSetCC(DL, VT, DAG.getBitcast(MVT::i16, Cmp),
41552 DAG.getConstant(0xFFFF, DL, MVT::i16), CC);
41553 // If all bytes match (bitmask is 0x(FFFF)FFFF), that's equality.
41554 // setcc i128 X, Y, eq --> setcc (pmovmskb (pcmpeqb X, Y)), 0xFFFF, eq
41555 // setcc i128 X, Y, ne --> setcc (pmovmskb (pcmpeqb X, Y)), 0xFFFF, ne
41556 // setcc i256 X, Y, eq --> setcc (vpmovmskb (vpcmpeqb X, Y)), 0xFFFFFFFF, eq
41557 // setcc i256 X, Y, ne --> setcc (vpmovmskb (vpcmpeqb X, Y)), 0xFFFFFFFF, ne
41558 SDValue MovMsk = DAG.getNode(X86ISD::MOVMSK, DL, MVT::i32, Cmp);
41559 SDValue FFFFs = DAG.getConstant(OpSize == 128 ? 0xFFFF : 0xFFFFFFFF, DL,
41560 MVT::i32);
41561 return DAG.getSetCC(DL, VT, MovMsk, FFFFs, CC);
41562 }
41563
41564 return SDValue();
41565}
41566
41567static SDValue combineSetCC(SDNode *N, SelectionDAG &DAG,
41568 const X86Subtarget &Subtarget) {
41569 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
41570 SDValue LHS = N->getOperand(0);
41571 SDValue RHS = N->getOperand(1);
41572 EVT VT = N->getValueType(0);
41573 EVT OpVT = LHS.getValueType();
41574 SDLoc DL(N);
41575
41576 if (CC == ISD::SETNE || CC == ISD::SETEQ) {
41577 // 0-x == y --> x+y == 0
41578 // 0-x != y --> x+y != 0
41579 if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) &&
41580 LHS.hasOneUse()) {
41581 SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, RHS, LHS.getOperand(1));
41582 return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
41583 }
41584 // x == 0-y --> x+y == 0
41585 // x != 0-y --> x+y != 0
41586 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
41587 RHS.hasOneUse()) {
41588 SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
41589 return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
41590 }
41591
41592 if (SDValue V = combineVectorSizedSetCCEquality(N, DAG, Subtarget))
41593 return V;
41594 }
41595
41596 if (VT.isVector() && VT.getVectorElementType() == MVT::i1 &&
41597 (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
41598 // Put build_vectors on the right.
41599 if (LHS.getOpcode() == ISD::BUILD_VECTOR) {
41600 std::swap(LHS, RHS);
41601 CC = ISD::getSetCCSwappedOperands(CC);
41602 }
41603
41604 bool IsSEXT0 =
41605 (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
41606 (LHS.getOperand(0).getValueType().getVectorElementType() == MVT::i1);
41607 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
41608
41609 if (IsSEXT0 && IsVZero1) {
41610 assert(VT == LHS.getOperand(0).getValueType() &&((VT == LHS.getOperand(0).getValueType() && "Uexpected operand type"
) ? static_cast<void> (0) : __assert_fail ("VT == LHS.getOperand(0).getValueType() && \"Uexpected operand type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 41611, __PRETTY_FUNCTION__))
41611 "Uexpected operand type")((VT == LHS.getOperand(0).getValueType() && "Uexpected operand type"
) ? static_cast<void> (0) : __assert_fail ("VT == LHS.getOperand(0).getValueType() && \"Uexpected operand type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 41611, __PRETTY_FUNCTION__))
;
41612 if (CC == ISD::SETGT)
41613 return DAG.getConstant(0, DL, VT);
41614 if (CC == ISD::SETLE)
41615 return DAG.getConstant(1, DL, VT);
41616 if (CC == ISD::SETEQ || CC == ISD::SETGE)
41617 return DAG.getNOT(DL, LHS.getOperand(0), VT);
41618
41619 assert((CC == ISD::SETNE || CC == ISD::SETLT) &&(((CC == ISD::SETNE || CC == ISD::SETLT) && "Unexpected condition code!"
) ? static_cast<void> (0) : __assert_fail ("(CC == ISD::SETNE || CC == ISD::SETLT) && \"Unexpected condition code!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 41620, __PRETTY_FUNCTION__))
41620 "Unexpected condition code!")(((CC == ISD::SETNE || CC == ISD::SETLT) && "Unexpected condition code!"
) ? static_cast<void> (0) : __assert_fail ("(CC == ISD::SETNE || CC == ISD::SETLT) && \"Unexpected condition code!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 41620, __PRETTY_FUNCTION__))
;
41621 return LHS.getOperand(0);
41622 }
41623 }
41624
41625 // If we have AVX512, but not BWI and this is a vXi16/vXi8 setcc, just
41626 // pre-promote its result type since vXi1 vectors don't get promoted
41627 // during type legalization.
41628 // NOTE: The element count check is to ignore operand types that need to
41629 // go through type promotion to a 128-bit vector.
41630 if (Subtarget.hasAVX512() && !Subtarget.hasBWI() && VT.isVector() &&
41631 VT.getVectorElementType() == MVT::i1 &&
41632 (ExperimentalVectorWideningLegalization ||
41633 VT.getVectorNumElements() > 4) &&
41634 (OpVT.getVectorElementType() == MVT::i8 ||
41635 OpVT.getVectorElementType() == MVT::i16)) {
41636 SDValue Setcc = DAG.getNode(ISD::SETCC, DL, OpVT, LHS, RHS,
41637 N->getOperand(2));
41638 return DAG.getNode(ISD::TRUNCATE, DL, VT, Setcc);
41639 }
41640
41641 // For an SSE1-only target, lower a comparison of v4f32 to X86ISD::CMPP early
41642 // to avoid scalarization via legalization because v4i32 is not a legal type.
41643 if (Subtarget.hasSSE1() && !Subtarget.hasSSE2() && VT == MVT::v4i32 &&
41644 LHS.getValueType() == MVT::v4f32)
41645 return LowerVSETCC(SDValue(N, 0), Subtarget, DAG);
41646
41647 return SDValue();
41648}
41649
41650static SDValue combineMOVMSK(SDNode *N, SelectionDAG &DAG,
41651 TargetLowering::DAGCombinerInfo &DCI) {
41652 SDValue Src = N->getOperand(0);
41653 MVT SrcVT = Src.getSimpleValueType();
41654 MVT VT = N->getSimpleValueType(0);
41655 unsigned NumBits = VT.getScalarSizeInBits();
41656 unsigned NumElts = SrcVT.getVectorNumElements();
41657
41658 // Perform constant folding.
41659 if (ISD::isBuildVectorOfConstantSDNodes(Src.getNode())) {
41660 assert(VT == MVT::i32 && "Unexpected result type")((VT == MVT::i32 && "Unexpected result type") ? static_cast
<void> (0) : __assert_fail ("VT == MVT::i32 && \"Unexpected result type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 41660, __PRETTY_FUNCTION__))
;
41661 APInt Imm(32, 0);
41662 for (unsigned Idx = 0, e = Src.getNumOperands(); Idx < e; ++Idx) {
41663 if (!Src.getOperand(Idx).isUndef() &&
41664 Src.getConstantOperandAPInt(Idx).isNegative())
41665 Imm.setBit(Idx);
41666 }
41667 return DAG.getConstant(Imm, SDLoc(N), VT);
41668 }
41669
41670 // Look through int->fp bitcasts that don't change the element width.
41671 unsigned EltWidth = SrcVT.getScalarSizeInBits();
41672 if (Src.getOpcode() == ISD::BITCAST &&
41673 Src.getOperand(0).getScalarValueSizeInBits() == EltWidth)
41674 return DAG.getNode(X86ISD::MOVMSK, SDLoc(N), VT, Src.getOperand(0));
41675
41676 // Fold movmsk(not(x)) -> not(movmsk) to improve folding of movmsk results
41677 // with scalar comparisons.
41678 if (SDValue NotSrc = IsNOT(Src, DAG)) {
41679 SDLoc DL(N);
41680 APInt NotMask = APInt::getLowBitsSet(NumBits, NumElts);
41681 NotSrc = DAG.getBitcast(SrcVT, NotSrc);
41682 return DAG.getNode(ISD::XOR, DL, VT,
41683 DAG.getNode(X86ISD::MOVMSK, DL, VT, NotSrc),
41684 DAG.getConstant(NotMask, DL, VT));
41685 }
41686
41687 // Simplify the inputs.
41688 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
41689 APInt DemandedMask(APInt::getAllOnesValue(NumBits));
41690 if (TLI.SimplifyDemandedBits(SDValue(N, 0), DemandedMask, DCI))
41691 return SDValue(N, 0);
41692
41693 return SDValue();
41694}
41695
41696static SDValue combineGatherScatter(SDNode *N, SelectionDAG &DAG,
41697 TargetLowering::DAGCombinerInfo &DCI,
41698 const X86Subtarget &Subtarget) {
41699 SDLoc DL(N);
41700
41701 if (DCI.isBeforeLegalizeOps()) {
41702 SDValue Index = N->getOperand(4);
41703 // Remove any sign extends from 32 or smaller to larger than 32.
41704 // Only do this before LegalizeOps in case we need the sign extend for
41705 // legalization.
41706 if (Index.getOpcode() == ISD::SIGN_EXTEND) {
41707 if (Index.getScalarValueSizeInBits() > 32 &&
41708 Index.getOperand(0).getScalarValueSizeInBits() <= 32) {
41709 SmallVector<SDValue, 5> NewOps(N->op_begin(), N->op_end());
41710 NewOps[4] = Index.getOperand(0);
41711 SDNode *Res = DAG.UpdateNodeOperands(N, NewOps);
41712 if (Res == N) {
41713 // The original sign extend has less users, add back to worklist in
41714 // case it needs to be removed
41715 DCI.AddToWorklist(Index.getNode());
41716 DCI.AddToWorklist(N);
41717 }
41718 return SDValue(Res, 0);
41719 }
41720 }
41721
41722 // Make sure the index is either i32 or i64
41723 unsigned ScalarSize = Index.getScalarValueSizeInBits();
41724 if (ScalarSize != 32 && ScalarSize != 64) {
41725 MVT EltVT = ScalarSize > 32 ? MVT::i64 : MVT::i32;
41726 EVT IndexVT = EVT::getVectorVT(*DAG.getContext(), EltVT,
41727 Index.getValueType().getVectorNumElements());
41728 Index = DAG.getSExtOrTrunc(Index, DL, IndexVT);
41729 SmallVector<SDValue, 5> NewOps(N->op_begin(), N->op_end());
41730 NewOps[4] = Index;
41731 SDNode *Res = DAG.UpdateNodeOperands(N, NewOps);
41732 if (Res == N)
41733 DCI.AddToWorklist(N);
41734 return SDValue(Res, 0);
41735 }
41736
41737 // Try to remove zero extends from 32->64 if we know the sign bit of
41738 // the input is zero.
41739 if (Index.getOpcode() == ISD::ZERO_EXTEND &&
41740 Index.getScalarValueSizeInBits() == 64 &&
41741 Index.getOperand(0).getScalarValueSizeInBits() == 32) {
41742 if (DAG.SignBitIsZero(Index.getOperand(0))) {
41743 SmallVector<SDValue, 5> NewOps(N->op_begin(), N->op_end());
41744 NewOps[4] = Index.getOperand(0);
41745 SDNode *Res = DAG.UpdateNodeOperands(N, NewOps);
41746 if (Res == N) {
41747 // The original sign extend has less users, add back to worklist in
41748 // case it needs to be removed
41749 DCI.AddToWorklist(Index.getNode());
41750 DCI.AddToWorklist(N);
41751 }
41752 return SDValue(Res, 0);
41753 }
41754 }
41755 }
41756
41757 // With AVX2 we only demand the upper bit of the mask.
41758 if (!Subtarget.hasAVX512()) {
41759 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
41760 SDValue Mask = N->getOperand(2);
41761 APInt DemandedMask(APInt::getSignMask(Mask.getScalarValueSizeInBits()));
41762 if (TLI.SimplifyDemandedBits(Mask, DemandedMask, DCI))
41763 return SDValue(N, 0);
41764 }
41765
41766 return SDValue();
41767}
41768
41769// Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
41770static SDValue combineX86SetCC(SDNode *N, SelectionDAG &DAG,
41771 const X86Subtarget &Subtarget) {
41772 SDLoc DL(N);
41773 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
41774 SDValue EFLAGS = N->getOperand(1);
41775
41776 // Try to simplify the EFLAGS and condition code operands.
41777 if (SDValue Flags = combineSetCCEFLAGS(EFLAGS, CC, DAG, Subtarget))
41778 return getSETCC(CC, Flags, DL, DAG);
41779
41780 return SDValue();
41781}
41782
41783/// Optimize branch condition evaluation.
41784static SDValue combineBrCond(SDNode *N, SelectionDAG &DAG,
41785 const X86Subtarget &Subtarget) {
41786 SDLoc DL(N);
41787 SDValue EFLAGS = N->getOperand(3);
41788 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
41789
41790 // Try to simplify the EFLAGS and condition code operands.
41791 // Make sure to not keep references to operands, as combineSetCCEFLAGS can
41792 // RAUW them under us.
41793 if (SDValue Flags = combineSetCCEFLAGS(EFLAGS, CC, DAG, Subtarget)) {
41794 SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
41795 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), N->getOperand(0),
41796 N->getOperand(1), Cond, Flags);
41797 }
41798
41799 return SDValue();
41800}
41801
41802static SDValue combineVectorCompareAndMaskUnaryOp(SDNode *N,
41803 SelectionDAG &DAG) {
41804 // Take advantage of vector comparisons producing 0 or -1 in each lane to
41805 // optimize away operation when it's from a constant.
41806 //
41807 // The general transformation is:
41808 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
41809 // AND(VECTOR_CMP(x,y), constant2)
41810 // constant2 = UNARYOP(constant)
41811
41812 // Early exit if this isn't a vector operation, the operand of the
41813 // unary operation isn't a bitwise AND, or if the sizes of the operations
41814 // aren't the same.
41815 EVT VT = N->getValueType(0);
41816 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
41817 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
41818 VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
41819 return SDValue();
41820
41821 // Now check that the other operand of the AND is a constant. We could
41822 // make the transformation for non-constant splats as well, but it's unclear
41823 // that would be a benefit as it would not eliminate any operations, just
41824 // perform one more step in scalar code before moving to the vector unit.
41825 if (auto *BV = dyn_cast<BuildVectorSDNode>(N->getOperand(0).getOperand(1))) {
41826 // Bail out if the vector isn't a constant.
41827 if (!BV->isConstant())
41828 return SDValue();
41829
41830 // Everything checks out. Build up the new and improved node.
41831 SDLoc DL(N);
41832 EVT IntVT = BV->getValueType(0);
41833 // Create a new constant of the appropriate type for the transformed
41834 // DAG.
41835 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
41836 // The AND node needs bitcasts to/from an integer vector type around it.
41837 SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
41838 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
41839 N->getOperand(0)->getOperand(0), MaskConst);
41840 SDValue Res = DAG.getBitcast(VT, NewAnd);
41841 return Res;
41842 }
41843
41844 return SDValue();
41845}
41846
41847static SDValue combineUIntToFP(SDNode *N, SelectionDAG &DAG,
41848 const X86Subtarget &Subtarget) {
41849 SDValue Op0 = N->getOperand(0);
41850 EVT VT = N->getValueType(0);
41851 EVT InVT = Op0.getValueType();
41852
41853 // UINT_TO_FP(vXi1) -> SINT_TO_FP(ZEXT(vXi1 to vXi32))
41854 // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
41855 // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
41856 if (InVT.isVector() && InVT.getScalarSizeInBits() < 32) {
41857 SDLoc dl(N);
41858 EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
41859 InVT.getVectorNumElements());
41860 SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
41861
41862 // UINT_TO_FP isn't legal without AVX512 so use SINT_TO_FP.
41863 return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
41864 }
41865
41866 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
41867 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
41868 // the optimization here.
41869 if (DAG.SignBitIsZero(Op0))
41870 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, Op0);
41871
41872 return SDValue();
41873}
41874
41875static SDValue combineSIntToFP(SDNode *N, SelectionDAG &DAG,
41876 const X86Subtarget &Subtarget) {
41877 // First try to optimize away the conversion entirely when it's
41878 // conditionally from a constant. Vectors only.
41879 if (SDValue Res = combineVectorCompareAndMaskUnaryOp(N, DAG))
41880 return Res;
41881
41882 // Now move on to more general possibilities.
41883 SDValue Op0 = N->getOperand(0);
41884 EVT VT = N->getValueType(0);
41885 EVT InVT = Op0.getValueType();
41886
41887 // SINT_TO_FP(vXi1) -> SINT_TO_FP(SEXT(vXi1 to vXi32))
41888 // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
41889 // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
41890 if (InVT.isVector() && InVT.getScalarSizeInBits() < 32) {
41891 SDLoc dl(N);
41892 EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
41893 InVT.getVectorNumElements());
41894 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
41895 return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
41896 }
41897
41898 // Without AVX512DQ we only support i64 to float scalar conversion. For both
41899 // vectors and scalars, see if we know that the upper bits are all the sign
41900 // bit, in which case we can truncate the input to i32 and convert from that.
41901 if (InVT.getScalarSizeInBits() > 32 && !Subtarget.hasDQI()) {
41902 unsigned BitWidth = InVT.getScalarSizeInBits();
41903 unsigned NumSignBits = DAG.ComputeNumSignBits(Op0);
41904 if (NumSignBits >= (BitWidth - 31)) {
41905 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), 32);
41906 if (InVT.isVector())
41907 TruncVT = EVT::getVectorVT(*DAG.getContext(), TruncVT,
41908 InVT.getVectorNumElements());
41909 SDLoc dl(N);
41910 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, TruncVT, Op0);
41911 return DAG.getNode(ISD::SINT_TO_FP, dl, VT, Trunc);
41912 }
41913 }
41914
41915 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
41916 // a 32-bit target where SSE doesn't support i64->FP operations.
41917 if (!Subtarget.useSoftFloat() && Subtarget.hasX87() &&
41918 Op0.getOpcode() == ISD::LOAD) {
41919 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
41920 EVT LdVT = Ld->getValueType(0);
41921
41922 // This transformation is not supported if the result type is f16 or f128.
41923 if (VT == MVT::f16 || VT == MVT::f128)
41924 return SDValue();
41925
41926 // If we have AVX512DQ we can use packed conversion instructions unless
41927 // the VT is f80.
41928 if (Subtarget.hasDQI() && VT != MVT::f80)
41929 return SDValue();
41930
41931 if (!Ld->isVolatile() && !VT.isVector() &&
41932 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
41933 !Subtarget.is64Bit() && LdVT == MVT::i64) {
41934 SDValue FILDChain = Subtarget.getTargetLowering()->BuildFILD(
41935 SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
41936 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
41937 return FILDChain;
41938 }
41939 }
41940 return SDValue();
41941}
41942
41943static bool needCarryOrOverflowFlag(SDValue Flags) {
41944 assert(Flags.getValueType() == MVT::i32 && "Unexpected VT!")((Flags.getValueType() == MVT::i32 && "Unexpected VT!"
) ? static_cast<void> (0) : __assert_fail ("Flags.getValueType() == MVT::i32 && \"Unexpected VT!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 41944, __PRETTY_FUNCTION__))
;
41945
41946 for (SDNode::use_iterator UI = Flags->use_begin(), UE = Flags->use_end();
41947 UI != UE; ++UI) {
41948 SDNode *User = *UI;
41949
41950 X86::CondCode CC;
41951 switch (User->getOpcode()) {
41952 default:
41953 // Be conservative.
41954 return true;
41955 case X86ISD::SETCC:
41956 case X86ISD::SETCC_CARRY:
41957 CC = (X86::CondCode)User->getConstantOperandVal(0);
41958 break;
41959 case X86ISD::BRCOND:
41960 CC = (X86::CondCode)User->getConstantOperandVal(2);
41961 break;
41962 case X86ISD::CMOV:
41963 CC = (X86::CondCode)User->getConstantOperandVal(2);
41964 break;
41965 }
41966
41967 switch (CC) {
41968 default: break;
41969 case X86::COND_A: case X86::COND_AE:
41970 case X86::COND_B: case X86::COND_BE:
41971 case X86::COND_O: case X86::COND_NO:
41972 case X86::COND_G: case X86::COND_GE:
41973 case X86::COND_L: case X86::COND_LE:
41974 return true;
41975 }
41976 }
41977
41978 return false;
41979}
41980
41981static bool onlyZeroFlagUsed(SDValue Flags) {
41982 assert(Flags.getValueType() == MVT::i32 && "Unexpected VT!")((Flags.getValueType() == MVT::i32 && "Unexpected VT!"
) ? static_cast<void> (0) : __assert_fail ("Flags.getValueType() == MVT::i32 && \"Unexpected VT!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 41982, __PRETTY_FUNCTION__))
;
41983
41984 for (SDNode::use_iterator UI = Flags->use_begin(), UE = Flags->use_end();
41985 UI != UE; ++UI) {
41986 SDNode *User = *UI;
41987
41988 unsigned CCOpNo;
41989 switch (User->getOpcode()) {
41990 default:
41991 // Be conservative.
41992 return false;
41993 case X86ISD::SETCC: CCOpNo = 0; break;
41994 case X86ISD::SETCC_CARRY: CCOpNo = 0; break;
41995 case X86ISD::BRCOND: CCOpNo = 2; break;
41996 case X86ISD::CMOV: CCOpNo = 2; break;
41997 }
41998
41999 X86::CondCode CC = (X86::CondCode)User->getConstantOperandVal(CCOpNo);
42000 if (CC != X86::COND_E && CC != X86::COND_NE)
42001 return false;
42002 }
42003
42004 return true;
42005}
42006
42007static SDValue combineCMP(SDNode *N, SelectionDAG &DAG) {
42008 // Only handle test patterns.
42009 if (!isNullConstant(N->getOperand(1)))
42010 return SDValue();
42011
42012 // If we have a CMP of a truncated binop, see if we can make a smaller binop
42013 // and use its flags directly.
42014 // TODO: Maybe we should try promoting compares that only use the zero flag
42015 // first if we can prove the upper bits with computeKnownBits?
42016 SDLoc dl(N);
42017 SDValue Op = N->getOperand(0);
42018 EVT VT = Op.getValueType();
42019
42020 // If we have a constant logical shift that's only used in a comparison
42021 // against zero turn it into an equivalent AND. This allows turning it into
42022 // a TEST instruction later.
42023 if ((Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) &&
42024 Op.hasOneUse() && isa<ConstantSDNode>(Op.getOperand(1)) &&
42025 onlyZeroFlagUsed(SDValue(N, 0))) {
42026 unsigned BitWidth = VT.getSizeInBits();
42027 const APInt &ShAmt = Op.getConstantOperandAPInt(1);
42028 if (ShAmt.ult(BitWidth)) { // Avoid undefined shifts.
42029 unsigned MaskBits = BitWidth - ShAmt.getZExtValue();
42030 APInt Mask = Op.getOpcode() == ISD::SRL
42031 ? APInt::getHighBitsSet(BitWidth, MaskBits)
42032 : APInt::getLowBitsSet(BitWidth, MaskBits);
42033 if (Mask.isSignedIntN(32)) {
42034 Op = DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0),
42035 DAG.getConstant(Mask, dl, VT));
42036 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
42037 DAG.getConstant(0, dl, VT));
42038 }
42039 }
42040 }
42041
42042 // Look for a truncate with a single use.
42043 if (Op.getOpcode() != ISD::TRUNCATE || !Op.hasOneUse())
42044 return SDValue();
42045
42046 Op = Op.getOperand(0);
42047
42048 // Arithmetic op can only have one use.
42049 if (!Op.hasOneUse())
42050 return SDValue();
42051
42052 unsigned NewOpc;
42053 switch (Op.getOpcode()) {
42054 default: return SDValue();
42055 case ISD::AND:
42056 // Skip and with constant. We have special handling for and with immediate
42057 // during isel to generate test instructions.
42058 if (isa<ConstantSDNode>(Op.getOperand(1)))
42059 return SDValue();
42060 NewOpc = X86ISD::AND;
42061 break;
42062 case ISD::OR: NewOpc = X86ISD::OR; break;
42063 case ISD::XOR: NewOpc = X86ISD::XOR; break;
42064 case ISD::ADD:
42065 // If the carry or overflow flag is used, we can't truncate.
42066 if (needCarryOrOverflowFlag(SDValue(N, 0)))
42067 return SDValue();
42068 NewOpc = X86ISD::ADD;
42069 break;
42070 case ISD::SUB:
42071 // If the carry or overflow flag is used, we can't truncate.
42072 if (needCarryOrOverflowFlag(SDValue(N, 0)))
42073 return SDValue();
42074 NewOpc = X86ISD::SUB;
42075 break;
42076 }
42077
42078 // We found an op we can narrow. Truncate its inputs.
42079 SDValue Op0 = DAG.getNode(ISD::TRUNCATE, dl, VT, Op.getOperand(0));
42080 SDValue Op1 = DAG.getNode(ISD::TRUNCATE, dl, VT, Op.getOperand(1));
42081
42082 // Use a X86 specific opcode to avoid DAG combine messing with it.
42083 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
42084 Op = DAG.getNode(NewOpc, dl, VTs, Op0, Op1);
42085
42086 // For AND, keep a CMP so that we can match the test pattern.
42087 if (NewOpc == X86ISD::AND)
42088 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
42089 DAG.getConstant(0, dl, VT));
42090
42091 // Return the flags.
42092 return Op.getValue(1);
42093}
42094
42095static SDValue combineX86AddSub(SDNode *N, SelectionDAG &DAG,
42096 TargetLowering::DAGCombinerInfo &DCI) {
42097 assert((X86ISD::ADD == N->getOpcode() || X86ISD::SUB == N->getOpcode()) &&(((X86ISD::ADD == N->getOpcode() || X86ISD::SUB == N->getOpcode
()) && "Expected X86ISD::ADD or X86ISD::SUB") ? static_cast
<void> (0) : __assert_fail ("(X86ISD::ADD == N->getOpcode() || X86ISD::SUB == N->getOpcode()) && \"Expected X86ISD::ADD or X86ISD::SUB\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 42098, __PRETTY_FUNCTION__))
42098 "Expected X86ISD::ADD or X86ISD::SUB")(((X86ISD::ADD == N->getOpcode() || X86ISD::SUB == N->getOpcode
()) && "Expected X86ISD::ADD or X86ISD::SUB") ? static_cast
<void> (0) : __assert_fail ("(X86ISD::ADD == N->getOpcode() || X86ISD::SUB == N->getOpcode()) && \"Expected X86ISD::ADD or X86ISD::SUB\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 42098, __PRETTY_FUNCTION__))
;
42099
42100 SDValue LHS = N->getOperand(0);
42101 SDValue RHS = N->getOperand(1);
42102 MVT VT = LHS.getSimpleValueType();
42103 unsigned GenericOpc = X86ISD::ADD == N->getOpcode() ? ISD::ADD : ISD::SUB;
42104
42105 // If we don't use the flag result, simplify back to a generic ADD/SUB.
42106 if (!N->hasAnyUseOfValue(1)) {
42107 SDLoc DL(N);
42108 SDValue Res = DAG.getNode(GenericOpc, DL, VT, LHS, RHS);
42109 return DAG.getMergeValues({Res, DAG.getConstant(0, DL, MVT::i32)}, DL);
42110 }
42111
42112 // Fold any similar generic ADD/SUB opcodes to reuse this node.
42113 auto MatchGeneric = [&](SDValue N0, SDValue N1, bool Negate) {
42114 // TODO: Add SUB(RHS, LHS) -> SUB(0, SUB(LHS, RHS)) negation support, this
42115 // currently causes regressions as we don't have broad x86sub combines.
42116 if (Negate)
42117 return;
42118 SDValue Ops[] = {N0, N1};
42119 SDVTList VTs = DAG.getVTList(N->getValueType(0));
42120 if (SDNode *GenericAddSub = DAG.getNodeIfExists(GenericOpc, VTs, Ops))
42121 DCI.CombineTo(GenericAddSub, SDValue(N, 0));
42122 };
42123 MatchGeneric(LHS, RHS, false);
42124 MatchGeneric(RHS, LHS, X86ISD::SUB == N->getOpcode());
42125
42126 return SDValue();
42127}
42128
42129static SDValue combineSBB(SDNode *N, SelectionDAG &DAG) {
42130 if (SDValue Flags = combineCarryThroughADD(N->getOperand(2), DAG)) {
42131 MVT VT = N->getSimpleValueType(0);
42132 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
42133 return DAG.getNode(X86ISD::SBB, SDLoc(N), VTs,
42134 N->getOperand(0), N->getOperand(1),
42135 Flags);
42136 }
42137
42138 // Fold SBB(SUB(X,Y),0,Carry) -> SBB(X,Y,Carry)
42139 // iff the flag result is dead.
42140 SDValue Op0 = N->getOperand(0);
42141 SDValue Op1 = N->getOperand(1);
42142 if (Op0.getOpcode() == ISD::SUB && isNullConstant(Op1) &&
42143 !N->hasAnyUseOfValue(1))
42144 return DAG.getNode(X86ISD::SBB, SDLoc(N), N->getVTList(), Op0.getOperand(0),
42145 Op0.getOperand(1), N->getOperand(2));
42146
42147 return SDValue();
42148}
42149
42150// Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
42151static SDValue combineADC(SDNode *N, SelectionDAG &DAG,
42152 TargetLowering::DAGCombinerInfo &DCI) {
42153 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
42154 // the result is either zero or one (depending on the input carry bit).
42155 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
42156 if (X86::isZeroNode(N->getOperand(0)) &&
42157 X86::isZeroNode(N->getOperand(1)) &&
42158 // We don't have a good way to replace an EFLAGS use, so only do this when
42159 // dead right now.
42160 SDValue(N, 1).use_empty()) {
42161 SDLoc DL(N);
42162 EVT VT = N->getValueType(0);
42163 SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
42164 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
42165 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
42166 DAG.getConstant(X86::COND_B, DL,
42167 MVT::i8),
42168 N->getOperand(2)),
42169 DAG.getConstant(1, DL, VT));
42170 return DCI.CombineTo(N, Res1, CarryOut);
42171 }
42172
42173 if (SDValue Flags = combineCarryThroughADD(N->getOperand(2), DAG)) {
42174 MVT VT = N->getSimpleValueType(0);
42175 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
42176 return DAG.getNode(X86ISD::ADC, SDLoc(N), VTs,
42177 N->getOperand(0), N->getOperand(1),
42178 Flags);
42179 }
42180
42181 return SDValue();
42182}
42183
42184/// If this is an add or subtract where one operand is produced by a cmp+setcc,
42185/// then try to convert it to an ADC or SBB. This replaces TEST+SET+{ADD/SUB}
42186/// with CMP+{ADC, SBB}.
42187static SDValue combineAddOrSubToADCOrSBB(SDNode *N, SelectionDAG &DAG) {
42188 bool IsSub = N->getOpcode() == ISD::SUB;
42189 SDValue X = N->getOperand(0);
42190 SDValue Y = N->getOperand(1);
42191
42192 // If this is an add, canonicalize a zext operand to the RHS.
42193 // TODO: Incomplete? What if both sides are zexts?
42194 if (!IsSub && X.getOpcode() == ISD::ZERO_EXTEND &&
42195 Y.getOpcode() != ISD::ZERO_EXTEND)
42196 std::swap(X, Y);
42197
42198 // Look through a one-use zext.
42199 bool PeekedThroughZext = false;
42200 if (Y.getOpcode() == ISD::ZERO_EXTEND && Y.hasOneUse()) {
42201 Y = Y.getOperand(0);
42202 PeekedThroughZext = true;
42203 }
42204
42205 // If this is an add, canonicalize a setcc operand to the RHS.
42206 // TODO: Incomplete? What if both sides are setcc?
42207 // TODO: Should we allow peeking through a zext of the other operand?
42208 if (!IsSub && !PeekedThroughZext && X.getOpcode() == X86ISD::SETCC &&
42209 Y.getOpcode() != X86ISD::SETCC)
42210 std::swap(X, Y);
42211
42212 if (Y.getOpcode() != X86ISD::SETCC || !Y.hasOneUse())
42213 return SDValue();
42214
42215 SDLoc DL(N);
42216 EVT VT = N->getValueType(0);
42217 X86::CondCode CC = (X86::CondCode)Y.getConstantOperandVal(0);
42218
42219 // If X is -1 or 0, then we have an opportunity to avoid constants required in
42220 // the general case below.
42221 auto *ConstantX = dyn_cast<ConstantSDNode>(X);
42222 if (ConstantX) {
42223 if ((!IsSub && CC == X86::COND_AE && ConstantX->isAllOnesValue()) ||
42224 (IsSub && CC == X86::COND_B && ConstantX->isNullValue())) {
42225 // This is a complicated way to get -1 or 0 from the carry flag:
42226 // -1 + SETAE --> -1 + (!CF) --> CF ? -1 : 0 --> SBB %eax, %eax
42227 // 0 - SETB --> 0 - (CF) --> CF ? -1 : 0 --> SBB %eax, %eax
42228 return DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
42229 DAG.getConstant(X86::COND_B, DL, MVT::i8),
42230 Y.getOperand(1));
42231 }
42232
42233 if ((!IsSub && CC == X86::COND_BE && ConstantX->isAllOnesValue()) ||
42234 (IsSub && CC == X86::COND_A && ConstantX->isNullValue())) {
42235 SDValue EFLAGS = Y->getOperand(1);
42236 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
42237 EFLAGS.getValueType().isInteger() &&
42238 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
42239 // Swap the operands of a SUB, and we have the same pattern as above.
42240 // -1 + SETBE (SUB A, B) --> -1 + SETAE (SUB B, A) --> SUB + SBB
42241 // 0 - SETA (SUB A, B) --> 0 - SETB (SUB B, A) --> SUB + SBB
42242 SDValue NewSub = DAG.getNode(
42243 X86ISD::SUB, SDLoc(EFLAGS), EFLAGS.getNode()->getVTList(),
42244 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
42245 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
42246 return DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
42247 DAG.getConstant(X86::COND_B, DL, MVT::i8),
42248 NewEFLAGS);
42249 }
42250 }
42251 }
42252
42253 if (CC == X86::COND_B) {
42254 // X + SETB Z --> adc X, 0
42255 // X - SETB Z --> sbb X, 0
42256 return DAG.getNode(IsSub ? X86ISD::SBB : X86ISD::ADC, DL,
42257 DAG.getVTList(VT, MVT::i32), X,
42258 DAG.getConstant(0, DL, VT), Y.getOperand(1));
42259 }
42260
42261 if (CC == X86::COND_A) {
42262 SDValue EFLAGS = Y->getOperand(1);
42263 // Try to convert COND_A into COND_B in an attempt to facilitate
42264 // materializing "setb reg".
42265 //
42266 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
42267 // cannot take an immediate as its first operand.
42268 //
42269 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.getNode()->hasOneUse() &&
42270 EFLAGS.getValueType().isInteger() &&
42271 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
42272 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
42273 EFLAGS.getNode()->getVTList(),
42274 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
42275 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
42276 return DAG.getNode(IsSub ? X86ISD::SBB : X86ISD::ADC, DL,
42277 DAG.getVTList(VT, MVT::i32), X,
42278 DAG.getConstant(0, DL, VT), NewEFLAGS);
42279 }
42280 }
42281
42282 if (CC != X86::COND_E && CC != X86::COND_NE)
42283 return SDValue();
42284
42285 SDValue Cmp = Y.getOperand(1);
42286 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
42287 !X86::isZeroNode(Cmp.getOperand(1)) ||
42288 !Cmp.getOperand(0).getValueType().isInteger())
42289 return SDValue();
42290
42291 SDValue Z = Cmp.getOperand(0);
42292 EVT ZVT = Z.getValueType();
42293
42294 // If X is -1 or 0, then we have an opportunity to avoid constants required in
42295 // the general case below.
42296 if (ConstantX) {
42297 // 'neg' sets the carry flag when Z != 0, so create 0 or -1 using 'sbb' with
42298 // fake operands:
42299 // 0 - (Z != 0) --> sbb %eax, %eax, (neg Z)
42300 // -1 + (Z == 0) --> sbb %eax, %eax, (neg Z)
42301 if ((IsSub && CC == X86::COND_NE && ConstantX->isNullValue()) ||
42302 (!IsSub && CC == X86::COND_E && ConstantX->isAllOnesValue())) {
42303 SDValue Zero = DAG.getConstant(0, DL, ZVT);
42304 SDVTList X86SubVTs = DAG.getVTList(ZVT, MVT::i32);
42305 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, X86SubVTs, Zero, Z);
42306 return DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
42307 DAG.getConstant(X86::COND_B, DL, MVT::i8),
42308 SDValue(Neg.getNode(), 1));
42309 }
42310
42311 // cmp with 1 sets the carry flag when Z == 0, so create 0 or -1 using 'sbb'
42312 // with fake operands:
42313 // 0 - (Z == 0) --> sbb %eax, %eax, (cmp Z, 1)
42314 // -1 + (Z != 0) --> sbb %eax, %eax, (cmp Z, 1)
42315 if ((IsSub && CC == X86::COND_E && ConstantX->isNullValue()) ||
42316 (!IsSub && CC == X86::COND_NE && ConstantX->isAllOnesValue())) {
42317 SDValue One = DAG.getConstant(1, DL, ZVT);
42318 SDValue Cmp1 = DAG.getNode(X86ISD::CMP, DL, MVT::i32, Z, One);
42319 return DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
42320 DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp1);
42321 }
42322 }
42323
42324 // (cmp Z, 1) sets the carry flag if Z is 0.
42325 SDValue One = DAG.getConstant(1, DL, ZVT);
42326 SDValue Cmp1 = DAG.getNode(X86ISD::CMP, DL, MVT::i32, Z, One);
42327
42328 // Add the flags type for ADC/SBB nodes.
42329 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
42330
42331 // X - (Z != 0) --> sub X, (zext(setne Z, 0)) --> adc X, -1, (cmp Z, 1)
42332 // X + (Z != 0) --> add X, (zext(setne Z, 0)) --> sbb X, -1, (cmp Z, 1)
42333 if (CC == X86::COND_NE)
42334 return DAG.getNode(IsSub ? X86ISD::ADC : X86ISD::SBB, DL, VTs, X,
42335 DAG.getConstant(-1ULL, DL, VT), Cmp1);
42336
42337 // X - (Z == 0) --> sub X, (zext(sete Z, 0)) --> sbb X, 0, (cmp Z, 1)
42338 // X + (Z == 0) --> add X, (zext(sete Z, 0)) --> adc X, 0, (cmp Z, 1)
42339 return DAG.getNode(IsSub ? X86ISD::SBB : X86ISD::ADC, DL, VTs, X,
42340 DAG.getConstant(0, DL, VT), Cmp1);
42341}
42342
42343static SDValue combineLoopMAddPattern(SDNode *N, SelectionDAG &DAG,
42344 const X86Subtarget &Subtarget) {
42345 if (!Subtarget.hasSSE2())
42346 return SDValue();
42347
42348 SDValue Op0 = N->getOperand(0);
42349 SDValue Op1 = N->getOperand(1);
42350
42351 EVT VT = N->getValueType(0);
42352
42353 // If the vector size is less than 128, or greater than the supported RegSize,
42354 // do not use PMADD.
42355 if (!VT.isVector() || VT.getVectorNumElements() < 8)
42356 return SDValue();
42357
42358 if (Op0.getOpcode() != ISD::MUL)
42359 std::swap(Op0, Op1);
42360 if (Op0.getOpcode() != ISD::MUL)
42361 return SDValue();
42362
42363 ShrinkMode Mode;
42364 if (!canReduceVMulWidth(Op0.getNode(), DAG, Mode) || Mode == MULU16)
42365 return SDValue();
42366
42367 SDLoc DL(N);
42368 EVT ReducedVT = EVT::getVectorVT(*DAG.getContext(), MVT::i16,
42369 VT.getVectorNumElements());
42370 EVT MAddVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
42371 VT.getVectorNumElements() / 2);
42372
42373 // Madd vector size is half of the original vector size
42374 auto PMADDWDBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
42375 ArrayRef<SDValue> Ops) {
42376 MVT OpVT = MVT::getVectorVT(MVT::i32, Ops[0].getValueSizeInBits() / 32);
42377 return DAG.getNode(X86ISD::VPMADDWD, DL, OpVT, Ops);
42378 };
42379
42380 auto BuildPMADDWD = [&](SDValue Mul) {
42381 // Shrink the operands of mul.
42382 SDValue N0 = DAG.getNode(ISD::TRUNCATE, DL, ReducedVT, Mul.getOperand(0));
42383 SDValue N1 = DAG.getNode(ISD::TRUNCATE, DL, ReducedVT, Mul.getOperand(1));
42384
42385 SDValue Madd = SplitOpsAndApply(DAG, Subtarget, DL, MAddVT, { N0, N1 },
42386 PMADDWDBuilder);
42387 // Fill the rest of the output with 0
42388 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Madd,
42389 DAG.getConstant(0, DL, MAddVT));
42390 };
42391
42392 Op0 = BuildPMADDWD(Op0);
42393
42394 // It's possible that Op1 is also a mul we can reduce.
42395 if (Op1.getOpcode() == ISD::MUL &&
42396 canReduceVMulWidth(Op1.getNode(), DAG, Mode) && Mode != MULU16) {
42397 Op1 = BuildPMADDWD(Op1);
42398 }
42399
42400 return DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
42401}
42402
42403static SDValue combineLoopSADPattern(SDNode *N, SelectionDAG &DAG,
42404 const X86Subtarget &Subtarget) {
42405 if (!Subtarget.hasSSE2())
42406 return SDValue();
42407
42408 SDLoc DL(N);
42409 EVT VT = N->getValueType(0);
42410 SDValue Op0 = N->getOperand(0);
42411 SDValue Op1 = N->getOperand(1);
42412
42413 // TODO: There's nothing special about i32, any integer type above i16 should
42414 // work just as well.
42415 if (!VT.isVector() || !VT.isSimple() ||
42416 !(VT.getVectorElementType() == MVT::i32))
42417 return SDValue();
42418
42419 unsigned RegSize = 128;
42420 if (Subtarget.useBWIRegs())
42421 RegSize = 512;
42422 else if (Subtarget.hasAVX())
42423 RegSize = 256;
42424
42425 // We only handle v16i32 for SSE2 / v32i32 for AVX / v64i32 for AVX512.
42426 // TODO: We should be able to handle larger vectors by splitting them before
42427 // feeding them into several SADs, and then reducing over those.
42428 if (VT.getSizeInBits() / 4 > RegSize)
42429 return SDValue();
42430
42431 // We know N is a reduction add, which means one of its operands is a phi.
42432 // To match SAD, we need the other operand to be a ABS.
42433 if (Op0.getOpcode() != ISD::ABS)
42434 std::swap(Op0, Op1);
42435 if (Op0.getOpcode() != ISD::ABS)
42436 return SDValue();
42437
42438 auto BuildPSADBW = [&](SDValue Op0, SDValue Op1) {
42439 // SAD pattern detected. Now build a SAD instruction and an addition for
42440 // reduction. Note that the number of elements of the result of SAD is less
42441 // than the number of elements of its input. Therefore, we could only update
42442 // part of elements in the reduction vector.
42443 SDValue Sad = createPSADBW(DAG, Op0, Op1, DL, Subtarget);
42444
42445 // The output of PSADBW is a vector of i64.
42446 // We need to turn the vector of i64 into a vector of i32.
42447 // If the reduction vector is at least as wide as the psadbw result, just
42448 // bitcast. If it's narrower, truncate - the high i32 of each i64 is zero
42449 // anyway.
42450 MVT ResVT = MVT::getVectorVT(MVT::i32, Sad.getValueSizeInBits() / 32);
42451 if (VT.getSizeInBits() >= ResVT.getSizeInBits())
42452 Sad = DAG.getNode(ISD::BITCAST, DL, ResVT, Sad);
42453 else
42454 Sad = DAG.getNode(ISD::TRUNCATE, DL, VT, Sad);
42455
42456 if (VT.getSizeInBits() > ResVT.getSizeInBits()) {
42457 // Fill the upper elements with zero to match the add width.
42458 SDValue Zero = DAG.getConstant(0, DL, VT);
42459 Sad = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Zero, Sad,
42460 DAG.getIntPtrConstant(0, DL));
42461 }
42462
42463 return Sad;
42464 };
42465
42466 // Check whether we have an abs-diff pattern feeding into the select.
42467 SDValue SadOp0, SadOp1;
42468 if (!detectZextAbsDiff(Op0, SadOp0, SadOp1))
42469 return SDValue();
42470
42471 Op0 = BuildPSADBW(SadOp0, SadOp1);
42472
42473 // It's possible we have a sad on the other side too.
42474 if (Op1.getOpcode() == ISD::ABS &&
42475 detectZextAbsDiff(Op1, SadOp0, SadOp1)) {
42476 Op1 = BuildPSADBW(SadOp0, SadOp1);
42477 }
42478
42479 return DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
42480}
42481
42482/// Convert vector increment or decrement to sub/add with an all-ones constant:
42483/// add X, <1, 1...> --> sub X, <-1, -1...>
42484/// sub X, <1, 1...> --> add X, <-1, -1...>
42485/// The all-ones vector constant can be materialized using a pcmpeq instruction
42486/// that is commonly recognized as an idiom (has no register dependency), so
42487/// that's better/smaller than loading a splat 1 constant.
42488static SDValue combineIncDecVector(SDNode *N, SelectionDAG &DAG) {
42489 assert((N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&(((N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::
SUB) && "Unexpected opcode for increment/decrement transform"
) ? static_cast<void> (0) : __assert_fail ("(N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) && \"Unexpected opcode for increment/decrement transform\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 42490, __PRETTY_FUNCTION__))
42490 "Unexpected opcode for increment/decrement transform")(((N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::
SUB) && "Unexpected opcode for increment/decrement transform"
) ? static_cast<void> (0) : __assert_fail ("(N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) && \"Unexpected opcode for increment/decrement transform\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 42490, __PRETTY_FUNCTION__))
;
42491
42492 // Pseudo-legality check: getOnesVector() expects one of these types, so bail
42493 // out and wait for legalization if we have an unsupported vector length.
42494 EVT VT = N->getValueType(0);
42495 if (!VT.is128BitVector() && !VT.is256BitVector() && !VT.is512BitVector())
42496 return SDValue();
42497
42498 APInt SplatVal;
42499 if (!isConstantSplat(N->getOperand(1), SplatVal) || !SplatVal.isOneValue())
42500 return SDValue();
42501
42502 SDValue AllOnesVec = getOnesVector(VT, DAG, SDLoc(N));
42503 unsigned NewOpcode = N->getOpcode() == ISD::ADD ? ISD::SUB : ISD::ADD;
42504 return DAG.getNode(NewOpcode, SDLoc(N), VT, N->getOperand(0), AllOnesVec);
42505}
42506
42507static SDValue matchPMADDWD(SelectionDAG &DAG, SDValue Op0, SDValue Op1,
42508 const SDLoc &DL, EVT VT,
42509 const X86Subtarget &Subtarget) {
42510 // Example of pattern we try to detect:
42511 // t := (v8i32 mul (sext (v8i16 x0), (sext (v8i16 x1))))
42512 //(add (build_vector (extract_elt t, 0),
42513 // (extract_elt t, 2),
42514 // (extract_elt t, 4),
42515 // (extract_elt t, 6)),
42516 // (build_vector (extract_elt t, 1),
42517 // (extract_elt t, 3),
42518 // (extract_elt t, 5),
42519 // (extract_elt t, 7)))
42520
42521 if (!Subtarget.hasSSE2())
42522 return SDValue();
42523
42524 if (Op0.getOpcode() != ISD::BUILD_VECTOR ||
42525 Op1.getOpcode() != ISD::BUILD_VECTOR)
42526 return SDValue();
42527
42528 if (!VT.isVector() || VT.getVectorElementType() != MVT::i32 ||
42529 VT.getVectorNumElements() < 4 ||
42530 !isPowerOf2_32(VT.getVectorNumElements()))
42531 return SDValue();
42532
42533 // Check if one of Op0,Op1 is of the form:
42534 // (build_vector (extract_elt Mul, 0),
42535 // (extract_elt Mul, 2),
42536 // (extract_elt Mul, 4),
42537 // ...
42538 // the other is of the form:
42539 // (build_vector (extract_elt Mul, 1),
42540 // (extract_elt Mul, 3),
42541 // (extract_elt Mul, 5),
42542 // ...
42543 // and identify Mul.
42544 SDValue Mul;
42545 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; i += 2) {
42546 SDValue Op0L = Op0->getOperand(i), Op1L = Op1->getOperand(i),
42547 Op0H = Op0->getOperand(i + 1), Op1H = Op1->getOperand(i + 1);
42548 // TODO: Be more tolerant to undefs.
42549 if (Op0L.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
42550 Op1L.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
42551 Op0H.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
42552 Op1H.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
42553 return SDValue();
42554 auto *Const0L = dyn_cast<ConstantSDNode>(Op0L->getOperand(1));
42555 auto *Const1L = dyn_cast<ConstantSDNode>(Op1L->getOperand(1));
42556 auto *Const0H = dyn_cast<ConstantSDNode>(Op0H->getOperand(1));
42557 auto *Const1H = dyn_cast<ConstantSDNode>(Op1H->getOperand(1));
42558 if (!Const0L || !Const1L || !Const0H || !Const1H)
42559 return SDValue();
42560 unsigned Idx0L = Const0L->getZExtValue(), Idx1L = Const1L->getZExtValue(),
42561 Idx0H = Const0H->getZExtValue(), Idx1H = Const1H->getZExtValue();
42562 // Commutativity of mul allows factors of a product to reorder.
42563 if (Idx0L > Idx1L)
42564 std::swap(Idx0L, Idx1L);
42565 if (Idx0H > Idx1H)
42566 std::swap(Idx0H, Idx1H);
42567 // Commutativity of add allows pairs of factors to reorder.
42568 if (Idx0L > Idx0H) {
42569 std::swap(Idx0L, Idx0H);
42570 std::swap(Idx1L, Idx1H);
42571 }
42572 if (Idx0L != 2 * i || Idx1L != 2 * i + 1 || Idx0H != 2 * i + 2 ||
42573 Idx1H != 2 * i + 3)
42574 return SDValue();
42575 if (!Mul) {
42576 // First time an extract_elt's source vector is visited. Must be a MUL
42577 // with 2X number of vector elements than the BUILD_VECTOR.
42578 // Both extracts must be from same MUL.
42579 Mul = Op0L->getOperand(0);
42580 if (Mul->getOpcode() != ISD::MUL ||
42581 Mul.getValueType().getVectorNumElements() != 2 * e)
42582 return SDValue();
42583 }
42584 // Check that the extract is from the same MUL previously seen.
42585 if (Mul != Op0L->getOperand(0) || Mul != Op1L->getOperand(0) ||
42586 Mul != Op0H->getOperand(0) || Mul != Op1H->getOperand(0))
42587 return SDValue();
42588 }
42589
42590 // Check if the Mul source can be safely shrunk.
42591 ShrinkMode Mode;
42592 if (!canReduceVMulWidth(Mul.getNode(), DAG, Mode) || Mode == MULU16)
42593 return SDValue();
42594
42595 auto PMADDBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
42596 ArrayRef<SDValue> Ops) {
42597 // Shrink by adding truncate nodes and let DAGCombine fold with the
42598 // sources.
42599 EVT InVT = Ops[0].getValueType();
42600 assert(InVT.getScalarType() == MVT::i32 &&((InVT.getScalarType() == MVT::i32 && "Unexpected scalar element type"
) ? static_cast<void> (0) : __assert_fail ("InVT.getScalarType() == MVT::i32 && \"Unexpected scalar element type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 42601, __PRETTY_FUNCTION__))
42601 "Unexpected scalar element type")((InVT.getScalarType() == MVT::i32 && "Unexpected scalar element type"
) ? static_cast<void> (0) : __assert_fail ("InVT.getScalarType() == MVT::i32 && \"Unexpected scalar element type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 42601, __PRETTY_FUNCTION__))
;
42602 assert(InVT == Ops[1].getValueType() && "Operands' types mismatch")((InVT == Ops[1].getValueType() && "Operands' types mismatch"
) ? static_cast<void> (0) : __assert_fail ("InVT == Ops[1].getValueType() && \"Operands' types mismatch\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 42602, __PRETTY_FUNCTION__))
;
42603 EVT ResVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
42604 InVT.getVectorNumElements() / 2);
42605 EVT TruncVT = EVT::getVectorVT(*DAG.getContext(), MVT::i16,
42606 InVT.getVectorNumElements());
42607 return DAG.getNode(X86ISD::VPMADDWD, DL, ResVT,
42608 DAG.getNode(ISD::TRUNCATE, DL, TruncVT, Ops[0]),
42609 DAG.getNode(ISD::TRUNCATE, DL, TruncVT, Ops[1]));
42610 };
42611 return SplitOpsAndApply(DAG, Subtarget, DL, VT,
42612 { Mul.getOperand(0), Mul.getOperand(1) },
42613 PMADDBuilder);
42614}
42615
42616// Attempt to turn this pattern into PMADDWD.
42617// (mul (add (zext (build_vector)), (zext (build_vector))),
42618// (add (zext (build_vector)), (zext (build_vector)))
42619static SDValue matchPMADDWD_2(SelectionDAG &DAG, SDValue N0, SDValue N1,
42620 const SDLoc &DL, EVT VT,
42621 const X86Subtarget &Subtarget) {
42622 if (!Subtarget.hasSSE2())
42623 return SDValue();
42624
42625 if (N0.getOpcode() != ISD::MUL || N1.getOpcode() != ISD::MUL)
42626 return SDValue();
42627
42628 if (!VT.isVector() || VT.getVectorElementType() != MVT::i32 ||
42629 VT.getVectorNumElements() < 4 ||
42630 !isPowerOf2_32(VT.getVectorNumElements()))
42631 return SDValue();
42632
42633 SDValue N00 = N0.getOperand(0);
42634 SDValue N01 = N0.getOperand(1);
42635 SDValue N10 = N1.getOperand(0);
42636 SDValue N11 = N1.getOperand(1);
42637
42638 // All inputs need to be sign extends.
42639 // TODO: Support ZERO_EXTEND from known positive?
42640 if (N00.getOpcode() != ISD::SIGN_EXTEND ||
42641 N01.getOpcode() != ISD::SIGN_EXTEND ||
42642 N10.getOpcode() != ISD::SIGN_EXTEND ||
42643 N11.getOpcode() != ISD::SIGN_EXTEND)
42644 return SDValue();
42645
42646 // Peek through the extends.
42647 N00 = N00.getOperand(0);
42648 N01 = N01.getOperand(0);
42649 N10 = N10.getOperand(0);
42650 N11 = N11.getOperand(0);
42651
42652 // Must be extending from vXi16.
42653 EVT InVT = N00.getValueType();
42654 if (InVT.getVectorElementType() != MVT::i16 || N01.getValueType() != InVT ||
42655 N10.getValueType() != InVT || N11.getValueType() != InVT)
42656 return SDValue();
42657
42658 // All inputs should be build_vectors.
42659 if (N00.getOpcode() != ISD::BUILD_VECTOR ||
42660 N01.getOpcode() != ISD::BUILD_VECTOR ||
42661 N10.getOpcode() != ISD::BUILD_VECTOR ||
42662 N11.getOpcode() != ISD::BUILD_VECTOR)
42663 return SDValue();
42664
42665 // For each element, we need to ensure we have an odd element from one vector
42666 // multiplied by the odd element of another vector and the even element from
42667 // one of the same vectors being multiplied by the even element from the
42668 // other vector. So we need to make sure for each element i, this operator
42669 // is being performed:
42670 // A[2 * i] * B[2 * i] + A[2 * i + 1] * B[2 * i + 1]
42671 SDValue In0, In1;
42672 for (unsigned i = 0; i != N00.getNumOperands(); ++i) {
42673 SDValue N00Elt = N00.getOperand(i);
42674 SDValue N01Elt = N01.getOperand(i);
42675 SDValue N10Elt = N10.getOperand(i);
42676 SDValue N11Elt = N11.getOperand(i);
42677 // TODO: Be more tolerant to undefs.
42678 if (N00Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
42679 N01Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
42680 N10Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
42681 N11Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
42682 return SDValue();
42683 auto *ConstN00Elt = dyn_cast<ConstantSDNode>(N00Elt.getOperand(1));
42684 auto *ConstN01Elt = dyn_cast<ConstantSDNode>(N01Elt.getOperand(1));
42685 auto *ConstN10Elt = dyn_cast<ConstantSDNode>(N10Elt.getOperand(1));
42686 auto *ConstN11Elt = dyn_cast<ConstantSDNode>(N11Elt.getOperand(1));
42687 if (!ConstN00Elt || !ConstN01Elt || !ConstN10Elt || !ConstN11Elt)
42688 return SDValue();
42689 unsigned IdxN00 = ConstN00Elt->getZExtValue();
42690 unsigned IdxN01 = ConstN01Elt->getZExtValue();
42691 unsigned IdxN10 = ConstN10Elt->getZExtValue();
42692 unsigned IdxN11 = ConstN11Elt->getZExtValue();
42693 // Add is commutative so indices can be reordered.
42694 if (IdxN00 > IdxN10) {
42695 std::swap(IdxN00, IdxN10);
42696 std::swap(IdxN01, IdxN11);
42697 }
42698 // N0 indices be the even element. N1 indices must be the next odd element.
42699 if (IdxN00 != 2 * i || IdxN10 != 2 * i + 1 ||
42700 IdxN01 != 2 * i || IdxN11 != 2 * i + 1)
42701 return SDValue();
42702 SDValue N00In = N00Elt.getOperand(0);
42703 SDValue N01In = N01Elt.getOperand(0);
42704 SDValue N10In = N10Elt.getOperand(0);
42705 SDValue N11In = N11Elt.getOperand(0);
42706 // First time we find an input capture it.
42707 if (!In0) {
42708 In0 = N00In;
42709 In1 = N01In;
42710 }
42711 // Mul is commutative so the input vectors can be in any order.
42712 // Canonicalize to make the compares easier.
42713 if (In0 != N00In)
42714 std::swap(N00In, N01In);
42715 if (In0 != N10In)
42716 std::swap(N10In, N11In);
42717 if (In0 != N00In || In1 != N01In || In0 != N10In || In1 != N11In)
42718 return SDValue();
42719 }
42720
42721 auto PMADDBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
42722 ArrayRef<SDValue> Ops) {
42723 // Shrink by adding truncate nodes and let DAGCombine fold with the
42724 // sources.
42725 EVT OpVT = Ops[0].getValueType();
42726 assert(OpVT.getScalarType() == MVT::i16 &&((OpVT.getScalarType() == MVT::i16 && "Unexpected scalar element type"
) ? static_cast<void> (0) : __assert_fail ("OpVT.getScalarType() == MVT::i16 && \"Unexpected scalar element type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 42727, __PRETTY_FUNCTION__))
42727 "Unexpected scalar element type")((OpVT.getScalarType() == MVT::i16 && "Unexpected scalar element type"
) ? static_cast<void> (0) : __assert_fail ("OpVT.getScalarType() == MVT::i16 && \"Unexpected scalar element type\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 42727, __PRETTY_FUNCTION__))
;
42728 assert(OpVT == Ops[1].getValueType() && "Operands' types mismatch")((OpVT == Ops[1].getValueType() && "Operands' types mismatch"
) ? static_cast<void> (0) : __assert_fail ("OpVT == Ops[1].getValueType() && \"Operands' types mismatch\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 42728, __PRETTY_FUNCTION__))
;
42729 EVT ResVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
42730 OpVT.getVectorNumElements() / 2);
42731 return DAG.getNode(X86ISD::VPMADDWD, DL, ResVT, Ops[0], Ops[1]);
42732 };
42733 return SplitOpsAndApply(DAG, Subtarget, DL, VT, { In0, In1 },
42734 PMADDBuilder);
42735}
42736
42737static SDValue combineAdd(SDNode *N, SelectionDAG &DAG,
42738 const X86Subtarget &Subtarget) {
42739 const SDNodeFlags Flags = N->getFlags();
42740 if (Flags.hasVectorReduction()) {
42741 if (SDValue Sad = combineLoopSADPattern(N, DAG, Subtarget))
42742 return Sad;
42743 if (SDValue MAdd = combineLoopMAddPattern(N, DAG, Subtarget))
42744 return MAdd;
42745 }
42746 EVT VT = N->getValueType(0);
42747 SDValue Op0 = N->getOperand(0);
42748 SDValue Op1 = N->getOperand(1);
42749
42750 if (SDValue MAdd = matchPMADDWD(DAG, Op0, Op1, SDLoc(N), VT, Subtarget))
42751 return MAdd;
42752 if (SDValue MAdd = matchPMADDWD_2(DAG, Op0, Op1, SDLoc(N), VT, Subtarget))
42753 return MAdd;
42754
42755 // Try to synthesize horizontal adds from adds of shuffles.
42756 if ((VT == MVT::v8i16 || VT == MVT::v4i32 || VT == MVT::v16i16 ||
42757 VT == MVT::v8i32) &&
42758 Subtarget.hasSSSE3() &&
42759 isHorizontalBinOp(Op0, Op1, DAG, Subtarget, true)) {
42760 auto HADDBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
42761 ArrayRef<SDValue> Ops) {
42762 return DAG.getNode(X86ISD::HADD, DL, Ops[0].getValueType(), Ops);
42763 };
42764 return SplitOpsAndApply(DAG, Subtarget, SDLoc(N), VT, {Op0, Op1},
42765 HADDBuilder);
42766 }
42767
42768 if (SDValue V = combineIncDecVector(N, DAG))
42769 return V;
42770
42771 return combineAddOrSubToADCOrSBB(N, DAG);
42772}
42773
42774static SDValue combineSubToSubus(SDNode *N, SelectionDAG &DAG,
42775 const X86Subtarget &Subtarget) {
42776 SDValue Op0 = N->getOperand(0);
42777 SDValue Op1 = N->getOperand(1);
42778 EVT VT = N->getValueType(0);
42779
42780 // PSUBUS is supported, starting from SSE2, but truncation for v8i32
42781 // is only worth it with SSSE3 (PSHUFB).
42782 if (!(Subtarget.hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) &&
42783 !(Subtarget.hasSSSE3() && (VT == MVT::v8i32 || VT == MVT::v8i64)) &&
42784 !(Subtarget.hasAVX() && (VT == MVT::v32i8 || VT == MVT::v16i16)) &&
42785 !(Subtarget.useBWIRegs() && (VT == MVT::v64i8 || VT == MVT::v32i16 ||
42786 VT == MVT::v16i32 || VT == MVT::v8i64)))
42787 return SDValue();
42788
42789 SDValue SubusLHS, SubusRHS;
42790 // Try to find umax(a,b) - b or a - umin(a,b) patterns
42791 // they may be converted to subus(a,b).
42792 // TODO: Need to add IR canonicalization for this code.
42793 if (Op0.getOpcode() == ISD::UMAX) {
42794 SubusRHS = Op1;
42795 SDValue MaxLHS = Op0.getOperand(0);
42796 SDValue MaxRHS = Op0.getOperand(1);
42797 if (MaxLHS == Op1)
42798 SubusLHS = MaxRHS;
42799 else if (MaxRHS == Op1)
42800 SubusLHS = MaxLHS;
42801 else
42802 return SDValue();
42803 } else if (Op1.getOpcode() == ISD::UMIN) {
42804 SubusLHS = Op0;
42805 SDValue MinLHS = Op1.getOperand(0);
42806 SDValue MinRHS = Op1.getOperand(1);
42807 if (MinLHS == Op0)
42808 SubusRHS = MinRHS;
42809 else if (MinRHS == Op0)
42810 SubusRHS = MinLHS;
42811 else
42812 return SDValue();
42813 } else
42814 return SDValue();
42815
42816 auto USUBSATBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
42817 ArrayRef<SDValue> Ops) {
42818 return DAG.getNode(ISD::USUBSAT, DL, Ops[0].getValueType(), Ops);
42819 };
42820
42821 // PSUBUS doesn't support v8i32/v8i64/v16i32, but it can be enabled with
42822 // special preprocessing in some cases.
42823 if (VT != MVT::v8i32 && VT != MVT::v16i32 && VT != MVT::v8i64)
42824 return SplitOpsAndApply(DAG, Subtarget, SDLoc(N), VT,
42825 { SubusLHS, SubusRHS }, USUBSATBuilder);
42826
42827 // Special preprocessing case can be only applied
42828 // if the value was zero extended from 16 bit,
42829 // so we require first 16 bits to be zeros for 32 bit
42830 // values, or first 48 bits for 64 bit values.
42831 KnownBits Known = DAG.computeKnownBits(SubusLHS);
42832 unsigned NumZeros = Known.countMinLeadingZeros();
42833 if ((VT == MVT::v8i64 && NumZeros < 48) || NumZeros < 16)
42834 return SDValue();
42835
42836 EVT ExtType = SubusLHS.getValueType();
42837 EVT ShrinkedType;
42838 if (VT == MVT::v8i32 || VT == MVT::v8i64)
42839 ShrinkedType = MVT::v8i16;
42840 else
42841 ShrinkedType = NumZeros >= 24 ? MVT::v16i8 : MVT::v16i16;
42842
42843 // If SubusLHS is zeroextended - truncate SubusRHS to it's
42844 // size SubusRHS = umin(0xFFF.., SubusRHS).
42845 SDValue SaturationConst =
42846 DAG.getConstant(APInt::getLowBitsSet(ExtType.getScalarSizeInBits(),
42847 ShrinkedType.getScalarSizeInBits()),
42848 SDLoc(SubusLHS), ExtType);
42849 SDValue UMin = DAG.getNode(ISD::UMIN, SDLoc(SubusLHS), ExtType, SubusRHS,
42850 SaturationConst);
42851 SDValue NewSubusLHS =
42852 DAG.getZExtOrTrunc(SubusLHS, SDLoc(SubusLHS), ShrinkedType);
42853 SDValue NewSubusRHS = DAG.getZExtOrTrunc(UMin, SDLoc(SubusRHS), ShrinkedType);
42854 SDValue Psubus =
42855 SplitOpsAndApply(DAG, Subtarget, SDLoc(N), ShrinkedType,
42856 { NewSubusLHS, NewSubusRHS }, USUBSATBuilder);
42857 // Zero extend the result, it may be used somewhere as 32 bit,
42858 // if not zext and following trunc will shrink.
42859 return DAG.getZExtOrTrunc(Psubus, SDLoc(N), ExtType);
42860}
42861
42862static SDValue combineSub(SDNode *N, SelectionDAG &DAG,
42863 const X86Subtarget &Subtarget) {
42864 SDValue Op0 = N->getOperand(0);
42865 SDValue Op1 = N->getOperand(1);
42866
42867 // X86 can't encode an immediate LHS of a sub. See if we can push the
42868 // negation into a preceding instruction.
42869 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
42870 // If the RHS of the sub is a XOR with one use and a constant, invert the
42871 // immediate. Then add one to the LHS of the sub so we can turn
42872 // X-Y -> X+~Y+1, saving one register.
42873 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
42874 isa<ConstantSDNode>(Op1.getOperand(1))) {
42875 const APInt &XorC = Op1.getConstantOperandAPInt(1);
42876 EVT VT = Op0.getValueType();
42877 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
42878 Op1.getOperand(0),
42879 DAG.getConstant(~XorC, SDLoc(Op1), VT));
42880 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
42881 DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
42882 }
42883 }
42884
42885 // Try to synthesize horizontal subs from subs of shuffles.
42886 EVT VT = N->getValueType(0);
42887 if ((VT == MVT::v8i16 || VT == MVT::v4i32 || VT == MVT::v16i16 ||
42888 VT == MVT::v8i32) &&
42889 Subtarget.hasSSSE3() &&
42890 isHorizontalBinOp(Op0, Op1, DAG, Subtarget, false)) {
42891 auto HSUBBuilder = [](SelectionDAG &DAG, const SDLoc &DL,
42892 ArrayRef<SDValue> Ops) {
42893 return DAG.getNode(X86ISD::HSUB, DL, Ops[0].getValueType(), Ops);
42894 };
42895 return SplitOpsAndApply(DAG, Subtarget, SDLoc(N), VT, {Op0, Op1},
42896 HSUBBuilder);
42897 }
42898
42899 if (SDValue V = combineIncDecVector(N, DAG))
42900 return V;
42901
42902 // Try to create PSUBUS if SUB's argument is max/min
42903 if (SDValue V = combineSubToSubus(N, DAG, Subtarget))
42904 return V;
42905
42906 return combineAddOrSubToADCOrSBB(N, DAG);
42907}
42908
42909static SDValue combineVectorCompare(SDNode *N, SelectionDAG &DAG,
42910 const X86Subtarget &Subtarget) {
42911 MVT VT = N->getSimpleValueType(0);
42912 SDLoc DL(N);
42913
42914 if (N->getOperand(0) == N->getOperand(1)) {
42915 if (N->getOpcode() == X86ISD::PCMPEQ)
42916 return DAG.getConstant(-1, DL, VT);
42917 if (N->getOpcode() == X86ISD::PCMPGT)
42918 return DAG.getConstant(0, DL, VT);
42919 }
42920
42921 return SDValue();
42922}
42923
42924/// Helper that combines an array of subvector ops as if they were the operands
42925/// of a ISD::CONCAT_VECTORS node, but may have come from another source (e.g.
42926/// ISD::INSERT_SUBVECTOR). The ops are assumed to be of the same type.
42927static SDValue combineConcatVectorOps(const SDLoc &DL, MVT VT,
42928 ArrayRef<SDValue> Ops, SelectionDAG &DAG,
42929 TargetLowering::DAGCombinerInfo &DCI,
42930 const X86Subtarget &Subtarget) {
42931 assert(Subtarget.hasAVX() && "AVX assumed for concat_vectors")((Subtarget.hasAVX() && "AVX assumed for concat_vectors"
) ? static_cast<void> (0) : __assert_fail ("Subtarget.hasAVX() && \"AVX assumed for concat_vectors\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 42931, __PRETTY_FUNCTION__))
;
42932
42933 if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
42934 return DAG.getUNDEF(VT);
42935
42936 if (llvm::all_of(Ops, [](SDValue Op) {
42937 return ISD::isBuildVectorAllZeros(Op.getNode());
42938 }))
42939 return getZeroVector(VT, Subtarget, DAG, DL);
42940
42941 SDValue Op0 = Ops[0];
42942
42943 // Fold subvector loads into one.
42944 // If needed, look through bitcasts to get to the load.
42945 if (auto *FirstLd = dyn_cast<LoadSDNode>(peekThroughBitcasts(Op0))) {
42946 bool Fast;
42947 unsigned Alignment = FirstLd->getAlignment();
42948 unsigned AS = FirstLd->getAddressSpace();
42949 const X86TargetLowering *TLI = Subtarget.getTargetLowering();
42950 if (TLI->allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT, AS,
42951 Alignment, &Fast) &&
42952 Fast) {
42953 if (SDValue Ld =
42954 EltsFromConsecutiveLoads(VT, Ops, DL, DAG, Subtarget, false))
42955 return Ld;
42956 }
42957 }
42958
42959 // Repeated subvectors.
42960 if (llvm::all_of(Ops, [Op0](SDValue Op) { return Op == Op0; })) {
42961 // If this broadcast/subv_broadcast is inserted into both halves, use a
42962 // larger broadcast/subv_broadcast.
42963 if (Op0.getOpcode() == X86ISD::VBROADCAST ||
42964 Op0.getOpcode() == X86ISD::SUBV_BROADCAST)
42965 return DAG.getNode(Op0.getOpcode(), DL, VT, Op0.getOperand(0));
42966
42967 // concat_vectors(movddup(x),movddup(x)) -> broadcast(x)
42968 if (Op0.getOpcode() == X86ISD::MOVDDUP && VT == MVT::v4f64 &&
42969 (Subtarget.hasAVX2() || MayFoldLoad(Op0.getOperand(0))))
42970 return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
42971 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f64,
42972 Op0.getOperand(0),
42973 DAG.getIntPtrConstant(0, DL)));
42974
42975 // concat_vectors(scalar_to_vector(x),scalar_to_vector(x)) -> broadcast(x)
42976 if (Op0.getOpcode() == ISD::SCALAR_TO_VECTOR &&
42977 (Subtarget.hasAVX2() ||
42978 (VT.getScalarSizeInBits() >= 32 && MayFoldLoad(Op0.getOperand(0)))) &&
42979 Op0.getOperand(0).getValueType() == VT.getScalarType())
42980 return DAG.getNode(X86ISD::VBROADCAST, DL, VT, Op0.getOperand(0));
42981 }
42982
42983 // Repeated opcode.
42984 if (llvm::all_of(Ops, [Op0](SDValue Op) {
42985 return Op.getOpcode() == Op0.getOpcode();
42986 })) {
42987 unsigned NumOps = Ops.size();
42988 switch (Op0.getOpcode()) {
42989 case X86ISD::PACKUS:
42990 if (NumOps == 2 && VT.is256BitVector() && Subtarget.hasInt256()) {
42991 SmallVector<SDValue, 2> LHS, RHS;
42992 for (unsigned i = 0; i != NumOps; ++i) {
42993 LHS.push_back(Ops[i].getOperand(0));
42994 RHS.push_back(Ops[i].getOperand(1));
42995 }
42996 MVT SrcVT = Op0.getOperand(0).getSimpleValueType();
42997 SrcVT = MVT::getVectorVT(SrcVT.getScalarType(),
42998 NumOps * SrcVT.getVectorNumElements());
42999 return DAG.getNode(Op0.getOpcode(), DL, VT,
43000 DAG.getNode(ISD::CONCAT_VECTORS, DL, SrcVT, LHS),
43001 DAG.getNode(ISD::CONCAT_VECTORS, DL, SrcVT, RHS));
43002 }
43003 break;
43004 }
43005 }
43006
43007 // If we're inserting all zeros into the upper half, change this to
43008 // an insert into an all zeros vector. We will match this to a move
43009 // with implicit upper bit zeroing during isel.
43010 if (Ops.size() == 2 && ISD::isBuildVectorAllZeros(Ops[1].getNode()))
43011 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
43012 getZeroVector(VT, Subtarget, DAG, DL), Ops[0],
43013 DAG.getIntPtrConstant(0, DL));
43014
43015 return SDValue();
43016}
43017
43018static SDValue combineConcatVectors(SDNode *N, SelectionDAG &DAG,
43019 TargetLowering::DAGCombinerInfo &DCI,
43020 const X86Subtarget &Subtarget) {
43021 EVT VT = N->getValueType(0);
43022 EVT SrcVT = N->getOperand(0).getValueType();
43023 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
43024
43025 if (Subtarget.hasAVX() && TLI.isTypeLegal(VT) && TLI.isTypeLegal(SrcVT)) {
43026 SmallVector<SDValue, 4> Ops(N->op_begin(), N->op_end());
43027 if (SDValue R = combineConcatVectorOps(SDLoc(N), VT.getSimpleVT(), Ops, DAG,
43028 DCI, Subtarget))
43029 return R;
43030 }
43031
43032 return SDValue();
43033}
43034
43035static SDValue combineInsertSubvector(SDNode *N, SelectionDAG &DAG,
43036 TargetLowering::DAGCombinerInfo &DCI,
43037 const X86Subtarget &Subtarget) {
43038 if (DCI.isBeforeLegalizeOps())
43039 return SDValue();
43040
43041 MVT OpVT = N->getSimpleValueType(0);
43042
43043 bool IsI1Vector = OpVT.getVectorElementType() == MVT::i1;
43044
43045 SDLoc dl(N);
43046 SDValue Vec = N->getOperand(0);
43047 SDValue SubVec = N->getOperand(1);
43048
43049 unsigned IdxVal = N->getConstantOperandVal(2);
43050 MVT SubVecVT = SubVec.getSimpleValueType();
43051
43052 if (Vec.isUndef() && SubVec.isUndef())
43053 return DAG.getUNDEF(OpVT);
43054
43055 // Inserting undefs/zeros into zeros/undefs is a zero vector.
43056 if ((Vec.isUndef() || ISD::isBuildVectorAllZeros(Vec.getNode())) &&
43057 (SubVec.isUndef() || ISD::isBuildVectorAllZeros(SubVec.getNode())))
43058 return getZeroVector(OpVT, Subtarget, DAG, dl);
43059
43060 if (ISD::isBuildVectorAllZeros(Vec.getNode())) {
43061 // If we're inserting into a zero vector and then into a larger zero vector,
43062 // just insert into the larger zero vector directly.
43063 if (SubVec.getOpcode() == ISD::INSERT_SUBVECTOR &&
43064 ISD::isBuildVectorAllZeros(SubVec.getOperand(0).getNode())) {
43065 unsigned Idx2Val = SubVec.getConstantOperandVal(2);
43066 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT,
43067 getZeroVector(OpVT, Subtarget, DAG, dl),
43068 SubVec.getOperand(1),
43069 DAG.getIntPtrConstant(IdxVal + Idx2Val, dl));
43070 }
43071
43072 // If we're inserting into a zero vector and our input was extracted from an
43073 // insert into a zero vector of the same type and the extraction was at
43074 // least as large as the original insertion. Just insert the original
43075 // subvector into a zero vector.
43076 if (SubVec.getOpcode() == ISD::EXTRACT_SUBVECTOR && IdxVal == 0 &&
43077 SubVec.getConstantOperandVal(1) == 0 &&
43078 SubVec.getOperand(0).getOpcode() == ISD::INSERT_SUBVECTOR) {
43079 SDValue Ins = SubVec.getOperand(0);
43080 if (Ins.getConstantOperandVal(2) == 0 &&
43081 ISD::isBuildVectorAllZeros(Ins.getOperand(0).getNode()) &&
43082 Ins.getOperand(1).getValueSizeInBits() <= SubVecVT.getSizeInBits())
43083 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT,
43084 getZeroVector(OpVT, Subtarget, DAG, dl),
43085 Ins.getOperand(1), N->getOperand(2));
43086 }
43087 }
43088
43089 // Stop here if this is an i1 vector.
43090 if (IsI1Vector)
43091 return SDValue();
43092
43093 // If this is an insert of an extract, combine to a shuffle. Don't do this
43094 // if the insert or extract can be represented with a subregister operation.
43095 if (SubVec.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
43096 SubVec.getOperand(0).getSimpleValueType() == OpVT &&
43097 (IdxVal != 0 || !Vec.isUndef())) {
43098 int ExtIdxVal = SubVec.getConstantOperandVal(1);
43099 if (ExtIdxVal != 0) {
43100 int VecNumElts = OpVT.getVectorNumElements();
43101 int SubVecNumElts = SubVecVT.getVectorNumElements();
43102 SmallVector<int, 64> Mask(VecNumElts);
43103 // First create an identity shuffle mask.
43104 for (int i = 0; i != VecNumElts; ++i)
43105 Mask[i] = i;
43106 // Now insert the extracted portion.
43107 for (int i = 0; i != SubVecNumElts; ++i)
43108 Mask[i + IdxVal] = i + ExtIdxVal + VecNumElts;
43109
43110 return DAG.getVectorShuffle(OpVT, dl, Vec, SubVec.getOperand(0), Mask);
43111 }
43112 }
43113
43114 // Match concat_vector style patterns.
43115 SmallVector<SDValue, 2> SubVectorOps;
43116 if (collectConcatOps(N, SubVectorOps))
43117 if (SDValue Fold =
43118 combineConcatVectorOps(dl, OpVT, SubVectorOps, DAG, DCI, Subtarget))
43119 return Fold;
43120
43121 // If we are inserting into both halves of the vector, the starting vector
43122 // should be undef. If it isn't, make it so. Only do this if the early insert
43123 // has no other uses.
43124 // TODO: Should this be a generic DAG combine?
43125 // TODO: Why doesn't SimplifyDemandedVectorElts catch this?
43126 if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
43127 Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
43128 OpVT.getSizeInBits() == SubVecVT.getSizeInBits() * 2 &&
43129 isNullConstant(Vec.getOperand(2)) && !Vec.getOperand(0).isUndef() &&
43130 Vec.hasOneUse()) {
43131 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, DAG.getUNDEF(OpVT),
43132 Vec.getOperand(1), Vec.getOperand(2));
43133 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Vec, SubVec,
43134 N->getOperand(2));
43135 }
43136
43137 // If this is a broadcast insert into an upper undef, use a larger broadcast.
43138 if (Vec.isUndef() && IdxVal != 0 && SubVec.getOpcode() == X86ISD::VBROADCAST)
43139 return DAG.getNode(X86ISD::VBROADCAST, dl, OpVT, SubVec.getOperand(0));
43140
43141 return SDValue();
43142}
43143
43144static SDValue combineExtractSubvector(SDNode *N, SelectionDAG &DAG,
43145 TargetLowering::DAGCombinerInfo &DCI,
43146 const X86Subtarget &Subtarget) {
43147 // For AVX1 only, if we are extracting from a 256-bit and+not (which will
43148 // eventually get combined/lowered into ANDNP) with a concatenated operand,
43149 // split the 'and' into 128-bit ops to avoid the concatenate and extract.
43150 // We let generic combining take over from there to simplify the
43151 // insert/extract and 'not'.
43152 // This pattern emerges during AVX1 legalization. We handle it before lowering
43153 // to avoid complications like splitting constant vector loads.
43154
43155 // Capture the original wide type in the likely case that we need to bitcast
43156 // back to this type.
43157 if (!N->getValueType(0).isSimple())
43158 return SDValue();
43159
43160 MVT VT = N->getSimpleValueType(0);
43161 EVT WideVecVT = N->getOperand(0).getValueType();
43162 SDValue WideVec = peekThroughBitcasts(N->getOperand(0));
43163 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
43164 if (Subtarget.hasAVX() && !Subtarget.hasAVX2() &&
43165 TLI.isTypeLegal(WideVecVT) &&
43166 WideVecVT.getSizeInBits() == 256 && WideVec.getOpcode() == ISD::AND) {
43167 auto isConcatenatedNot = [] (SDValue V) {
43168 V = peekThroughBitcasts(V);
43169 if (!isBitwiseNot(V))
43170 return false;
43171 SDValue NotOp = V->getOperand(0);
43172 return peekThroughBitcasts(NotOp).getOpcode() == ISD::CONCAT_VECTORS;
43173 };
43174 if (isConcatenatedNot(WideVec.getOperand(0)) ||
43175 isConcatenatedNot(WideVec.getOperand(1))) {
43176 // extract (and v4i64 X, (not (concat Y1, Y2))), n -> andnp v2i64 X(n), Y1
43177 SDValue Concat = split256IntArith(WideVec, DAG);
43178 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), VT,
43179 DAG.getBitcast(WideVecVT, Concat), N->getOperand(1));
43180 }
43181 }
43182
43183 if (DCI.isBeforeLegalizeOps())
43184 return SDValue();
43185
43186 SDValue InVec = N->getOperand(0);
43187 unsigned IdxVal = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
43188
43189 if (ISD::isBuildVectorAllZeros(InVec.getNode()))
43190 return getZeroVector(VT, Subtarget, DAG, SDLoc(N));
43191
43192 if (ISD::isBuildVectorAllOnes(InVec.getNode())) {
43193 if (VT.getScalarType() == MVT::i1)
43194 return DAG.getConstant(1, SDLoc(N), VT);
43195 return getOnesVector(VT, DAG, SDLoc(N));
43196 }
43197
43198 if (InVec.getOpcode() == ISD::BUILD_VECTOR)
43199 return DAG.getBuildVector(
43200 VT, SDLoc(N),
43201 InVec.getNode()->ops().slice(IdxVal, VT.getVectorNumElements()));
43202
43203 // If we're extracting from a broadcast then we're better off just
43204 // broadcasting to the smaller type directly, assuming this is the only use.
43205 // As its a broadcast we don't care about the extraction index.
43206 if (InVec.getOpcode() == X86ISD::VBROADCAST && InVec.hasOneUse() &&
43207 InVec.getOperand(0).getValueSizeInBits() <= VT.getSizeInBits())
43208 return DAG.getNode(X86ISD::VBROADCAST, SDLoc(N), VT, InVec.getOperand(0));
43209
43210 // If we're extracting the lowest subvector and we're the only user,
43211 // we may be able to perform this with a smaller vector width.
43212 if (IdxVal == 0 && InVec.hasOneUse()) {
43213 unsigned InOpcode = InVec.getOpcode();
43214 if (VT == MVT::v2f64 && InVec.getValueType() == MVT::v4f64) {
43215 // v2f64 CVTDQ2PD(v4i32).
43216 if (InOpcode == ISD::SINT_TO_FP &&
43217 InVec.getOperand(0).getValueType() == MVT::v4i32) {
43218 return DAG.getNode(X86ISD::CVTSI2P, SDLoc(N), VT, InVec.getOperand(0));
43219 }
43220 // v2f64 CVTUDQ2PD(v4i32).
43221 if (InOpcode == ISD::UINT_TO_FP &&
43222 InVec.getOperand(0).getValueType() == MVT::v4i32) {
43223 return DAG.getNode(X86ISD::CVTUI2P, SDLoc(N), VT, InVec.getOperand(0));
43224 }
43225 // v2f64 CVTPS2PD(v4f32).
43226 if (InOpcode == ISD::FP_EXTEND &&
43227 InVec.getOperand(0).getValueType() == MVT::v4f32) {
43228 return DAG.getNode(X86ISD::VFPEXT, SDLoc(N), VT, InVec.getOperand(0));
43229 }
43230 }
43231 if ((InOpcode == ISD::ANY_EXTEND || InOpcode == ISD::ZERO_EXTEND ||
43232 InOpcode == ISD::SIGN_EXTEND) &&
43233 VT.is128BitVector() &&
43234 InVec.getOperand(0).getSimpleValueType().is128BitVector()) {
43235 unsigned ExtOp = InOpcode == ISD::SIGN_EXTEND
43236 ? ISD::SIGN_EXTEND_VECTOR_INREG
43237 : ISD::ZERO_EXTEND_VECTOR_INREG;
43238 return DAG.getNode(ExtOp, SDLoc(N), VT, InVec.getOperand(0));
43239 }
43240 if ((InOpcode == ISD::ANY_EXTEND_VECTOR_INREG ||
43241 InOpcode == ISD::ZERO_EXTEND_VECTOR_INREG ||
43242 InOpcode == ISD::SIGN_EXTEND_VECTOR_INREG) &&
43243 VT.is128BitVector() &&
43244 InVec.getOperand(0).getSimpleValueType().is128BitVector()) {
43245 return DAG.getNode(InOpcode, SDLoc(N), VT, InVec.getOperand(0));
43246 }
43247 }
43248
43249 return SDValue();
43250}
43251
43252static SDValue combineScalarToVector(SDNode *N, SelectionDAG &DAG) {
43253 EVT VT = N->getValueType(0);
43254 SDValue Src = N->getOperand(0);
43255 SDLoc DL(N);
43256
43257 // If this is a scalar to vector to v1i1 from an AND with 1, bypass the and.
43258 // This occurs frequently in our masked scalar intrinsic code and our
43259 // floating point select lowering with AVX512.
43260 // TODO: SimplifyDemandedBits instead?
43261 if (VT == MVT::v1i1 && Src.getOpcode() == ISD::AND && Src.hasOneUse())
43262 if (auto *C = dyn_cast<ConstantSDNode>(Src.getOperand(1)))
43263 if (C->getAPIntValue().isOneValue())
43264 return DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v1i1,
43265 Src.getOperand(0));
43266
43267 // Combine scalar_to_vector of an extract_vector_elt into an extract_subvec.
43268 if (VT == MVT::v1i1 && Src.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
43269 Src.hasOneUse() && Src.getOperand(0).getValueType().isVector() &&
43270 Src.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
43271 if (auto *C = dyn_cast<ConstantSDNode>(Src.getOperand(1)))
43272 if (C->isNullValue())
43273 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src.getOperand(0),
43274 Src.getOperand(1));
43275
43276 // Reduce v2i64 to v4i32 if we don't need the upper bits.
43277 // TODO: Move to DAGCombine?
43278 if (VT == MVT::v2i64 && Src.getOpcode() == ISD::ANY_EXTEND &&
43279 Src.getValueType() == MVT::i64 && Src.hasOneUse() &&
43280 Src.getOperand(0).getScalarValueSizeInBits() <= 32)
43281 return DAG.getBitcast(
43282 VT, DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v4i32,
43283 DAG.getAnyExtOrTrunc(Src.getOperand(0), DL, MVT::i32)));
43284
43285 return SDValue();
43286}
43287
43288// Simplify PMULDQ and PMULUDQ operations.
43289static SDValue combinePMULDQ(SDNode *N, SelectionDAG &DAG,
43290 TargetLowering::DAGCombinerInfo &DCI) {
43291 SDValue LHS = N->getOperand(0);
43292 SDValue RHS = N->getOperand(1);
43293
43294 // Canonicalize constant to RHS.
43295 if (DAG.isConstantIntBuildVectorOrConstantInt(LHS) &&
43296 !DAG.isConstantIntBuildVectorOrConstantInt(RHS))
43297 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0), RHS, LHS);
43298
43299 // Multiply by zero.
43300 if (ISD::isBuildVectorAllZeros(RHS.getNode()))
43301 return RHS;
43302
43303 // Aggressively peek through ops to get at the demanded low bits.
43304 APInt DemandedMask = APInt::getLowBitsSet(64, 32);
43305 SDValue DemandedLHS = DAG.GetDemandedBits(LHS, DemandedMask);
43306 SDValue DemandedRHS = DAG.GetDemandedBits(RHS, DemandedMask);
43307 if (DemandedLHS || DemandedRHS)
43308 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
43309 DemandedLHS ? DemandedLHS : LHS,
43310 DemandedRHS ? DemandedRHS : RHS);
43311
43312 // PMULDQ/PMULUDQ only uses lower 32 bits from each vector element.
43313 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
43314 if (TLI.SimplifyDemandedBits(SDValue(N, 0), APInt::getAllOnesValue(64), DCI))
43315 return SDValue(N, 0);
43316
43317 return SDValue();
43318}
43319
43320static SDValue combineExtInVec(SDNode *N, SelectionDAG &DAG,
43321 const X86Subtarget &Subtarget) {
43322 // Disabling for widening legalization for now. We can enable if we find a
43323 // case that needs it. Otherwise it can be deleted when we switch to
43324 // widening legalization.
43325 if (ExperimentalVectorWideningLegalization)
43326 return SDValue();
43327
43328 EVT VT = N->getValueType(0);
43329 SDValue In = N->getOperand(0);
43330
43331 // Combine (ext_invec (ext_invec X)) -> (ext_invec X)
43332 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
43333 if (In.getOpcode() == N->getOpcode() &&
43334 TLI.isTypeLegal(VT) && TLI.isTypeLegal(In.getOperand(0).getValueType()))
43335 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, In.getOperand(0));
43336
43337 // Attempt to combine as a shuffle.
43338 // TODO: SSE41 support
43339 if (Subtarget.hasAVX()) {
43340 SDValue Op(N, 0);
43341 if (TLI.isTypeLegal(VT) && TLI.isTypeLegal(In.getValueType()))
43342 if (SDValue Res = combineX86ShufflesRecursively(Op, DAG, Subtarget))
43343 return Res;
43344 }
43345
43346 return SDValue();
43347}
43348
43349SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
43350 DAGCombinerInfo &DCI) const {
43351 SelectionDAG &DAG = DCI.DAG;
43352 switch (N->getOpcode()) {
43353 default: break;
43354 case ISD::SCALAR_TO_VECTOR:
43355 return combineScalarToVector(N, DAG);
43356 case ISD::EXTRACT_VECTOR_ELT:
43357 case X86ISD::PEXTRW:
43358 case X86ISD::PEXTRB:
43359 return combineExtractVectorElt(N, DAG, DCI, Subtarget);
43360 case ISD::CONCAT_VECTORS:
43361 return combineConcatVectors(N, DAG, DCI, Subtarget);
43362 case ISD::INSERT_SUBVECTOR:
43363 return combineInsertSubvector(N, DAG, DCI, Subtarget);
43364 case ISD::EXTRACT_SUBVECTOR:
43365 return combineExtractSubvector(N, DAG, DCI, Subtarget);
43366 case ISD::VSELECT:
43367 case ISD::SELECT:
43368 case X86ISD::BLENDV: return combineSelect(N, DAG, DCI, Subtarget);
43369 case ISD::BITCAST: return combineBitcast(N, DAG, DCI, Subtarget);
43370 case X86ISD::CMOV: return combineCMov(N, DAG, DCI, Subtarget);
43371 case X86ISD::CMP: return combineCMP(N, DAG);
43372 case ISD::ADD: return combineAdd(N, DAG, Subtarget);
43373 case ISD::SUB: return combineSub(N, DAG, Subtarget);
43374 case X86ISD::ADD:
43375 case X86ISD::SUB: return combineX86AddSub(N, DAG, DCI);
43376 case X86ISD::SBB: return combineSBB(N, DAG);
43377 case X86ISD::ADC: return combineADC(N, DAG, DCI);
43378 case ISD::MUL: return combineMul(N, DAG, DCI, Subtarget);
43379 case ISD::SHL: return combineShiftLeft(N, DAG);
43380 case ISD::SRA: return combineShiftRightArithmetic(N, DAG);
43381 case ISD::SRL: return combineShiftRightLogical(N, DAG, DCI);
43382 case ISD::AND: return combineAnd(N, DAG, DCI, Subtarget);
43383 case ISD::OR: return combineOr(N, DAG, DCI, Subtarget);
43384 case ISD::XOR: return combineXor(N, DAG, DCI, Subtarget);
43385 case X86ISD::BEXTR: return combineBEXTR(N, DAG, DCI, Subtarget);
43386 case ISD::LOAD: return combineLoad(N, DAG, DCI, Subtarget);
43387 case ISD::MLOAD: return combineMaskedLoad(N, DAG, DCI, Subtarget);
43388 case ISD::STORE: return combineStore(N, DAG, Subtarget);
43389 case ISD::MSTORE: return combineMaskedStore(N, DAG, DCI, Subtarget);
43390 case ISD::SINT_TO_FP: return combineSIntToFP(N, DAG, Subtarget);
43391 case ISD::UINT_TO_FP: return combineUIntToFP(N, DAG, Subtarget);
43392 case ISD::FADD:
43393 case ISD::FSUB: return combineFaddFsub(N, DAG, Subtarget);
43394 case ISD::FNEG: return combineFneg(N, DAG, Subtarget);
43395 case ISD::TRUNCATE: return combineTruncate(N, DAG, Subtarget);
43396 case X86ISD::ANDNP: return combineAndnp(N, DAG, DCI, Subtarget);
43397 case X86ISD::FAND: return combineFAnd(N, DAG, Subtarget);
43398 case X86ISD::FANDN: return combineFAndn(N, DAG, Subtarget);
43399 case X86ISD::FXOR:
43400 case X86ISD::FOR: return combineFOr(N, DAG, Subtarget);
43401 case X86ISD::FMIN:
43402 case X86ISD::FMAX: return combineFMinFMax(N, DAG);
43403 case ISD::FMINNUM:
43404 case ISD::FMAXNUM: return combineFMinNumFMaxNum(N, DAG, Subtarget);
43405 case X86ISD::CVTSI2P:
43406 case X86ISD::CVTUI2P: return combineX86INT_TO_FP(N, DAG, DCI);
43407 case X86ISD::BT: return combineBT(N, DAG, DCI);
43408 case ISD::ANY_EXTEND:
43409 case ISD::ZERO_EXTEND: return combineZext(N, DAG, DCI, Subtarget);
43410 case ISD::SIGN_EXTEND: return combineSext(N, DAG, DCI, Subtarget);
43411 case ISD::SIGN_EXTEND_INREG: return combineSignExtendInReg(N, DAG, Subtarget);
43412 case ISD::ANY_EXTEND_VECTOR_INREG:
43413 case ISD::ZERO_EXTEND_VECTOR_INREG: return combineExtInVec(N, DAG, Subtarget);
43414 case ISD::SETCC: return combineSetCC(N, DAG, Subtarget);
43415 case X86ISD::SETCC: return combineX86SetCC(N, DAG, Subtarget);
43416 case X86ISD::BRCOND: return combineBrCond(N, DAG, Subtarget);
43417 case X86ISD::PACKSS:
43418 case X86ISD::PACKUS: return combineVectorPack(N, DAG, DCI, Subtarget);
43419 case X86ISD::VSHL:
43420 case X86ISD::VSRA:
43421 case X86ISD::VSRL:
43422 return combineVectorShiftVar(N, DAG, DCI, Subtarget);
43423 case X86ISD::VSHLI:
43424 case X86ISD::VSRAI:
43425 case X86ISD::VSRLI:
43426 return combineVectorShiftImm(N, DAG, DCI, Subtarget);
43427 case X86ISD::PINSRB:
43428 case X86ISD::PINSRW: return combineVectorInsert(N, DAG, DCI, Subtarget);
43429 case X86ISD::SHUFP: // Handle all target specific shuffles
43430 case X86ISD::INSERTPS:
43431 case X86ISD::EXTRQI:
43432 case X86ISD::INSERTQI:
43433 case X86ISD::PALIGNR:
43434 case X86ISD::VSHLDQ:
43435 case X86ISD::VSRLDQ:
43436 case X86ISD::BLENDI:
43437 case X86ISD::UNPCKH:
43438 case X86ISD::UNPCKL:
43439 case X86ISD::MOVHLPS:
43440 case X86ISD::MOVLHPS:
43441 case X86ISD::PSHUFB:
43442 case X86ISD::PSHUFD:
43443 case X86ISD::PSHUFHW:
43444 case X86ISD::PSHUFLW:
43445 case X86ISD::MOVSHDUP:
43446 case X86ISD::MOVSLDUP:
43447 case X86ISD::MOVDDUP:
43448 case X86ISD::MOVSS:
43449 case X86ISD::MOVSD:
43450 case X86ISD::VBROADCAST:
43451 case X86ISD::VPPERM:
43452 case X86ISD::VPERMI:
43453 case X86ISD::VPERMV:
43454 case X86ISD::VPERMV3:
43455 case X86ISD::VPERMIL2:
43456 case X86ISD::VPERMILPI:
43457 case X86ISD::VPERMILPV:
43458 case X86ISD::VPERM2X128:
43459 case X86ISD::SHUF128:
43460 case X86ISD::VZEXT_MOVL:
43461 case ISD::VECTOR_SHUFFLE: return combineShuffle(N, DAG, DCI,Subtarget);
43462 case X86ISD::FMADD_RND:
43463 case X86ISD::FMSUB:
43464 case X86ISD::FMSUB_RND:
43465 case X86ISD::FNMADD:
43466 case X86ISD::FNMADD_RND:
43467 case X86ISD::FNMSUB:
43468 case X86ISD::FNMSUB_RND:
43469 case ISD::FMA: return combineFMA(N, DAG, Subtarget);
43470 case X86ISD::FMADDSUB_RND:
43471 case X86ISD::FMSUBADD_RND:
43472 case X86ISD::FMADDSUB:
43473 case X86ISD::FMSUBADD: return combineFMADDSUB(N, DAG, Subtarget);
43474 case X86ISD::MOVMSK: return combineMOVMSK(N, DAG, DCI);
43475 case X86ISD::MGATHER:
43476 case X86ISD::MSCATTER:
43477 case ISD::MGATHER:
43478 case ISD::MSCATTER: return combineGatherScatter(N, DAG, DCI, Subtarget);
43479 case X86ISD::PCMPEQ:
43480 case X86ISD::PCMPGT: return combineVectorCompare(N, DAG, Subtarget);
43481 case X86ISD::PMULDQ:
43482 case X86ISD::PMULUDQ: return combinePMULDQ(N, DAG, DCI);
43483 }
43484
43485 return SDValue();
43486}
43487
43488bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
43489 if (!isTypeLegal(VT))
43490 return false;
43491
43492 // There are no vXi8 shifts.
43493 if (Opc == ISD::SHL && VT.isVector() && VT.getVectorElementType() == MVT::i8)
43494 return false;
43495
43496 // TODO: Almost no 8-bit ops are desirable because they have no actual
43497 // size/speed advantages vs. 32-bit ops, but they do have a major
43498 // potential disadvantage by causing partial register stalls.
43499 //
43500 // 8-bit multiply/shl is probably not cheaper than 32-bit multiply/shl, and
43501 // we have specializations to turn 32-bit multiply/shl into LEA or other ops.
43502 // Also, see the comment in "IsDesirableToPromoteOp" - where we additionally
43503 // check for a constant operand to the multiply.
43504 if ((Opc == ISD::MUL || Opc == ISD::SHL) && VT == MVT::i8)
43505 return false;
43506
43507 // i16 instruction encodings are longer and some i16 instructions are slow,
43508 // so those are not desirable.
43509 if (VT == MVT::i16) {
43510 switch (Opc) {
43511 default:
43512 break;
43513 case ISD::LOAD:
43514 case ISD::SIGN_EXTEND:
43515 case ISD::ZERO_EXTEND:
43516 case ISD::ANY_EXTEND:
43517 case ISD::SHL:
43518 case ISD::SRA:
43519 case ISD::SRL:
43520 case ISD::SUB:
43521 case ISD::ADD:
43522 case ISD::MUL:
43523 case ISD::AND:
43524 case ISD::OR:
43525 case ISD::XOR:
43526 return false;
43527 }
43528 }
43529
43530 // Any legal type not explicitly accounted for above here is desirable.
43531 return true;
43532}
43533
43534SDValue X86TargetLowering::expandIndirectJTBranch(const SDLoc& dl,
43535 SDValue Value, SDValue Addr,
43536 SelectionDAG &DAG) const {
43537 const Module *M = DAG.getMachineFunction().getMMI().getModule();
43538 Metadata *IsCFProtectionSupported = M->getModuleFlag("cf-protection-branch");
43539 if (IsCFProtectionSupported) {
43540 // In case control-flow branch protection is enabled, we need to add
43541 // notrack prefix to the indirect branch.
43542 // In order to do that we create NT_BRIND SDNode.
43543 // Upon ISEL, the pattern will convert it to jmp with NoTrack prefix.
43544 return DAG.getNode(X86ISD::NT_BRIND, dl, MVT::Other, Value, Addr);
43545 }
43546
43547 return TargetLowering::expandIndirectJTBranch(dl, Value, Addr, DAG);
43548}
43549
43550bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
43551 EVT VT = Op.getValueType();
43552 bool Is8BitMulByConstant = VT == MVT::i8 && Op.getOpcode() == ISD::MUL &&
43553 isa<ConstantSDNode>(Op.getOperand(1));
43554
43555 // i16 is legal, but undesirable since i16 instruction encodings are longer
43556 // and some i16 instructions are slow.
43557 // 8-bit multiply-by-constant can usually be expanded to something cheaper
43558 // using LEA and/or other ALU ops.
43559 if (VT != MVT::i16 && !Is8BitMulByConstant)
43560 return false;
43561
43562 auto IsFoldableRMW = [](SDValue Load, SDValue Op) {
43563 if (!Op.hasOneUse())
43564 return false;
43565 SDNode *User = *Op->use_begin();
43566 if (!ISD::isNormalStore(User))
43567 return false;
43568 auto *Ld = cast<LoadSDNode>(Load);
43569 auto *St = cast<StoreSDNode>(User);
43570 return Ld->getBasePtr() == St->getBasePtr();
43571 };
43572
43573 auto IsFoldableAtomicRMW = [](SDValue Load, SDValue Op) {
43574 if (!Load.hasOneUse() || Load.getOpcode() != ISD::ATOMIC_LOAD)
43575 return false;
43576 if (!Op.hasOneUse())
43577 return false;
43578 SDNode *User = *Op->use_begin();
43579 if (User->getOpcode() != ISD::ATOMIC_STORE)
43580 return false;
43581 auto *Ld = cast<AtomicSDNode>(Load);
43582 auto *St = cast<AtomicSDNode>(User);
43583 return Ld->getBasePtr() == St->getBasePtr();
43584 };
43585
43586 bool Commute = false;
43587 switch (Op.getOpcode()) {
43588 default: return false;
43589 case ISD::SIGN_EXTEND:
43590 case ISD::ZERO_EXTEND:
43591 case ISD::ANY_EXTEND:
43592 break;
43593 case ISD::SHL:
43594 case ISD::SRA:
43595 case ISD::SRL: {
43596 SDValue N0 = Op.getOperand(0);
43597 // Look out for (store (shl (load), x)).
43598 if (MayFoldLoad(N0) && IsFoldableRMW(N0, Op))
43599 return false;
43600 break;
43601 }
43602 case ISD::ADD:
43603 case ISD::MUL:
43604 case ISD::AND:
43605 case ISD::OR:
43606 case ISD::XOR:
43607 Commute = true;
43608 LLVM_FALLTHROUGH[[clang::fallthrough]];
43609 case ISD::SUB: {
43610 SDValue N0 = Op.getOperand(0);
43611 SDValue N1 = Op.getOperand(1);
43612 // Avoid disabling potential load folding opportunities.
43613 if (MayFoldLoad(N1) &&
43614 (!Commute || !isa<ConstantSDNode>(N0) ||
43615 (Op.getOpcode() != ISD::MUL && IsFoldableRMW(N1, Op))))
43616 return false;
43617 if (MayFoldLoad(N0) &&
43618 ((Commute && !isa<ConstantSDNode>(N1)) ||
43619 (Op.getOpcode() != ISD::MUL && IsFoldableRMW(N0, Op))))
43620 return false;
43621 if (IsFoldableAtomicRMW(N0, Op) ||
43622 (Commute && IsFoldableAtomicRMW(N1, Op)))
43623 return false;
43624 }
43625 }
43626
43627 PVT = MVT::i32;
43628 return true;
43629}
43630
43631bool X86TargetLowering::
43632 isDesirableToCombineBuildVectorToShuffleTruncate(
43633 ArrayRef<int> ShuffleMask, EVT SrcVT, EVT TruncVT) const {
43634
43635 assert(SrcVT.getVectorNumElements() == ShuffleMask.size() &&((SrcVT.getVectorNumElements() == ShuffleMask.size() &&
"Element count mismatch") ? static_cast<void> (0) : __assert_fail
("SrcVT.getVectorNumElements() == ShuffleMask.size() && \"Element count mismatch\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 43636, __PRETTY_FUNCTION__))
43636 "Element count mismatch")((SrcVT.getVectorNumElements() == ShuffleMask.size() &&
"Element count mismatch") ? static_cast<void> (0) : __assert_fail
("SrcVT.getVectorNumElements() == ShuffleMask.size() && \"Element count mismatch\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 43636, __PRETTY_FUNCTION__))
;
43637 assert(((Subtarget.getTargetLowering()->isShuffleMaskLegal(ShuffleMask
, SrcVT) && "Shuffle Mask expected to be legal") ? static_cast
<void> (0) : __assert_fail ("Subtarget.getTargetLowering()->isShuffleMaskLegal(ShuffleMask, SrcVT) && \"Shuffle Mask expected to be legal\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 43639, __PRETTY_FUNCTION__))
43638 Subtarget.getTargetLowering()->isShuffleMaskLegal(ShuffleMask, SrcVT) &&((Subtarget.getTargetLowering()->isShuffleMaskLegal(ShuffleMask
, SrcVT) && "Shuffle Mask expected to be legal") ? static_cast
<void> (0) : __assert_fail ("Subtarget.getTargetLowering()->isShuffleMaskLegal(ShuffleMask, SrcVT) && \"Shuffle Mask expected to be legal\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 43639, __PRETTY_FUNCTION__))
43639 "Shuffle Mask expected to be legal")((Subtarget.getTargetLowering()->isShuffleMaskLegal(ShuffleMask
, SrcVT) && "Shuffle Mask expected to be legal") ? static_cast
<void> (0) : __assert_fail ("Subtarget.getTargetLowering()->isShuffleMaskLegal(ShuffleMask, SrcVT) && \"Shuffle Mask expected to be legal\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 43639, __PRETTY_FUNCTION__))
;
43640
43641 // For 32-bit elements VPERMD is better than shuffle+truncate.
43642 // TODO: After we improve lowerBuildVector, add execption for VPERMW.
43643 if (SrcVT.getScalarSizeInBits() == 32 || !Subtarget.hasAVX2())
43644 return false;
43645
43646 if (is128BitLaneCrossingShuffleMask(SrcVT.getSimpleVT(), ShuffleMask))
43647 return false;
43648
43649 return true;
43650}
43651
43652//===----------------------------------------------------------------------===//
43653// X86 Inline Assembly Support
43654//===----------------------------------------------------------------------===//
43655
43656// Helper to match a string separated by whitespace.
43657static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
43658 S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
43659
43660 for (StringRef Piece : Pieces) {
43661 if (!S.startswith(Piece)) // Check if the piece matches.
43662 return false;
43663
43664 S = S.substr(Piece.size());
43665 StringRef::size_type Pos = S.find_first_not_of(" \t");
43666 if (Pos == 0) // We matched a prefix.
43667 return false;
43668
43669 S = S.substr(Pos);
43670 }
43671
43672 return S.empty();
43673}
43674
43675static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
43676
43677 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
43678 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
43679 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
43680 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
43681
43682 if (AsmPieces.size() == 3)
43683 return true;
43684 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
43685 return true;
43686 }
43687 }
43688 return false;
43689}
43690
43691bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
43692 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
43693
43694 const std::string &AsmStr = IA->getAsmString();
43695
43696 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
43697 if (!Ty || Ty->getBitWidth() % 16 != 0)
43698 return false;
43699
43700 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
43701 SmallVector<StringRef, 4> AsmPieces;
43702 SplitString(AsmStr, AsmPieces, ";\n");
43703
43704 switch (AsmPieces.size()) {
43705 default: return false;
43706 case 1:
43707 // FIXME: this should verify that we are targeting a 486 or better. If not,
43708 // we will turn this bswap into something that will be lowered to logical
43709 // ops instead of emitting the bswap asm. For now, we don't support 486 or
43710 // lower so don't worry about this.
43711 // bswap $0
43712 if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
43713 matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
43714 matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
43715 matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
43716 matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
43717 matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
43718 // No need to check constraints, nothing other than the equivalent of
43719 // "=r,0" would be valid here.
43720 return IntrinsicLowering::LowerToByteSwap(CI);
43721 }
43722
43723 // rorw $$8, ${0:w} --> llvm.bswap.i16
43724 if (CI->getType()->isIntegerTy(16) &&
43725 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
43726 (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
43727 matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
43728 AsmPieces.clear();
43729 StringRef ConstraintsStr = IA->getConstraintString();
43730 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
43731 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
43732 if (clobbersFlagRegisters(AsmPieces))
43733 return IntrinsicLowering::LowerToByteSwap(CI);
43734 }
43735 break;
43736 case 3:
43737 if (CI->getType()->isIntegerTy(32) &&
43738 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
43739 matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
43740 matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
43741 matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
43742 AsmPieces.clear();
43743 StringRef ConstraintsStr = IA->getConstraintString();
43744 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
43745 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
43746 if (clobbersFlagRegisters(AsmPieces))
43747 return IntrinsicLowering::LowerToByteSwap(CI);
43748 }
43749
43750 if (CI->getType()->isIntegerTy(64)) {
43751 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
43752 if (Constraints.size() >= 2 &&
43753 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
43754 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
43755 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
43756 if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
43757 matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
43758 matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
43759 return IntrinsicLowering::LowerToByteSwap(CI);
43760 }
43761 }
43762 break;
43763 }
43764 return false;
43765}
43766
43767static X86::CondCode parseConstraintCode(llvm::StringRef Constraint) {
43768 X86::CondCode Cond = StringSwitch<X86::CondCode>(Constraint)
43769 .Case("{@cca}", X86::COND_A)
43770 .Case("{@ccae}", X86::COND_AE)
43771 .Case("{@ccb}", X86::COND_B)
43772 .Case("{@ccbe}", X86::COND_BE)
43773 .Case("{@ccc}", X86::COND_B)
43774 .Case("{@cce}", X86::COND_E)
43775 .Case("{@ccz}", X86::COND_E)
43776 .Case("{@ccg}", X86::COND_G)
43777 .Case("{@ccge}", X86::COND_GE)
43778 .Case("{@ccl}", X86::COND_L)
43779 .Case("{@ccle}", X86::COND_LE)
43780 .Case("{@ccna}", X86::COND_BE)
43781 .Case("{@ccnae}", X86::COND_B)
43782 .Case("{@ccnb}", X86::COND_AE)
43783 .Case("{@ccnbe}", X86::COND_A)
43784 .Case("{@ccnc}", X86::COND_AE)
43785 .Case("{@ccne}", X86::COND_NE)
43786 .Case("{@ccnz}", X86::COND_NE)
43787 .Case("{@ccng}", X86::COND_LE)
43788 .Case("{@ccnge}", X86::COND_L)
43789 .Case("{@ccnl}", X86::COND_GE)
43790 .Case("{@ccnle}", X86::COND_G)
43791 .Case("{@ccno}", X86::COND_NO)
43792 .Case("{@ccnp}", X86::COND_P)
43793 .Case("{@ccns}", X86::COND_NS)
43794 .Case("{@cco}", X86::COND_O)
43795 .Case("{@ccp}", X86::COND_P)
43796 .Case("{@ccs}", X86::COND_S)
43797 .Default(X86::COND_INVALID);
43798 return Cond;
43799}
43800
43801/// Given a constraint letter, return the type of constraint for this target.
43802X86TargetLowering::ConstraintType
43803X86TargetLowering::getConstraintType(StringRef Constraint) const {
43804 if (Constraint.size() == 1) {
43805 switch (Constraint[0]) {
43806 case 'R':
43807 case 'q':
43808 case 'Q':
43809 case 'f':
43810 case 't':
43811 case 'u':
43812 case 'y':
43813 case 'x':
43814 case 'v':
43815 case 'Y':
43816 case 'l':
43817 case 'k': // AVX512 masking registers.
43818 return C_RegisterClass;
43819 case 'a':
43820 case 'b':
43821 case 'c':
43822 case 'd':
43823 case 'S':
43824 case 'D':
43825 case 'A':
43826 return C_Register;
43827 case 'I':
43828 case 'J':
43829 case 'K':
43830 case 'L':
43831 case 'M':
43832 case 'N':
43833 case 'G':
43834 case 'C':
43835 case 'e':
43836 case 'Z':
43837 return C_Other;
43838 default:
43839 break;
43840 }
43841 }
43842 else if (Constraint.size() == 2) {
43843 switch (Constraint[0]) {
43844 default:
43845 break;
43846 case 'Y':
43847 switch (Constraint[1]) {
43848 default:
43849 break;
43850 case 'z':
43851 case '0':
43852 return C_Register;
43853 case 'i':
43854 case 'm':
43855 case 'k':
43856 case 't':
43857 case '2':
43858 return C_RegisterClass;
43859 }
43860 }
43861 } else if (parseConstraintCode(Constraint) != X86::COND_INVALID)
43862 return C_Other;
43863 return TargetLowering::getConstraintType(Constraint);
43864}
43865
43866/// Examine constraint type and operand type and determine a weight value.
43867/// This object must already have been set up with the operand type
43868/// and the current alternative constraint selected.
43869TargetLowering::ConstraintWeight
43870 X86TargetLowering::getSingleConstraintMatchWeight(
43871 AsmOperandInfo &info, const char *constraint) const {
43872 ConstraintWeight weight = CW_Invalid;
43873 Value *CallOperandVal = info.CallOperandVal;
43874 // If we don't have a value, we can't do a match,
43875 // but allow it at the lowest weight.
43876 if (!CallOperandVal)
43877 return CW_Default;
43878 Type *type = CallOperandVal->getType();
43879 // Look at the constraint type.
43880 switch (*constraint) {
43881 default:
43882 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
43883 LLVM_FALLTHROUGH[[clang::fallthrough]];
43884 case 'R':
43885 case 'q':
43886 case 'Q':
43887 case 'a':
43888 case 'b':
43889 case 'c':
43890 case 'd':
43891 case 'S':
43892 case 'D':
43893 case 'A':
43894 if (CallOperandVal->getType()->isIntegerTy())
43895 weight = CW_SpecificReg;
43896 break;
43897 case 'f':
43898 case 't':
43899 case 'u':
43900 if (type->isFloatingPointTy())
43901 weight = CW_SpecificReg;
43902 break;
43903 case 'y':
43904 if (type->isX86_MMXTy() && Subtarget.hasMMX())
43905 weight = CW_SpecificReg;
43906 break;
43907 case 'Y': {
43908 unsigned Size = StringRef(constraint).size();
43909 // Pick 'i' as the next char as 'Yi' and 'Y' are synonymous, when matching 'Y'
43910 char NextChar = Size == 2 ? constraint[1] : 'i';
43911 if (Size > 2)
43912 break;
43913 switch (NextChar) {
43914 default:
43915 return CW_Invalid;
43916 // XMM0
43917 case 'z':
43918 case '0':
43919 if ((type->getPrimitiveSizeInBits() == 128) && Subtarget.hasSSE1())
43920 return CW_SpecificReg;
43921 return CW_Invalid;
43922 // Conditional OpMask regs (AVX512)
43923 case 'k':
43924 if ((type->getPrimitiveSizeInBits() == 64) && Subtarget.hasAVX512())
43925 return CW_Register;
43926 return CW_Invalid;
43927 // Any MMX reg
43928 case 'm':
43929 if (type->isX86_MMXTy() && Subtarget.hasMMX())
43930 return weight;
43931 return CW_Invalid;
43932 // Any SSE reg when ISA >= SSE2, same as 'Y'
43933 case 'i':
43934 case 't':
43935 case '2':
43936 if (!Subtarget.hasSSE2())
43937 return CW_Invalid;
43938 break;
43939 }
43940 // Fall through (handle "Y" constraint).
43941 LLVM_FALLTHROUGH[[clang::fallthrough]];
43942 }
43943 case 'v':
43944 if ((type->getPrimitiveSizeInBits() == 512) && Subtarget.hasAVX512())
43945 weight = CW_Register;
43946 LLVM_FALLTHROUGH[[clang::fallthrough]];
43947 case 'x':
43948 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget.hasSSE1()) ||
43949 ((type->getPrimitiveSizeInBits() == 256) && Subtarget.hasAVX()))
43950 weight = CW_Register;
43951 break;
43952 case 'k':
43953 // Enable conditional vector operations using %k<#> registers.
43954 if ((type->getPrimitiveSizeInBits() == 64) && Subtarget.hasAVX512())
43955 weight = CW_Register;
43956 break;
43957 case 'I':
43958 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
43959 if (C->getZExtValue() <= 31)
43960 weight = CW_Constant;
43961 }
43962 break;
43963 case 'J':
43964 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
43965 if (C->getZExtValue() <= 63)
43966 weight = CW_Constant;
43967 }
43968 break;
43969 case 'K':
43970 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
43971 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
43972 weight = CW_Constant;
43973 }
43974 break;
43975 case 'L':
43976 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
43977 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
43978 weight = CW_Constant;
43979 }
43980 break;
43981 case 'M':
43982 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
43983 if (C->getZExtValue() <= 3)
43984 weight = CW_Constant;
43985 }
43986 break;
43987 case 'N':
43988 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
43989 if (C->getZExtValue() <= 0xff)
43990 weight = CW_Constant;
43991 }
43992 break;
43993 case 'G':
43994 case 'C':
43995 if (isa<ConstantFP>(CallOperandVal)) {
43996 weight = CW_Constant;
43997 }
43998 break;
43999 case 'e':
44000 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
44001 if ((C->getSExtValue() >= -0x80000000LL) &&
44002 (C->getSExtValue() <= 0x7fffffffLL))
44003 weight = CW_Constant;
44004 }
44005 break;
44006 case 'Z':
44007 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
44008 if (C->getZExtValue() <= 0xffffffff)
44009 weight = CW_Constant;
44010 }
44011 break;
44012 }
44013 return weight;
44014}
44015
44016/// Try to replace an X constraint, which matches anything, with another that
44017/// has more specific requirements based on the type of the corresponding
44018/// operand.
44019const char *X86TargetLowering::
44020LowerXConstraint(EVT ConstraintVT) const {
44021 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
44022 // 'f' like normal targets.
44023 if (ConstraintVT.isFloatingPoint()) {
44024 if (Subtarget.hasSSE2())
44025 return "Y";
44026 if (Subtarget.hasSSE1())
44027 return "x";
44028 }
44029
44030 return TargetLowering::LowerXConstraint(ConstraintVT);
44031}
44032
44033// Lower @cc targets via setcc.
44034SDValue X86TargetLowering::LowerAsmOutputForConstraint(
44035 SDValue &Chain, SDValue &Flag, SDLoc DL, const AsmOperandInfo &OpInfo,
44036 SelectionDAG &DAG) const {
44037 X86::CondCode Cond = parseConstraintCode(OpInfo.ConstraintCode);
44038 if (Cond == X86::COND_INVALID)
44039 return SDValue();
44040 // Check that return type is valid.
44041 if (OpInfo.ConstraintVT.isVector() || !OpInfo.ConstraintVT.isInteger() ||
44042 OpInfo.ConstraintVT.getSizeInBits() < 8)
44043 report_fatal_error("Flag output operand is of invalid type");
44044
44045 // Get EFLAGS register. Only update chain when copyfrom is glued.
44046 if (Flag.getNode()) {
44047 Flag = DAG.getCopyFromReg(Chain, DL, X86::EFLAGS, MVT::i32, Flag);
44048 Chain = Flag.getValue(1);
44049 } else
44050 Flag = DAG.getCopyFromReg(Chain, DL, X86::EFLAGS, MVT::i32);
44051 // Extract CC code.
44052 SDValue CC = getSETCC(Cond, Flag, DL, DAG);
44053 // Extend to 32-bits
44054 SDValue Result = DAG.getNode(ISD::ZERO_EXTEND, DL, OpInfo.ConstraintVT, CC);
44055
44056 return Result;
44057}
44058
44059/// Lower the specified operand into the Ops vector.
44060/// If it is invalid, don't add anything to Ops.
44061void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
44062 std::string &Constraint,
44063 std::vector<SDValue>&Ops,
44064 SelectionDAG &DAG) const {
44065 SDValue Result;
44066
44067 // Only support length 1 constraints for now.
44068 if (Constraint.length() > 1) return;
44069
44070 char ConstraintLetter = Constraint[0];
44071 switch (ConstraintLetter) {
44072 default: break;
44073 case 'I':
44074 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
44075 if (C->getZExtValue() <= 31) {
44076 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
44077 Op.getValueType());
44078 break;
44079 }
44080 }
44081 return;
44082 case 'J':
44083 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
44084 if (C->getZExtValue() <= 63) {
44085 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
44086 Op.getValueType());
44087 break;
44088 }
44089 }
44090 return;
44091 case 'K':
44092 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
44093 if (isInt<8>(C->getSExtValue())) {
44094 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
44095 Op.getValueType());
44096 break;
44097 }
44098 }
44099 return;
44100 case 'L':
44101 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
44102 if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
44103 (Subtarget.is64Bit() && C->getZExtValue() == 0xffffffff)) {
44104 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
44105 Op.getValueType());
44106 break;
44107 }
44108 }
44109 return;
44110 case 'M':
44111 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
44112 if (C->getZExtValue() <= 3) {
44113 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
44114 Op.getValueType());
44115 break;
44116 }
44117 }
44118 return;
44119 case 'N':
44120 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
44121 if (C->getZExtValue() <= 255) {
44122 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
44123 Op.getValueType());
44124 break;
44125 }
44126 }
44127 return;
44128 case 'O':
44129 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
44130 if (C->getZExtValue() <= 127) {
44131 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
44132 Op.getValueType());
44133 break;
44134 }
44135 }
44136 return;
44137 case 'e': {
44138 // 32-bit signed value
44139 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
44140 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
44141 C->getSExtValue())) {
44142 // Widen to 64 bits here to get it sign extended.
44143 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
44144 break;
44145 }
44146 // FIXME gcc accepts some relocatable values here too, but only in certain
44147 // memory models; it's complicated.
44148 }
44149 return;
44150 }
44151 case 'Z': {
44152 // 32-bit unsigned value
44153 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
44154 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
44155 C->getZExtValue())) {
44156 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
44157 Op.getValueType());
44158 break;
44159 }
44160 }
44161 // FIXME gcc accepts some relocatable values here too, but only in certain
44162 // memory models; it's complicated.
44163 return;
44164 }
44165 case 'i': {
44166 // Literal immediates are always ok.
44167 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
44168 bool IsBool = CST->getConstantIntValue()->getBitWidth() == 1;
44169 BooleanContent BCont = getBooleanContents(MVT::i64);
44170 ISD::NodeType ExtOpc = IsBool ? getExtendForContent(BCont)
44171 : ISD::SIGN_EXTEND;
44172 int64_t ExtVal = ExtOpc == ISD::ZERO_EXTEND ? CST->getZExtValue()
44173 : CST->getSExtValue();
44174 Result = DAG.getTargetConstant(ExtVal, SDLoc(Op), MVT::i64);
44175 break;
44176 }
44177
44178 // In any sort of PIC mode addresses need to be computed at runtime by
44179 // adding in a register or some sort of table lookup. These can't
44180 // be used as immediates.
44181 if (Subtarget.isPICStyleGOT() || Subtarget.isPICStyleStubPIC())
44182 return;
44183
44184 // If we are in non-pic codegen mode, we allow the address of a global (with
44185 // an optional displacement) to be used with 'i'.
44186 if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op))
44187 // If we require an extra load to get this address, as in PIC mode, we
44188 // can't accept it.
44189 if (isGlobalStubReference(
44190 Subtarget.classifyGlobalReference(GA->getGlobal())))
44191 return;
44192 break;
44193 }
44194 }
44195
44196 if (Result.getNode()) {
44197 Ops.push_back(Result);
44198 return;
44199 }
44200 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
44201}
44202
44203/// Check if \p RC is a general purpose register class.
44204/// I.e., GR* or one of their variant.
44205static bool isGRClass(const TargetRegisterClass &RC) {
44206 return RC.hasSuperClassEq(&X86::GR8RegClass) ||
44207 RC.hasSuperClassEq(&X86::GR16RegClass) ||
44208 RC.hasSuperClassEq(&X86::GR32RegClass) ||
44209 RC.hasSuperClassEq(&X86::GR64RegClass) ||
44210 RC.hasSuperClassEq(&X86::LOW32_ADDR_ACCESS_RBPRegClass);
44211}
44212
44213/// Check if \p RC is a vector register class.
44214/// I.e., FR* / VR* or one of their variant.
44215static bool isFRClass(const TargetRegisterClass &RC) {
44216 return RC.hasSuperClassEq(&X86::FR32XRegClass) ||
44217 RC.hasSuperClassEq(&X86::FR64XRegClass) ||
44218 RC.hasSuperClassEq(&X86::VR128XRegClass) ||
44219 RC.hasSuperClassEq(&X86::VR256XRegClass) ||
44220 RC.hasSuperClassEq(&X86::VR512RegClass);
44221}
44222
44223/// Check if \p RC is a mask register class.
44224/// I.e., VK* or one of their variant.
44225static bool isVKClass(const TargetRegisterClass &RC) {
44226 return RC.hasSuperClassEq(&X86::VK1RegClass) ||
44227 RC.hasSuperClassEq(&X86::VK2RegClass) ||
44228 RC.hasSuperClassEq(&X86::VK4RegClass) ||
44229 RC.hasSuperClassEq(&X86::VK8RegClass) ||
44230 RC.hasSuperClassEq(&X86::VK16RegClass) ||
44231 RC.hasSuperClassEq(&X86::VK32RegClass) ||
44232 RC.hasSuperClassEq(&X86::VK64RegClass);
44233}
44234
44235std::pair<unsigned, const TargetRegisterClass *>
44236X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
44237 StringRef Constraint,
44238 MVT VT) const {
44239 // First, see if this is a constraint that directly corresponds to an LLVM
44240 // register class.
44241 if (Constraint.size() == 1) {
44242 // GCC Constraint Letters
44243 switch (Constraint[0]) {
44244 default: break;
44245 // 'A' means [ER]AX + [ER]DX.
44246 case 'A':
44247 if (Subtarget.is64Bit())
44248 return std::make_pair(X86::RAX, &X86::GR64_ADRegClass);
44249 assert((Subtarget.is32Bit() || Subtarget.is16Bit()) &&(((Subtarget.is32Bit() || Subtarget.is16Bit()) && "Expecting 64, 32 or 16 bit subtarget"
) ? static_cast<void> (0) : __assert_fail ("(Subtarget.is32Bit() || Subtarget.is16Bit()) && \"Expecting 64, 32 or 16 bit subtarget\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 44250, __PRETTY_FUNCTION__))
44250 "Expecting 64, 32 or 16 bit subtarget")(((Subtarget.is32Bit() || Subtarget.is16Bit()) && "Expecting 64, 32 or 16 bit subtarget"
) ? static_cast<void> (0) : __assert_fail ("(Subtarget.is32Bit() || Subtarget.is16Bit()) && \"Expecting 64, 32 or 16 bit subtarget\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 44250, __PRETTY_FUNCTION__))
;
44251 return std::make_pair(X86::EAX, &X86::GR32_ADRegClass);
44252
44253 // TODO: Slight differences here in allocation order and leaving
44254 // RIP in the class. Do they matter any more here than they do
44255 // in the normal allocation?
44256 case 'k':
44257 if (Subtarget.hasAVX512()) {
44258 if (VT == MVT::i1)
44259 return std::make_pair(0U, &X86::VK1RegClass);
44260 if (VT == MVT::i8)
44261 return std::make_pair(0U, &X86::VK8RegClass);
44262 if (VT == MVT::i16)
44263 return std::make_pair(0U, &X86::VK16RegClass);
44264 }
44265 if (Subtarget.hasBWI()) {
44266 if (VT == MVT::i32)
44267 return std::make_pair(0U, &X86::VK32RegClass);
44268 if (VT == MVT::i64)
44269 return std::make_pair(0U, &X86::VK64RegClass);
44270 }
44271 break;
44272 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
44273 if (Subtarget.is64Bit()) {
44274 if (VT == MVT::i32 || VT == MVT::f32)
44275 return std::make_pair(0U, &X86::GR32RegClass);
44276 if (VT == MVT::i16)
44277 return std::make_pair(0U, &X86::GR16RegClass);
44278 if (VT == MVT::i8 || VT == MVT::i1)
44279 return std::make_pair(0U, &X86::GR8RegClass);
44280 if (VT == MVT::i64 || VT == MVT::f64)
44281 return std::make_pair(0U, &X86::GR64RegClass);
44282 break;
44283 }
44284 LLVM_FALLTHROUGH[[clang::fallthrough]];
44285 // 32-bit fallthrough
44286 case 'Q': // Q_REGS
44287 if (VT == MVT::i32 || VT == MVT::f32)
44288 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
44289 if (VT == MVT::i16)
44290 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
44291 if (VT == MVT::i8 || VT == MVT::i1)
44292 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
44293 if (VT == MVT::i64)
44294 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
44295 break;
44296 case 'r': // GENERAL_REGS
44297 case 'l': // INDEX_REGS
44298 if (VT == MVT::i8 || VT == MVT::i1)
44299 return std::make_pair(0U, &X86::GR8RegClass);
44300 if (VT == MVT::i16)
44301 return std::make_pair(0U, &X86::GR16RegClass);
44302 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget.is64Bit())
44303 return std::make_pair(0U, &X86::GR32RegClass);
44304 return std::make_pair(0U, &X86::GR64RegClass);
44305 case 'R': // LEGACY_REGS
44306 if (VT == MVT::i8 || VT == MVT::i1)
44307 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
44308 if (VT == MVT::i16)
44309 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
44310 if (VT == MVT::i32 || !Subtarget.is64Bit())
44311 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
44312 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
44313 case 'f': // FP Stack registers.
44314 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
44315 // value to the correct fpstack register class.
44316 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
44317 return std::make_pair(0U, &X86::RFP32RegClass);
44318 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
44319 return std::make_pair(0U, &X86::RFP64RegClass);
44320 return std::make_pair(0U, &X86::RFP80RegClass);
44321 case 'y': // MMX_REGS if MMX allowed.
44322 if (!Subtarget.hasMMX()) break;
44323 return std::make_pair(0U, &X86::VR64RegClass);
44324 case 'Y': // SSE_REGS if SSE2 allowed
44325 if (!Subtarget.hasSSE2()) break;
44326 LLVM_FALLTHROUGH[[clang::fallthrough]];
44327 case 'v':
44328 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
44329 if (!Subtarget.hasSSE1()) break;
44330 bool VConstraint = (Constraint[0] == 'v');
44331
44332 switch (VT.SimpleTy) {
44333 default: break;
44334 // Scalar SSE types.
44335 case MVT::f32:
44336 case MVT::i32:
44337 if (VConstraint && Subtarget.hasVLX())
44338 return std::make_pair(0U, &X86::FR32XRegClass);
44339 return std::make_pair(0U, &X86::FR32RegClass);
44340 case MVT::f64:
44341 case MVT::i64:
44342 if (VConstraint && Subtarget.hasVLX())
44343 return std::make_pair(0U, &X86::FR64XRegClass);
44344 return std::make_pair(0U, &X86::FR64RegClass);
44345 // TODO: Handle f128 and i128 in FR128RegClass after it is tested well.
44346 // Vector types.
44347 case MVT::v16i8:
44348 case MVT::v8i16:
44349 case MVT::v4i32:
44350 case MVT::v2i64:
44351 case MVT::v4f32:
44352 case MVT::v2f64:
44353 if (VConstraint && Subtarget.hasVLX())
44354 return std::make_pair(0U, &X86::VR128XRegClass);
44355 return std::make_pair(0U, &X86::VR128RegClass);
44356 // AVX types.
44357 case MVT::v32i8:
44358 case MVT::v16i16:
44359 case MVT::v8i32:
44360 case MVT::v4i64:
44361 case MVT::v8f32:
44362 case MVT::v4f64:
44363 if (VConstraint && Subtarget.hasVLX())
44364 return std::make_pair(0U, &X86::VR256XRegClass);
44365 if (Subtarget.hasAVX())
44366 return std::make_pair(0U, &X86::VR256RegClass);
44367 break;
44368 case MVT::v8f64:
44369 case MVT::v16f32:
44370 case MVT::v16i32:
44371 case MVT::v8i64:
44372 if (!Subtarget.hasAVX512()) break;
44373 if (VConstraint)
44374 return std::make_pair(0U, &X86::VR512RegClass);
44375 return std::make_pair(0U, &X86::VR512_0_15RegClass);
44376 }
44377 break;
44378 }
44379 } else if (Constraint.size() == 2 && Constraint[0] == 'Y') {
44380 switch (Constraint[1]) {
44381 default:
44382 break;
44383 case 'i':
44384 case 't':
44385 case '2':
44386 return getRegForInlineAsmConstraint(TRI, "Y", VT);
44387 case 'm':
44388 if (!Subtarget.hasMMX()) break;
44389 return std::make_pair(0U, &X86::VR64RegClass);
44390 case 'z':
44391 case '0':
44392 if (!Subtarget.hasSSE1()) break;
44393 return std::make_pair(X86::XMM0, &X86::VR128RegClass);
44394 case 'k':
44395 // This register class doesn't allocate k0 for masked vector operation.
44396 if (Subtarget.hasAVX512()) {
44397 if (VT == MVT::i1)
44398 return std::make_pair(0U, &X86::VK1WMRegClass);
44399 if (VT == MVT::i8)
44400 return std::make_pair(0U, &X86::VK8WMRegClass);
44401 if (VT == MVT::i16)
44402 return std::make_pair(0U, &X86::VK16WMRegClass);
44403 }
44404 if (Subtarget.hasBWI()) {
44405 if (VT == MVT::i32)
44406 return std::make_pair(0U, &X86::VK32WMRegClass);
44407 if (VT == MVT::i64)
44408 return std::make_pair(0U, &X86::VK64WMRegClass);
44409 }
44410 break;
44411 }
44412 }
44413
44414 if (parseConstraintCode(Constraint) != X86::COND_INVALID)
44415 return std::make_pair(0U, &X86::GR32RegClass);
44416
44417 // Use the default implementation in TargetLowering to convert the register
44418 // constraint into a member of a register class.
44419 std::pair<unsigned, const TargetRegisterClass*> Res;
44420 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
44421
44422 // Not found as a standard register?
44423 if (!Res.second) {
44424 // Map st(0) -> st(7) -> ST0
44425 if (Constraint.size() == 7 && Constraint[0] == '{' &&
44426 tolower(Constraint[1]) == 's' && tolower(Constraint[2]) == 't' &&
44427 Constraint[3] == '(' &&
44428 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
44429 Constraint[5] == ')' && Constraint[6] == '}') {
44430 // st(7) is not allocatable and thus not a member of RFP80. Return
44431 // singleton class in cases where we have a reference to it.
44432 if (Constraint[4] == '7')
44433 return std::make_pair(X86::FP7, &X86::RFP80_7RegClass);
44434 return std::make_pair(X86::FP0 + Constraint[4] - '0',
44435 &X86::RFP80RegClass);
44436 }
44437
44438 // GCC allows "st(0)" to be called just plain "st".
44439 if (StringRef("{st}").equals_lower(Constraint))
44440 return std::make_pair(X86::FP0, &X86::RFP80RegClass);
44441
44442 // flags -> EFLAGS
44443 if (StringRef("{flags}").equals_lower(Constraint))
44444 return std::make_pair(X86::EFLAGS, &X86::CCRRegClass);
44445
44446 // dirflag -> DF
44447 if (StringRef("{dirflag}").equals_lower(Constraint))
44448 return std::make_pair(X86::DF, &X86::DFCCRRegClass);
44449
44450 // fpsr -> FPSW
44451 if (StringRef("{fpsr}").equals_lower(Constraint))
44452 return std::make_pair(X86::FPSW, &X86::FPCCRRegClass);
44453
44454 return Res;
44455 }
44456
44457 // Make sure it isn't a register that requires 64-bit mode.
44458 if (!Subtarget.is64Bit() &&
44459 (isFRClass(*Res.second) || isGRClass(*Res.second)) &&
44460 TRI->getEncodingValue(Res.first) >= 8) {
44461 // Register requires REX prefix, but we're in 32-bit mode.
44462 return std::make_pair(0, nullptr);
44463 }
44464
44465 // Make sure it isn't a register that requires AVX512.
44466 if (!Subtarget.hasAVX512() && isFRClass(*Res.second) &&
44467 TRI->getEncodingValue(Res.first) & 0x10) {
44468 // Register requires EVEX prefix.
44469 return std::make_pair(0, nullptr);
44470 }
44471
44472 // Otherwise, check to see if this is a register class of the wrong value
44473 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
44474 // turn into {ax},{dx}.
44475 // MVT::Other is used to specify clobber names.
44476 if (TRI->isTypeLegalForClass(*Res.second, VT) || VT == MVT::Other)
44477 return Res; // Correct type already, nothing to do.
44478
44479 // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
44480 // return "eax". This should even work for things like getting 64bit integer
44481 // registers when given an f64 type.
44482 const TargetRegisterClass *Class = Res.second;
44483 // The generic code will match the first register class that contains the
44484 // given register. Thus, based on the ordering of the tablegened file,
44485 // the "plain" GR classes might not come first.
44486 // Therefore, use a helper method.
44487 if (isGRClass(*Class)) {
44488 unsigned Size = VT.getSizeInBits();
44489 if (Size == 1) Size = 8;
44490 unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, Size);
44491 if (DestReg > 0) {
44492 bool is64Bit = Subtarget.is64Bit();
44493 const TargetRegisterClass *RC =
44494 Size == 8 ? (is64Bit ? &X86::GR8RegClass : &X86::GR8_NOREXRegClass)
44495 : Size == 16 ? (is64Bit ? &X86::GR16RegClass : &X86::GR16_NOREXRegClass)
44496 : Size == 32 ? (is64Bit ? &X86::GR32RegClass : &X86::GR32_NOREXRegClass)
44497 : Size == 64 ? (is64Bit ? &X86::GR64RegClass : nullptr)
44498 : nullptr;
44499 if (Size == 64 && !is64Bit) {
44500 // Model GCC's behavior here and select a fixed pair of 32-bit
44501 // registers.
44502 switch (DestReg) {
44503 case X86::RAX:
44504 return std::make_pair(X86::EAX, &X86::GR32_ADRegClass);
44505 case X86::RDX:
44506 return std::make_pair(X86::EDX, &X86::GR32_DCRegClass);
44507 case X86::RCX:
44508 return std::make_pair(X86::ECX, &X86::GR32_CBRegClass);
44509 case X86::RBX:
44510 return std::make_pair(X86::EBX, &X86::GR32_BSIRegClass);
44511 case X86::RSI:
44512 return std::make_pair(X86::ESI, &X86::GR32_SIDIRegClass);
44513 case X86::RDI:
44514 return std::make_pair(X86::EDI, &X86::GR32_DIBPRegClass);
44515 case X86::RBP:
44516 return std::make_pair(X86::EBP, &X86::GR32_BPSPRegClass);
44517 default:
44518 return std::make_pair(0, nullptr);
44519 }
44520 }
44521 if (RC && RC->contains(DestReg))
44522 return std::make_pair(DestReg, RC);
44523 return Res;
44524 }
44525 // No register found/type mismatch.
44526 return std::make_pair(0, nullptr);
44527 } else if (isFRClass(*Class)) {
44528 // Handle references to XMM physical registers that got mapped into the
44529 // wrong class. This can happen with constraints like {xmm0} where the
44530 // target independent register mapper will just pick the first match it can
44531 // find, ignoring the required type.
44532
44533 // TODO: Handle f128 and i128 in FR128RegClass after it is tested well.
44534 if (VT == MVT::f32 || VT == MVT::i32)
44535 Res.second = &X86::FR32XRegClass;
44536 else if (VT == MVT::f64 || VT == MVT::i64)
44537 Res.second = &X86::FR64XRegClass;
44538 else if (TRI->isTypeLegalForClass(X86::VR128XRegClass, VT))
44539 Res.second = &X86::VR128XRegClass;
44540 else if (TRI->isTypeLegalForClass(X86::VR256XRegClass, VT))
44541 Res.second = &X86::VR256XRegClass;
44542 else if (TRI->isTypeLegalForClass(X86::VR512RegClass, VT))
44543 Res.second = &X86::VR512RegClass;
44544 else {
44545 // Type mismatch and not a clobber: Return an error;
44546 Res.first = 0;
44547 Res.second = nullptr;
44548 }
44549 } else if (isVKClass(*Class)) {
44550 if (VT == MVT::i1)
44551 Res.second = &X86::VK1RegClass;
44552 else if (VT == MVT::i8)
44553 Res.second = &X86::VK8RegClass;
44554 else if (VT == MVT::i16)
44555 Res.second = &X86::VK16RegClass;
44556 else if (VT == MVT::i32)
44557 Res.second = &X86::VK32RegClass;
44558 else if (VT == MVT::i64)
44559 Res.second = &X86::VK64RegClass;
44560 else {
44561 // Type mismatch and not a clobber: Return an error;
44562 Res.first = 0;
44563 Res.second = nullptr;
44564 }
44565 }
44566
44567 return Res;
44568}
44569
44570int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
44571 const AddrMode &AM, Type *Ty,
44572 unsigned AS) const {
44573 // Scaling factors are not free at all.
44574 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
44575 // will take 2 allocations in the out of order engine instead of 1
44576 // for plain addressing mode, i.e. inst (reg1).
44577 // E.g.,
44578 // vaddps (%rsi,%rdx), %ymm0, %ymm1
44579 // Requires two allocations (one for the load, one for the computation)
44580 // whereas:
44581 // vaddps (%rsi), %ymm0, %ymm1
44582 // Requires just 1 allocation, i.e., freeing allocations for other operations
44583 // and having less micro operations to execute.
44584 //
44585 // For some X86 architectures, this is even worse because for instance for
44586 // stores, the complex addressing mode forces the instruction to use the
44587 // "load" ports instead of the dedicated "store" port.
44588 // E.g., on Haswell:
44589 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
44590 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
44591 if (isLegalAddressingMode(DL, AM, Ty, AS))
44592 // Scale represents reg2 * scale, thus account for 1
44593 // as soon as we use a second register.
44594 return AM.Scale != 0;
44595 return -1;
44596}
44597
44598bool X86TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
44599 // Integer division on x86 is expensive. However, when aggressively optimizing
44600 // for code size, we prefer to use a div instruction, as it is usually smaller
44601 // than the alternative sequence.
44602 // The exception to this is vector division. Since x86 doesn't have vector
44603 // integer division, leaving the division as-is is a loss even in terms of
44604 // size, because it will have to be scalarized, while the alternative code
44605 // sequence can be performed in vector form.
44606 bool OptSize =
44607 Attr.hasAttribute(AttributeList::FunctionIndex, Attribute::MinSize);
44608 return OptSize && !VT.isVector();
44609}
44610
44611void X86TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
44612 if (!Subtarget.is64Bit())
44613 return;
44614
44615 // Update IsSplitCSR in X86MachineFunctionInfo.
44616 X86MachineFunctionInfo *AFI =
44617 Entry->getParent()->getInfo<X86MachineFunctionInfo>();
44618 AFI->setIsSplitCSR(true);
44619}
44620
44621void X86TargetLowering::insertCopiesSplitCSR(
44622 MachineBasicBlock *Entry,
44623 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
44624 const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
44625 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
44626 if (!IStart)
44627 return;
44628
44629 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
44630 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
44631 MachineBasicBlock::iterator MBBI = Entry->begin();
44632 for (const MCPhysReg *I = IStart; *I; ++I) {
44633 const TargetRegisterClass *RC = nullptr;
44634 if (X86::GR64RegClass.contains(*I))
44635 RC = &X86::GR64RegClass;
44636 else
44637 llvm_unreachable("Unexpected register class in CSRsViaCopy!")::llvm::llvm_unreachable_internal("Unexpected register class in CSRsViaCopy!"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 44637)
;
44638
44639 unsigned NewVR = MRI->createVirtualRegister(RC);
44640 // Create copy from CSR to a virtual register.
44641 // FIXME: this currently does not emit CFI pseudo-instructions, it works
44642 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
44643 // nounwind. If we want to generalize this later, we may need to emit
44644 // CFI pseudo-instructions.
44645 assert(((Entry->getParent()->getFunction().hasFnAttribute(Attribute
::NoUnwind) && "Function should be nounwind in insertCopiesSplitCSR!"
) ? static_cast<void> (0) : __assert_fail ("Entry->getParent()->getFunction().hasFnAttribute(Attribute::NoUnwind) && \"Function should be nounwind in insertCopiesSplitCSR!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 44647, __PRETTY_FUNCTION__))
44646 Entry->getParent()->getFunction().hasFnAttribute(Attribute::NoUnwind) &&((Entry->getParent()->getFunction().hasFnAttribute(Attribute
::NoUnwind) && "Function should be nounwind in insertCopiesSplitCSR!"
) ? static_cast<void> (0) : __assert_fail ("Entry->getParent()->getFunction().hasFnAttribute(Attribute::NoUnwind) && \"Function should be nounwind in insertCopiesSplitCSR!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 44647, __PRETTY_FUNCTION__))
44647 "Function should be nounwind in insertCopiesSplitCSR!")((Entry->getParent()->getFunction().hasFnAttribute(Attribute
::NoUnwind) && "Function should be nounwind in insertCopiesSplitCSR!"
) ? static_cast<void> (0) : __assert_fail ("Entry->getParent()->getFunction().hasFnAttribute(Attribute::NoUnwind) && \"Function should be nounwind in insertCopiesSplitCSR!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/Target/X86/X86ISelLowering.cpp"
, 44647, __PRETTY_FUNCTION__))
;
44648 Entry->addLiveIn(*I);
44649 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
44650 .addReg(*I);
44651
44652 // Insert the copy-back instructions right before the terminator.
44653 for (auto *Exit : Exits)
44654 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
44655 TII->get(TargetOpcode::COPY), *I)
44656 .addReg(NewVR);
44657 }
44658}
44659
44660bool X86TargetLowering::supportSwiftError() const {
44661 return Subtarget.is64Bit();
44662}
44663
44664/// Returns the name of the symbol used to emit stack probes or the empty
44665/// string if not applicable.
44666StringRef
44667X86TargetLowering::getStackProbeSymbolName(MachineFunction &MF) const {
44668 // If the function specifically requests stack probes, emit them.
44669 if (MF.getFunction().hasFnAttribute("probe-stack"))
44670 return MF.getFunction().getFnAttribute("probe-stack").getValueAsString();
44671
44672 // Generally, if we aren't on Windows, the platform ABI does not include
44673 // support for stack probes, so don't emit them.
44674 if (!Subtarget.isOSWindows() || Subtarget.isTargetMachO() ||
44675 MF.getFunction().hasFnAttribute("no-stack-arg-probe"))
44676 return "";
44677
44678 // We need a stack probe to conform to the Windows ABI. Choose the right
44679 // symbol.
44680 if (Subtarget.is64Bit())
44681 return Subtarget.isTargetCygMing() ? "___chkstk_ms" : "__chkstk";
44682 return Subtarget.isTargetCygMing() ? "_alloca" : "_chkstk";
44683}