1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86FrameLowering.h"
19 #include "X86InstrBuilder.h"
20 #include "X86MachineFunctionInfo.h"
21 #include "X86ShuffleDecodeConstantPool.h"
22 #include "X86TargetMachine.h"
23 #include "X86TargetObjectFile.h"
24 #include "llvm/ADT/SmallBitVector.h"
25 #include "llvm/ADT/SmallSet.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/ADT/StringSwitch.h"
29 #include "llvm/Analysis/EHPersonalities.h"
30 #include "llvm/CodeGen/IntrinsicLowering.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineJumpTableInfo.h"
35 #include "llvm/CodeGen/MachineModuleInfo.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.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/Function.h"
43 #include "llvm/IR/GlobalAlias.h"
44 #include "llvm/IR/GlobalVariable.h"
45 #include "llvm/IR/Instructions.h"
46 #include "llvm/IR/Intrinsics.h"
47 #include "llvm/MC/MCAsmInfo.h"
48 #include "llvm/MC/MCContext.h"
49 #include "llvm/MC/MCExpr.h"
50 #include "llvm/MC/MCSymbol.h"
51 #include "llvm/Support/CommandLine.h"
52 #include "llvm/Support/Debug.h"
53 #include "llvm/Support/ErrorHandling.h"
54 #include "llvm/Support/MathExtras.h"
55 #include "llvm/Target/TargetOptions.h"
56 #include "X86IntrinsicsInfo.h"
62 #define DEBUG_TYPE "x86-isel"
64 STATISTIC(NumTailCalls, "Number of tail calls");
66 static cl::opt<bool> ExperimentalVectorWideningLegalization(
67 "x86-experimental-vector-widening-legalization", cl::init(false),
68 cl::desc("Enable an experimental vector type legalization through widening "
69 "rather than promotion."),
72 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
73 const X86Subtarget &STI)
74 : TargetLowering(TM), Subtarget(&STI) {
75 X86ScalarSSEf64 = Subtarget->hasSSE2();
76 X86ScalarSSEf32 = Subtarget->hasSSE1();
77 MVT PtrVT = MVT::getIntegerVT(8 * TM.getPointerSize());
79 // Set up the TargetLowering object.
81 // X86 is weird. It always uses i8 for shift amounts and setcc results.
82 setBooleanContents(ZeroOrOneBooleanContent);
83 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
84 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
86 // For 64-bit, since we have so many registers, use the ILP scheduler.
87 // For 32-bit, use the register pressure specific scheduling.
88 // For Atom, always use ILP scheduling.
89 if (Subtarget->isAtom())
90 setSchedulingPreference(Sched::ILP);
91 else if (Subtarget->is64Bit())
92 setSchedulingPreference(Sched::ILP);
94 setSchedulingPreference(Sched::RegPressure);
95 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
96 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
98 // Bypass expensive divides on Atom when compiling with O2.
99 if (TM.getOptLevel() >= CodeGenOpt::Default) {
100 if (Subtarget->hasSlowDivide32())
101 addBypassSlowDiv(32, 8);
102 if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
103 addBypassSlowDiv(64, 16);
106 if (Subtarget->isTargetKnownWindowsMSVC()) {
107 // Setup Windows compiler runtime calls.
108 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
109 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
110 setLibcallName(RTLIB::SREM_I64, "_allrem");
111 setLibcallName(RTLIB::UREM_I64, "_aullrem");
112 setLibcallName(RTLIB::MUL_I64, "_allmul");
113 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
114 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
115 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
116 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
117 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
120 if (Subtarget->isTargetDarwin()) {
121 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
122 setUseUnderscoreSetJmp(false);
123 setUseUnderscoreLongJmp(false);
124 } else if (Subtarget->isTargetWindowsGNU()) {
125 // MS runtime is weird: it exports _setjmp, but longjmp!
126 setUseUnderscoreSetJmp(true);
127 setUseUnderscoreLongJmp(false);
129 setUseUnderscoreSetJmp(true);
130 setUseUnderscoreLongJmp(true);
133 // Set up the register classes.
134 addRegisterClass(MVT::i8, &X86::GR8RegClass);
135 addRegisterClass(MVT::i16, &X86::GR16RegClass);
136 addRegisterClass(MVT::i32, &X86::GR32RegClass);
137 if (Subtarget->is64Bit())
138 addRegisterClass(MVT::i64, &X86::GR64RegClass);
140 for (MVT VT : MVT::integer_valuetypes())
141 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
143 // We don't accept any truncstore of integer registers.
144 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
145 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
146 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
147 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
148 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
149 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
151 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
153 // SETOEQ and SETUNE require checking two conditions.
154 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
155 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
156 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
157 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
158 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
159 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
161 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
163 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
164 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
165 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
167 if (Subtarget->is64Bit()) {
168 if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512())
169 // f32/f64 are legal, f80 is custom.
170 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
172 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
173 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
174 } else if (!Subtarget->useSoftFloat()) {
175 // We have an algorithm for SSE2->double, and we turn this into a
176 // 64-bit FILD followed by conditional FADD for other targets.
177 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
178 // We have an algorithm for SSE2, and we turn this into a 64-bit
179 // FILD or VCVTUSI2SS/SD for other targets.
180 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
183 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
185 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
186 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
188 if (!Subtarget->useSoftFloat()) {
189 // SSE has no i16 to fp conversion, only i32
190 if (X86ScalarSSEf32) {
191 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
192 // f32 and f64 cases are Legal, f80 case is not
193 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
195 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
196 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
199 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
200 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
203 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
205 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
206 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
208 if (!Subtarget->useSoftFloat()) {
209 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
210 // are Legal, f80 is custom lowered.
211 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
212 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
214 if (X86ScalarSSEf32) {
215 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
216 // f32 and f64 cases are Legal, f80 case is not
217 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
219 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
220 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
223 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
224 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Expand);
225 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Expand);
228 // Handle FP_TO_UINT by promoting the destination to a larger signed
230 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
231 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
232 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
234 if (Subtarget->is64Bit()) {
235 if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
236 // FP_TO_UINT-i32/i64 is legal for f32/f64, but custom for f80.
237 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
238 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
240 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
241 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
243 } else if (!Subtarget->useSoftFloat()) {
244 // Since AVX is a superset of SSE3, only check for SSE here.
245 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
246 // Expand FP_TO_UINT into a select.
247 // FIXME: We would like to use a Custom expander here eventually to do
248 // the optimal thing for SSE vs. the default expansion in the legalizer.
249 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
251 // With AVX512 we can use vcvts[ds]2usi for f32/f64->i32, f80 is custom.
252 // With SSE3 we can use fisttpll to convert to a signed i64; without
253 // SSE, we're stuck with a fistpll.
254 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
256 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
259 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
260 if (!X86ScalarSSEf64) {
261 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
262 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
263 if (Subtarget->is64Bit()) {
264 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
265 // Without SSE, i64->f64 goes through memory.
266 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
270 // Scalar integer divide and remainder are lowered to use operations that
271 // produce two results, to match the available instructions. This exposes
272 // the two-result form to trivial CSE, which is able to combine x/y and x%y
273 // into a single instruction.
275 // Scalar integer multiply-high is also lowered to use two-result
276 // operations, to match the available instructions. However, plain multiply
277 // (low) operations are left as Legal, as there are single-result
278 // instructions for this in x86. Using the two-result multiply instructions
279 // when both high and low results are needed must be arranged by dagcombine.
280 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
281 setOperationAction(ISD::MULHS, VT, Expand);
282 setOperationAction(ISD::MULHU, VT, Expand);
283 setOperationAction(ISD::SDIV, VT, Expand);
284 setOperationAction(ISD::UDIV, VT, Expand);
285 setOperationAction(ISD::SREM, VT, Expand);
286 setOperationAction(ISD::UREM, VT, Expand);
288 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
289 setOperationAction(ISD::ADDC, VT, Custom);
290 setOperationAction(ISD::ADDE, VT, Custom);
291 setOperationAction(ISD::SUBC, VT, Custom);
292 setOperationAction(ISD::SUBE, VT, Custom);
295 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
296 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
297 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
298 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
299 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
300 setOperationAction(ISD::BR_CC , MVT::f128, Expand);
301 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
302 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
303 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
304 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
305 setOperationAction(ISD::SELECT_CC , MVT::f32, Expand);
306 setOperationAction(ISD::SELECT_CC , MVT::f64, Expand);
307 setOperationAction(ISD::SELECT_CC , MVT::f80, Expand);
308 setOperationAction(ISD::SELECT_CC , MVT::f128, Expand);
309 setOperationAction(ISD::SELECT_CC , MVT::i8, Expand);
310 setOperationAction(ISD::SELECT_CC , MVT::i16, Expand);
311 setOperationAction(ISD::SELECT_CC , MVT::i32, Expand);
312 setOperationAction(ISD::SELECT_CC , MVT::i64, Expand);
313 if (Subtarget->is64Bit())
314 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
315 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
316 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
317 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
318 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
320 if (Subtarget->is32Bit() && Subtarget->isTargetKnownWindowsMSVC()) {
321 // On 32 bit MSVC, `fmodf(f32)` is not defined - only `fmod(f64)`
322 // is. We should promote the value to 64-bits to solve this.
323 // This is what the CRT headers do - `fmodf` is an inline header
324 // function casting to f64 and calling `fmod`.
325 setOperationAction(ISD::FREM , MVT::f32 , Promote);
327 setOperationAction(ISD::FREM , MVT::f32 , Expand);
330 setOperationAction(ISD::FREM , MVT::f64 , Expand);
331 setOperationAction(ISD::FREM , MVT::f80 , Expand);
332 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
334 // Promote the i8 variants and force them on up to i32 which has a shorter
336 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
337 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
338 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
339 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
340 if (Subtarget->hasBMI()) {
341 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
342 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
343 if (Subtarget->is64Bit())
344 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
346 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
347 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
348 if (Subtarget->is64Bit())
349 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
352 if (Subtarget->hasLZCNT()) {
353 // When promoting the i8 variants, force them to i32 for a shorter
355 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
356 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
357 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
358 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
359 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
360 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
361 if (Subtarget->is64Bit())
362 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
364 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
365 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
366 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
367 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
368 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
369 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
370 if (Subtarget->is64Bit()) {
371 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
372 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
376 // Special handling for half-precision floating point conversions.
377 // If we don't have F16C support, then lower half float conversions
378 // into library calls.
379 if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) {
380 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
381 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
384 // There's never any support for operations beyond MVT::f32.
385 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
386 setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
387 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
388 setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
390 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
391 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
392 setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
393 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
394 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
395 setTruncStoreAction(MVT::f80, MVT::f16, Expand);
397 if (Subtarget->hasPOPCNT()) {
398 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
400 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
401 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
402 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
403 if (Subtarget->is64Bit())
404 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
407 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
409 if (!Subtarget->hasMOVBE())
410 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
412 // These should be promoted to a larger select which is supported.
413 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
414 // X86 wants to expand cmov itself.
415 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
416 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
417 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
418 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
419 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
420 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
421 setOperationAction(ISD::SELECT , MVT::f128 , Custom);
422 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
423 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
424 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
425 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
426 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
427 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
428 setOperationAction(ISD::SETCC , MVT::f128 , Custom);
429 setOperationAction(ISD::SETCCE , MVT::i8 , Custom);
430 setOperationAction(ISD::SETCCE , MVT::i16 , Custom);
431 setOperationAction(ISD::SETCCE , MVT::i32 , Custom);
432 if (Subtarget->is64Bit()) {
433 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
434 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
435 setOperationAction(ISD::SETCCE , MVT::i64 , Custom);
437 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
438 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
439 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
440 // support continuation, user-level threading, and etc.. As a result, no
441 // other SjLj exception interfaces are implemented and please don't build
442 // your own exception handling based on them.
443 // LLVM/Clang supports zero-cost DWARF exception handling.
444 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
445 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
448 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
449 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
450 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
451 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
452 if (Subtarget->is64Bit())
453 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
454 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
455 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
456 if (Subtarget->is64Bit()) {
457 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
458 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
459 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
460 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
461 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
463 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
464 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
465 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
466 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
467 if (Subtarget->is64Bit()) {
468 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
469 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
470 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
473 if (Subtarget->hasSSE1())
474 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
476 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
478 // Expand certain atomics
479 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
480 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
481 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
482 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
485 if (Subtarget->hasCmpxchg16b()) {
486 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
489 // FIXME - use subtarget debug flags
490 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
491 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
492 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
495 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
496 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
498 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
499 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
501 setOperationAction(ISD::TRAP, MVT::Other, Legal);
502 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
504 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
505 setOperationAction(ISD::VASTART , MVT::Other, Custom);
506 setOperationAction(ISD::VAEND , MVT::Other, Expand);
507 if (Subtarget->is64Bit()) {
508 setOperationAction(ISD::VAARG , MVT::Other, Custom);
509 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
511 // TargetInfo::CharPtrBuiltinVaList
512 setOperationAction(ISD::VAARG , MVT::Other, Expand);
513 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
516 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
517 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
519 setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
521 // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
522 setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
523 setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
525 if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
526 // f32 and f64 use SSE.
527 // Set up the FP register classes.
528 addRegisterClass(MVT::f32, &X86::FR32RegClass);
529 addRegisterClass(MVT::f64, &X86::FR64RegClass);
531 // Use ANDPD to simulate FABS.
532 setOperationAction(ISD::FABS , MVT::f64, Custom);
533 setOperationAction(ISD::FABS , MVT::f32, Custom);
535 // Use XORP to simulate FNEG.
536 setOperationAction(ISD::FNEG , MVT::f64, Custom);
537 setOperationAction(ISD::FNEG , MVT::f32, Custom);
539 // Use ANDPD and ORPD to simulate FCOPYSIGN.
540 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
541 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
543 // Lower this to FGETSIGNx86 plus an AND.
544 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
545 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
547 // We don't support sin/cos/fmod
548 setOperationAction(ISD::FSIN , MVT::f64, Expand);
549 setOperationAction(ISD::FCOS , MVT::f64, Expand);
550 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
551 setOperationAction(ISD::FSIN , MVT::f32, Expand);
552 setOperationAction(ISD::FCOS , MVT::f32, Expand);
553 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
555 // Expand FP immediates into loads from the stack, except for the special
557 addLegalFPImmediate(APFloat(+0.0)); // xorpd
558 addLegalFPImmediate(APFloat(+0.0f)); // xorps
559 } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
560 // Use SSE for f32, x87 for f64.
561 // Set up the FP register classes.
562 addRegisterClass(MVT::f32, &X86::FR32RegClass);
563 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
565 // Use ANDPS to simulate FABS.
566 setOperationAction(ISD::FABS , MVT::f32, Custom);
568 // Use XORP to simulate FNEG.
569 setOperationAction(ISD::FNEG , MVT::f32, Custom);
571 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
573 // Use ANDPS and ORPS to simulate FCOPYSIGN.
574 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
575 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
577 // We don't support sin/cos/fmod
578 setOperationAction(ISD::FSIN , MVT::f32, Expand);
579 setOperationAction(ISD::FCOS , MVT::f32, Expand);
580 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
582 // Special cases we handle for FP constants.
583 addLegalFPImmediate(APFloat(+0.0f)); // xorps
584 addLegalFPImmediate(APFloat(+0.0)); // FLD0
585 addLegalFPImmediate(APFloat(+1.0)); // FLD1
586 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
587 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
589 if (!TM.Options.UnsafeFPMath) {
590 setOperationAction(ISD::FSIN , MVT::f64, Expand);
591 setOperationAction(ISD::FCOS , MVT::f64, Expand);
592 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
594 } else if (!Subtarget->useSoftFloat()) {
595 // f32 and f64 in x87.
596 // Set up the FP register classes.
597 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
598 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
600 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
601 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
602 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
603 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
605 if (!TM.Options.UnsafeFPMath) {
606 setOperationAction(ISD::FSIN , MVT::f64, Expand);
607 setOperationAction(ISD::FSIN , MVT::f32, Expand);
608 setOperationAction(ISD::FCOS , MVT::f64, Expand);
609 setOperationAction(ISD::FCOS , MVT::f32, Expand);
610 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
611 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
613 addLegalFPImmediate(APFloat(+0.0)); // FLD0
614 addLegalFPImmediate(APFloat(+1.0)); // FLD1
615 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
616 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
617 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
618 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
619 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
620 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
623 // We don't support FMA.
624 setOperationAction(ISD::FMA, MVT::f64, Expand);
625 setOperationAction(ISD::FMA, MVT::f32, Expand);
627 // Long double always uses X87, except f128 in MMX.
628 if (!Subtarget->useSoftFloat()) {
629 if (Subtarget->is64Bit() && Subtarget->hasMMX()) {
630 addRegisterClass(MVT::f128, &X86::FR128RegClass);
631 ValueTypeActions.setTypeAction(MVT::f128, TypeSoftenFloat);
632 setOperationAction(ISD::FABS , MVT::f128, Custom);
633 setOperationAction(ISD::FNEG , MVT::f128, Custom);
634 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Custom);
637 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
638 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
639 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
641 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
642 addLegalFPImmediate(TmpFlt); // FLD0
644 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
647 APFloat TmpFlt2(+1.0);
648 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
650 addLegalFPImmediate(TmpFlt2); // FLD1
651 TmpFlt2.changeSign();
652 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
655 if (!TM.Options.UnsafeFPMath) {
656 setOperationAction(ISD::FSIN , MVT::f80, Expand);
657 setOperationAction(ISD::FCOS , MVT::f80, Expand);
658 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
661 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
662 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
663 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
664 setOperationAction(ISD::FRINT, MVT::f80, Expand);
665 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
666 setOperationAction(ISD::FMA, MVT::f80, Expand);
669 // Always use a library call for pow.
670 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
671 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
672 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
674 setOperationAction(ISD::FLOG, MVT::f80, Expand);
675 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
676 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
677 setOperationAction(ISD::FEXP, MVT::f80, Expand);
678 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
679 setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
680 setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
682 // First set operation action for all vector types to either promote
683 // (for widening) or expand (for scalarization). Then we will selectively
684 // turn on ones that can be effectively codegen'd.
685 for (MVT VT : MVT::vector_valuetypes()) {
686 setOperationAction(ISD::ADD , VT, Expand);
687 setOperationAction(ISD::SUB , VT, Expand);
688 setOperationAction(ISD::FADD, VT, Expand);
689 setOperationAction(ISD::FNEG, VT, Expand);
690 setOperationAction(ISD::FSUB, VT, Expand);
691 setOperationAction(ISD::MUL , VT, Expand);
692 setOperationAction(ISD::FMUL, VT, Expand);
693 setOperationAction(ISD::SDIV, VT, Expand);
694 setOperationAction(ISD::UDIV, VT, Expand);
695 setOperationAction(ISD::FDIV, VT, Expand);
696 setOperationAction(ISD::SREM, VT, Expand);
697 setOperationAction(ISD::UREM, VT, Expand);
698 setOperationAction(ISD::LOAD, VT, Expand);
699 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
700 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
701 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
702 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
703 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
704 setOperationAction(ISD::FABS, VT, Expand);
705 setOperationAction(ISD::FSIN, VT, Expand);
706 setOperationAction(ISD::FSINCOS, VT, Expand);
707 setOperationAction(ISD::FCOS, VT, Expand);
708 setOperationAction(ISD::FSINCOS, VT, Expand);
709 setOperationAction(ISD::FREM, VT, Expand);
710 setOperationAction(ISD::FMA, VT, Expand);
711 setOperationAction(ISD::FPOWI, VT, Expand);
712 setOperationAction(ISD::FSQRT, VT, Expand);
713 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
714 setOperationAction(ISD::FFLOOR, VT, Expand);
715 setOperationAction(ISD::FCEIL, VT, Expand);
716 setOperationAction(ISD::FTRUNC, VT, Expand);
717 setOperationAction(ISD::FRINT, VT, Expand);
718 setOperationAction(ISD::FNEARBYINT, VT, Expand);
719 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
720 setOperationAction(ISD::MULHS, VT, Expand);
721 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
722 setOperationAction(ISD::MULHU, VT, Expand);
723 setOperationAction(ISD::SDIVREM, VT, Expand);
724 setOperationAction(ISD::UDIVREM, VT, Expand);
725 setOperationAction(ISD::FPOW, VT, Expand);
726 setOperationAction(ISD::CTPOP, VT, Expand);
727 setOperationAction(ISD::CTTZ, VT, Expand);
728 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
729 setOperationAction(ISD::CTLZ, VT, Expand);
730 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
731 setOperationAction(ISD::SHL, VT, Expand);
732 setOperationAction(ISD::SRA, VT, Expand);
733 setOperationAction(ISD::SRL, VT, Expand);
734 setOperationAction(ISD::ROTL, VT, Expand);
735 setOperationAction(ISD::ROTR, VT, Expand);
736 setOperationAction(ISD::BSWAP, VT, Expand);
737 setOperationAction(ISD::SETCC, VT, Expand);
738 setOperationAction(ISD::FLOG, VT, Expand);
739 setOperationAction(ISD::FLOG2, VT, Expand);
740 setOperationAction(ISD::FLOG10, VT, Expand);
741 setOperationAction(ISD::FEXP, VT, Expand);
742 setOperationAction(ISD::FEXP2, VT, Expand);
743 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
744 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
745 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
746 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
747 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
748 setOperationAction(ISD::TRUNCATE, VT, Expand);
749 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
750 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
751 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
752 setOperationAction(ISD::VSELECT, VT, Expand);
753 setOperationAction(ISD::SELECT_CC, VT, Expand);
754 for (MVT InnerVT : MVT::vector_valuetypes()) {
755 setTruncStoreAction(InnerVT, VT, Expand);
757 setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
758 setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
760 // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
761 // types, we have to deal with them whether we ask for Expansion or not.
762 // Setting Expand causes its own optimisation problems though, so leave
764 if (VT.getVectorElementType() == MVT::i1)
765 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
767 // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
768 // split/scalarized right now.
769 if (VT.getVectorElementType() == MVT::f16)
770 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
774 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
775 // with -msoft-float, disable use of MMX as well.
776 if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
777 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
778 // No operations on x86mmx supported, everything uses intrinsics.
781 // MMX-sized vectors (other than x86mmx) are expected to be expanded
782 // into smaller operations.
783 for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
784 setOperationAction(ISD::MULHS, MMXTy, Expand);
785 setOperationAction(ISD::AND, MMXTy, Expand);
786 setOperationAction(ISD::OR, MMXTy, Expand);
787 setOperationAction(ISD::XOR, MMXTy, Expand);
788 setOperationAction(ISD::SCALAR_TO_VECTOR, MMXTy, Expand);
789 setOperationAction(ISD::SELECT, MMXTy, Expand);
790 setOperationAction(ISD::BITCAST, MMXTy, Expand);
792 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
794 if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
795 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
797 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
798 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
799 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
800 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
801 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
802 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
803 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
804 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
805 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
806 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
807 setOperationAction(ISD::VSELECT, MVT::v4f32, Custom);
808 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
809 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
810 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
813 if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
814 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
816 // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
817 // registers cannot be used even for integer operations.
818 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
819 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
820 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
821 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
823 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
824 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
825 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
826 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
827 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
828 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
829 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
830 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
831 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
832 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
833 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
834 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
835 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
836 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
837 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
838 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
839 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
840 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
841 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
842 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
843 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
844 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
845 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
847 setOperationAction(ISD::SMAX, MVT::v8i16, Legal);
848 setOperationAction(ISD::UMAX, MVT::v16i8, Legal);
849 setOperationAction(ISD::SMIN, MVT::v8i16, Legal);
850 setOperationAction(ISD::UMIN, MVT::v16i8, Legal);
852 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
853 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
854 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
855 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
857 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
858 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
859 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
860 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
861 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
863 setOperationAction(ISD::CTPOP, MVT::v16i8, Custom);
864 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
865 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
866 setOperationAction(ISD::CTPOP, MVT::v2i64, Custom);
868 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
869 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
870 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
871 // ISD::CTTZ v2i64 - scalarization is faster.
872 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
873 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
874 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
875 // ISD::CTTZ_ZERO_UNDEF v2i64 - scalarization is faster.
877 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
878 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
879 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
880 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
881 setOperationAction(ISD::VSELECT, VT, Custom);
882 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
885 // We support custom legalizing of sext and anyext loads for specific
886 // memory vector types which we can load as a scalar (or sequence of
887 // scalars) and extend in-register to a legal 128-bit vector type. For sext
888 // loads these must work with a single scalar load.
889 for (MVT VT : MVT::integer_vector_valuetypes()) {
890 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
891 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
892 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
893 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
894 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
895 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
896 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
897 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
898 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
901 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
902 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
903 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
904 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
905 setOperationAction(ISD::VSELECT, MVT::v2f64, Custom);
906 setOperationAction(ISD::VSELECT, MVT::v2i64, Custom);
907 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
908 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
910 if (Subtarget->is64Bit()) {
911 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
912 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
915 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
916 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
917 setOperationAction(ISD::AND, VT, Promote);
918 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
919 setOperationAction(ISD::OR, VT, Promote);
920 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
921 setOperationAction(ISD::XOR, VT, Promote);
922 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
923 setOperationAction(ISD::LOAD, VT, Promote);
924 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
925 setOperationAction(ISD::SELECT, VT, Promote);
926 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
929 // Custom lower v2i64 and v2f64 selects.
930 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
931 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
932 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
933 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
935 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
936 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
938 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
940 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
941 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
942 // As there is no 64-bit GPR available, we need build a special custom
943 // sequence to convert from v2i32 to v2f32.
944 if (!Subtarget->is64Bit())
945 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
947 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
948 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
950 for (MVT VT : MVT::fp_vector_valuetypes())
951 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
953 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
954 setOperationAction(ISD::BITCAST, MVT::v4i16, Custom);
955 setOperationAction(ISD::BITCAST, MVT::v8i8, Custom);
958 if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
959 for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
960 setOperationAction(ISD::FFLOOR, RoundedTy, Legal);
961 setOperationAction(ISD::FCEIL, RoundedTy, Legal);
962 setOperationAction(ISD::FTRUNC, RoundedTy, Legal);
963 setOperationAction(ISD::FRINT, RoundedTy, Legal);
964 setOperationAction(ISD::FNEARBYINT, RoundedTy, Legal);
967 setOperationAction(ISD::SMAX, MVT::v16i8, Legal);
968 setOperationAction(ISD::SMAX, MVT::v4i32, Legal);
969 setOperationAction(ISD::UMAX, MVT::v8i16, Legal);
970 setOperationAction(ISD::UMAX, MVT::v4i32, Legal);
971 setOperationAction(ISD::SMIN, MVT::v16i8, Legal);
972 setOperationAction(ISD::SMIN, MVT::v4i32, Legal);
973 setOperationAction(ISD::UMIN, MVT::v8i16, Legal);
974 setOperationAction(ISD::UMIN, MVT::v4i32, Legal);
976 // FIXME: Do we need to handle scalar-to-vector here?
977 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
979 // We directly match byte blends in the backend as they match the VSELECT
981 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
983 // SSE41 brings specific instructions for doing vector sign extend even in
984 // cases where we don't have SRA.
985 for (MVT VT : MVT::integer_vector_valuetypes()) {
986 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
987 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
988 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
991 // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
992 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8, Legal);
993 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8, Legal);
994 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8, Legal);
995 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
996 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
997 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
999 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8, Legal);
1000 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8, Legal);
1001 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8, Legal);
1002 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
1003 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
1004 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
1006 // i8 and i16 vectors are custom because the source register and source
1007 // source memory operand types are not the same width. f32 vectors are
1008 // custom since the immediate controlling the insert encodes additional
1010 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1011 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1012 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1013 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1015 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1016 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1017 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1018 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1020 // FIXME: these should be Legal, but that's only for the case where
1021 // the index is constant. For now custom expand to deal with that.
1022 if (Subtarget->is64Bit()) {
1023 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1024 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1028 if (Subtarget->hasSSE2()) {
1029 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1030 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1031 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1033 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1034 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1036 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1037 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1039 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1040 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1042 // In the customized shift lowering, the legal cases in AVX2 will be
1044 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1045 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1047 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1048 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1050 setOperationAction(ISD::SRA, MVT::v2i64, Custom);
1051 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1054 if (Subtarget->hasXOP()) {
1055 setOperationAction(ISD::ROTL, MVT::v16i8, Custom);
1056 setOperationAction(ISD::ROTL, MVT::v8i16, Custom);
1057 setOperationAction(ISD::ROTL, MVT::v4i32, Custom);
1058 setOperationAction(ISD::ROTL, MVT::v2i64, Custom);
1059 setOperationAction(ISD::ROTL, MVT::v32i8, Custom);
1060 setOperationAction(ISD::ROTL, MVT::v16i16, Custom);
1061 setOperationAction(ISD::ROTL, MVT::v8i32, Custom);
1062 setOperationAction(ISD::ROTL, MVT::v4i64, Custom);
1065 if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1066 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1067 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1068 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1069 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1070 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1071 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1073 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1074 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1075 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1077 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1078 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1079 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1080 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1081 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1082 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1083 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1084 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1085 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1086 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1087 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1088 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1090 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1091 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1092 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1093 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1094 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1095 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1096 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1097 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1098 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1099 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1100 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1101 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1103 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1104 // even though v8i16 is a legal type.
1105 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1106 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1107 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1109 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1110 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1111 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1113 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1114 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1116 for (MVT VT : MVT::fp_vector_valuetypes())
1117 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1119 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1120 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1122 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1123 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1125 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1126 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1128 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1129 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1130 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1131 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1133 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1134 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1135 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1137 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1138 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1139 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1140 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1141 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1142 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1143 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1144 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1145 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1146 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1147 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1148 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1150 setOperationAction(ISD::CTPOP, MVT::v32i8, Custom);
1151 setOperationAction(ISD::CTPOP, MVT::v16i16, Custom);
1152 setOperationAction(ISD::CTPOP, MVT::v8i32, Custom);
1153 setOperationAction(ISD::CTPOP, MVT::v4i64, Custom);
1155 setOperationAction(ISD::CTTZ, MVT::v32i8, Custom);
1156 setOperationAction(ISD::CTTZ, MVT::v16i16, Custom);
1157 setOperationAction(ISD::CTTZ, MVT::v8i32, Custom);
1158 setOperationAction(ISD::CTTZ, MVT::v4i64, Custom);
1159 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v32i8, Custom);
1160 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i16, Custom);
1161 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i32, Custom);
1162 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i64, Custom);
1164 if (Subtarget->hasAnyFMA()) {
1165 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1166 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1167 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1168 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1169 setOperationAction(ISD::FMA, MVT::f32, Legal);
1170 setOperationAction(ISD::FMA, MVT::f64, Legal);
1173 if (Subtarget->hasInt256()) {
1174 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1175 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1176 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1177 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1179 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1180 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1181 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1182 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1184 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1185 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1186 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1187 setOperationAction(ISD::MUL, MVT::v32i8, Custom);
1189 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1190 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1191 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1192 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1194 setOperationAction(ISD::SMAX, MVT::v32i8, Legal);
1195 setOperationAction(ISD::SMAX, MVT::v16i16, Legal);
1196 setOperationAction(ISD::SMAX, MVT::v8i32, Legal);
1197 setOperationAction(ISD::UMAX, MVT::v32i8, Legal);
1198 setOperationAction(ISD::UMAX, MVT::v16i16, Legal);
1199 setOperationAction(ISD::UMAX, MVT::v8i32, Legal);
1200 setOperationAction(ISD::SMIN, MVT::v32i8, Legal);
1201 setOperationAction(ISD::SMIN, MVT::v16i16, Legal);
1202 setOperationAction(ISD::SMIN, MVT::v8i32, Legal);
1203 setOperationAction(ISD::UMIN, MVT::v32i8, Legal);
1204 setOperationAction(ISD::UMIN, MVT::v16i16, Legal);
1205 setOperationAction(ISD::UMIN, MVT::v8i32, Legal);
1207 // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1208 // when we have a 256bit-wide blend with immediate.
1209 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1211 // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1212 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1213 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1214 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1215 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1216 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1217 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1219 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1220 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1221 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1222 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1223 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1224 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1226 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1227 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1228 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1229 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1231 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1232 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1233 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1234 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1236 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1237 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1238 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1239 setOperationAction(ISD::MUL, MVT::v32i8, Custom);
1241 setOperationAction(ISD::SMAX, MVT::v32i8, Custom);
1242 setOperationAction(ISD::SMAX, MVT::v16i16, Custom);
1243 setOperationAction(ISD::SMAX, MVT::v8i32, Custom);
1244 setOperationAction(ISD::UMAX, MVT::v32i8, Custom);
1245 setOperationAction(ISD::UMAX, MVT::v16i16, Custom);
1246 setOperationAction(ISD::UMAX, MVT::v8i32, Custom);
1247 setOperationAction(ISD::SMIN, MVT::v32i8, Custom);
1248 setOperationAction(ISD::SMIN, MVT::v16i16, Custom);
1249 setOperationAction(ISD::SMIN, MVT::v8i32, Custom);
1250 setOperationAction(ISD::UMIN, MVT::v32i8, Custom);
1251 setOperationAction(ISD::UMIN, MVT::v16i16, Custom);
1252 setOperationAction(ISD::UMIN, MVT::v8i32, Custom);
1255 // In the customized shift lowering, the legal cases in AVX2 will be
1257 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1258 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1260 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1261 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1263 setOperationAction(ISD::SRA, MVT::v4i64, Custom);
1264 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1266 // Custom lower several nodes for 256-bit types.
1267 for (MVT VT : MVT::vector_valuetypes()) {
1268 if (VT.getScalarSizeInBits() >= 32) {
1269 setOperationAction(ISD::MLOAD, VT, Legal);
1270 setOperationAction(ISD::MSTORE, VT, Legal);
1272 // Extract subvector is special because the value type
1273 // (result) is 128-bit but the source is 256-bit wide.
1274 if (VT.is128BitVector()) {
1275 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1277 // Do not attempt to custom lower other non-256-bit vectors
1278 if (!VT.is256BitVector())
1281 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1282 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1283 setOperationAction(ISD::VSELECT, VT, Custom);
1284 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1285 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1286 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1287 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1288 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1291 if (Subtarget->hasInt256())
1292 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1294 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1295 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32 }) {
1296 setOperationAction(ISD::AND, VT, Promote);
1297 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1298 setOperationAction(ISD::OR, VT, Promote);
1299 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1300 setOperationAction(ISD::XOR, VT, Promote);
1301 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1302 setOperationAction(ISD::LOAD, VT, Promote);
1303 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1304 setOperationAction(ISD::SELECT, VT, Promote);
1305 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1309 if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1310 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1311 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1312 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1313 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1315 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1316 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1317 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1319 for (MVT VT : MVT::fp_vector_valuetypes())
1320 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1322 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1323 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1324 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1325 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1326 setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1327 setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1328 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64, MVT::v8i8, Legal);
1329 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64, MVT::v8i8, Legal);
1330 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64, MVT::v8i16, Legal);
1331 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64, MVT::v8i16, Legal);
1332 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64, MVT::v8i32, Legal);
1333 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64, MVT::v8i32, Legal);
1335 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1336 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1337 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
1338 setOperationAction(ISD::XOR, MVT::i1, Legal);
1339 setOperationAction(ISD::OR, MVT::i1, Legal);
1340 setOperationAction(ISD::AND, MVT::i1, Legal);
1341 setOperationAction(ISD::SUB, MVT::i1, Custom);
1342 setOperationAction(ISD::ADD, MVT::i1, Custom);
1343 setOperationAction(ISD::MUL, MVT::i1, Custom);
1344 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1345 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1346 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1347 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1348 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1350 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1351 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1352 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1353 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1354 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1355 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1356 setOperationAction(ISD::FABS, MVT::v16f32, Custom);
1358 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1359 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1360 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1361 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1362 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1363 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1364 setOperationAction(ISD::FABS, MVT::v8f64, Custom);
1365 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1366 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1368 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1369 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1370 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1371 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1372 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1373 setOperationAction(ISD::SINT_TO_FP, MVT::v8i1, Custom);
1374 setOperationAction(ISD::SINT_TO_FP, MVT::v16i1, Custom);
1375 setOperationAction(ISD::SINT_TO_FP, MVT::v16i8, Promote);
1376 setOperationAction(ISD::SINT_TO_FP, MVT::v16i16, Promote);
1377 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1378 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1379 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1380 setOperationAction(ISD::UINT_TO_FP, MVT::v16i8, Custom);
1381 setOperationAction(ISD::UINT_TO_FP, MVT::v16i16, Custom);
1382 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1383 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1385 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Legal);
1386 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Legal);
1387 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Legal);
1388 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Legal);
1389 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Legal);
1390 if (Subtarget->hasVLX()){
1391 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Legal);
1392 setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1393 setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1394 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Legal);
1395 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1397 setTruncStoreAction(MVT::v2i64, MVT::v2i8, Legal);
1398 setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1399 setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1400 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Legal);
1401 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1403 setOperationAction(ISD::MLOAD, MVT::v8i32, Custom);
1404 setOperationAction(ISD::MLOAD, MVT::v8f32, Custom);
1405 setOperationAction(ISD::MSTORE, MVT::v8i32, Custom);
1406 setOperationAction(ISD::MSTORE, MVT::v8f32, Custom);
1408 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1409 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1410 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1411 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i1, Custom);
1412 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i1, Custom);
1413 if (Subtarget->hasDQI()) {
1414 setOperationAction(ISD::TRUNCATE, MVT::v2i1, Custom);
1415 setOperationAction(ISD::TRUNCATE, MVT::v4i1, Custom);
1417 setOperationAction(ISD::SINT_TO_FP, MVT::v8i64, Legal);
1418 setOperationAction(ISD::UINT_TO_FP, MVT::v8i64, Legal);
1419 setOperationAction(ISD::FP_TO_SINT, MVT::v8i64, Legal);
1420 setOperationAction(ISD::FP_TO_UINT, MVT::v8i64, Legal);
1421 if (Subtarget->hasVLX()) {
1422 setOperationAction(ISD::SINT_TO_FP, MVT::v4i64, Legal);
1423 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
1424 setOperationAction(ISD::UINT_TO_FP, MVT::v4i64, Legal);
1425 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
1426 setOperationAction(ISD::FP_TO_SINT, MVT::v4i64, Legal);
1427 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
1428 setOperationAction(ISD::FP_TO_UINT, MVT::v4i64, Legal);
1429 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
1432 if (Subtarget->hasVLX()) {
1433 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1434 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1435 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1436 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1437 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1438 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1439 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1440 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1442 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1443 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1444 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1445 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1446 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1447 setOperationAction(ISD::ANY_EXTEND, MVT::v16i32, Custom);
1448 setOperationAction(ISD::ANY_EXTEND, MVT::v8i64, Custom);
1449 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1450 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1451 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1452 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1453 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1454 if (Subtarget->hasDQI()) {
1455 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Custom);
1456 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i64, Custom);
1458 setOperationAction(ISD::FFLOOR, MVT::v16f32, Legal);
1459 setOperationAction(ISD::FFLOOR, MVT::v8f64, Legal);
1460 setOperationAction(ISD::FCEIL, MVT::v16f32, Legal);
1461 setOperationAction(ISD::FCEIL, MVT::v8f64, Legal);
1462 setOperationAction(ISD::FTRUNC, MVT::v16f32, Legal);
1463 setOperationAction(ISD::FTRUNC, MVT::v8f64, Legal);
1464 setOperationAction(ISD::FRINT, MVT::v16f32, Legal);
1465 setOperationAction(ISD::FRINT, MVT::v8f64, Legal);
1466 setOperationAction(ISD::FNEARBYINT, MVT::v16f32, Legal);
1467 setOperationAction(ISD::FNEARBYINT, MVT::v8f64, Legal);
1469 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1470 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1471 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1472 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1473 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Custom);
1475 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1476 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1478 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1480 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1481 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1482 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v16i1, Custom);
1483 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1484 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1485 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1486 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1487 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1488 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1489 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1490 setOperationAction(ISD::SELECT, MVT::v16i1, Custom);
1491 setOperationAction(ISD::SELECT, MVT::v8i1, Custom);
1493 setOperationAction(ISD::SMAX, MVT::v16i32, Legal);
1494 setOperationAction(ISD::SMAX, MVT::v8i64, Legal);
1495 setOperationAction(ISD::UMAX, MVT::v16i32, Legal);
1496 setOperationAction(ISD::UMAX, MVT::v8i64, Legal);
1497 setOperationAction(ISD::SMIN, MVT::v16i32, Legal);
1498 setOperationAction(ISD::SMIN, MVT::v8i64, Legal);
1499 setOperationAction(ISD::UMIN, MVT::v16i32, Legal);
1500 setOperationAction(ISD::UMIN, MVT::v8i64, Legal);
1502 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1503 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1505 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1506 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1508 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1510 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1511 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1513 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1514 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1516 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1517 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1519 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1520 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1521 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1522 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1523 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1524 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1526 if (Subtarget->hasCDI()) {
1527 setOperationAction(ISD::CTLZ, MVT::v8i64, Legal);
1528 setOperationAction(ISD::CTLZ, MVT::v16i32, Legal);
1529 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v8i64, Expand);
1530 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v16i32, Expand);
1532 setOperationAction(ISD::CTLZ, MVT::v8i16, Custom);
1533 setOperationAction(ISD::CTLZ, MVT::v16i8, Custom);
1534 setOperationAction(ISD::CTLZ, MVT::v16i16, Custom);
1535 setOperationAction(ISD::CTLZ, MVT::v32i8, Custom);
1536 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v8i16, Expand);
1537 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v16i8, Expand);
1538 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v16i16, Expand);
1539 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v32i8, Expand);
1541 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i64, Custom);
1542 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i32, Custom);
1544 if (Subtarget->hasVLX()) {
1545 setOperationAction(ISD::CTLZ, MVT::v4i64, Legal);
1546 setOperationAction(ISD::CTLZ, MVT::v8i32, Legal);
1547 setOperationAction(ISD::CTLZ, MVT::v2i64, Legal);
1548 setOperationAction(ISD::CTLZ, MVT::v4i32, Legal);
1549 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v4i64, Expand);
1550 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v8i32, Expand);
1551 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v2i64, Expand);
1552 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v4i32, Expand);
1554 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i64, Custom);
1555 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i32, Custom);
1556 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
1557 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
1559 setOperationAction(ISD::CTLZ, MVT::v4i64, Custom);
1560 setOperationAction(ISD::CTLZ, MVT::v8i32, Custom);
1561 setOperationAction(ISD::CTLZ, MVT::v2i64, Custom);
1562 setOperationAction(ISD::CTLZ, MVT::v4i32, Custom);
1563 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v4i64, Expand);
1564 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v8i32, Expand);
1565 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v2i64, Expand);
1566 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v4i32, Expand);
1568 } // Subtarget->hasCDI()
1570 if (Subtarget->hasDQI()) {
1571 setOperationAction(ISD::MUL, MVT::v2i64, Legal);
1572 setOperationAction(ISD::MUL, MVT::v4i64, Legal);
1573 setOperationAction(ISD::MUL, MVT::v8i64, Legal);
1575 // Custom lower several nodes.
1576 for (MVT VT : MVT::vector_valuetypes()) {
1577 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1579 setOperationAction(ISD::AND, VT, Legal);
1580 setOperationAction(ISD::OR, VT, Legal);
1581 setOperationAction(ISD::XOR, VT, Legal);
1583 if ((VT.is128BitVector() || VT.is256BitVector()) && EltSize >= 32) {
1584 setOperationAction(ISD::MGATHER, VT, Custom);
1585 setOperationAction(ISD::MSCATTER, VT, Custom);
1587 // Extract subvector is special because the value type
1588 // (result) is 256/128-bit but the source is 512-bit wide.
1589 if (VT.is128BitVector() || VT.is256BitVector()) {
1590 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1592 if (VT.getVectorElementType() == MVT::i1)
1593 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1595 // Do not attempt to custom lower other non-512-bit vectors
1596 if (!VT.is512BitVector())
1599 if (EltSize >= 32) {
1600 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1601 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1602 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1603 setOperationAction(ISD::VSELECT, VT, Legal);
1604 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1605 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1606 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1607 setOperationAction(ISD::MLOAD, VT, Legal);
1608 setOperationAction(ISD::MSTORE, VT, Legal);
1609 setOperationAction(ISD::MGATHER, VT, Legal);
1610 setOperationAction(ISD::MSCATTER, VT, Custom);
1613 for (auto VT : { MVT::v64i8, MVT::v32i16, MVT::v16i32 }) {
1614 setOperationAction(ISD::SELECT, VT, Promote);
1615 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1619 if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1620 addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1621 addRegisterClass(MVT::v64i8, &X86::VR512RegClass);
1623 addRegisterClass(MVT::v32i1, &X86::VK32RegClass);
1624 addRegisterClass(MVT::v64i1, &X86::VK64RegClass);
1626 setOperationAction(ISD::LOAD, MVT::v32i16, Legal);
1627 setOperationAction(ISD::LOAD, MVT::v64i8, Legal);
1628 setOperationAction(ISD::SETCC, MVT::v32i1, Custom);
1629 setOperationAction(ISD::SETCC, MVT::v64i1, Custom);
1630 setOperationAction(ISD::ADD, MVT::v32i16, Legal);
1631 setOperationAction(ISD::ADD, MVT::v64i8, Legal);
1632 setOperationAction(ISD::SUB, MVT::v32i16, Legal);
1633 setOperationAction(ISD::SUB, MVT::v64i8, Legal);
1634 setOperationAction(ISD::MUL, MVT::v32i16, Legal);
1635 setOperationAction(ISD::MULHS, MVT::v32i16, Legal);
1636 setOperationAction(ISD::MULHU, MVT::v32i16, Legal);
1637 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i1, Custom);
1638 setOperationAction(ISD::CONCAT_VECTORS, MVT::v64i1, Custom);
1639 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i16, Custom);
1640 setOperationAction(ISD::CONCAT_VECTORS, MVT::v64i8, Custom);
1641 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v32i1, Custom);
1642 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v64i1, Custom);
1643 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v32i16, Custom);
1644 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v64i8, Custom);
1645 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v32i16, Custom);
1646 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v64i8, Custom);
1647 setOperationAction(ISD::SELECT, MVT::v32i1, Custom);
1648 setOperationAction(ISD::SELECT, MVT::v64i1, Custom);
1649 setOperationAction(ISD::SIGN_EXTEND, MVT::v32i8, Custom);
1650 setOperationAction(ISD::ZERO_EXTEND, MVT::v32i8, Custom);
1651 setOperationAction(ISD::SIGN_EXTEND, MVT::v32i16, Custom);
1652 setOperationAction(ISD::ZERO_EXTEND, MVT::v32i16, Custom);
1653 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v32i16, Custom);
1654 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v64i8, Custom);
1655 setOperationAction(ISD::SIGN_EXTEND, MVT::v64i8, Custom);
1656 setOperationAction(ISD::ZERO_EXTEND, MVT::v64i8, Custom);
1657 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v32i1, Custom);
1658 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v64i1, Custom);
1659 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v32i16, Custom);
1660 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v64i8, Custom);
1661 setOperationAction(ISD::VSELECT, MVT::v32i16, Legal);
1662 setOperationAction(ISD::VSELECT, MVT::v64i8, Legal);
1663 setOperationAction(ISD::TRUNCATE, MVT::v32i1, Custom);
1664 setOperationAction(ISD::TRUNCATE, MVT::v64i1, Custom);
1665 setOperationAction(ISD::TRUNCATE, MVT::v32i8, Custom);
1666 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v32i1, Custom);
1667 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v64i1, Custom);
1669 setOperationAction(ISD::SMAX, MVT::v64i8, Legal);
1670 setOperationAction(ISD::SMAX, MVT::v32i16, Legal);
1671 setOperationAction(ISD::UMAX, MVT::v64i8, Legal);
1672 setOperationAction(ISD::UMAX, MVT::v32i16, Legal);
1673 setOperationAction(ISD::SMIN, MVT::v64i8, Legal);
1674 setOperationAction(ISD::SMIN, MVT::v32i16, Legal);
1675 setOperationAction(ISD::UMIN, MVT::v64i8, Legal);
1676 setOperationAction(ISD::UMIN, MVT::v32i16, Legal);
1678 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Legal);
1679 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Legal);
1680 if (Subtarget->hasVLX())
1681 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Legal);
1683 if (Subtarget->hasCDI()) {
1684 setOperationAction(ISD::CTLZ, MVT::v32i16, Custom);
1685 setOperationAction(ISD::CTLZ, MVT::v64i8, Custom);
1686 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v32i16, Expand);
1687 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v64i8, Expand);
1690 for (auto VT : { MVT::v64i8, MVT::v32i16 }) {
1691 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1692 setOperationAction(ISD::VSELECT, VT, Legal);
1693 setOperationAction(ISD::SRL, VT, Custom);
1694 setOperationAction(ISD::SHL, VT, Custom);
1695 setOperationAction(ISD::SRA, VT, Custom);
1697 setOperationAction(ISD::AND, VT, Promote);
1698 AddPromotedToType (ISD::AND, VT, MVT::v8i64);
1699 setOperationAction(ISD::OR, VT, Promote);
1700 AddPromotedToType (ISD::OR, VT, MVT::v8i64);
1701 setOperationAction(ISD::XOR, VT, Promote);
1702 AddPromotedToType (ISD::XOR, VT, MVT::v8i64);
1706 if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1707 addRegisterClass(MVT::v4i1, &X86::VK4RegClass);
1708 addRegisterClass(MVT::v2i1, &X86::VK2RegClass);
1710 setOperationAction(ISD::SETCC, MVT::v4i1, Custom);
1711 setOperationAction(ISD::SETCC, MVT::v2i1, Custom);
1712 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i1, Custom);
1713 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1714 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i1, Custom);
1715 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i1, Custom);
1716 setOperationAction(ISD::SELECT, MVT::v4i1, Custom);
1717 setOperationAction(ISD::SELECT, MVT::v2i1, Custom);
1718 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
1719 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i1, Custom);
1720 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i1, Custom);
1721 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i1, Custom);
1723 setOperationAction(ISD::AND, MVT::v8i32, Legal);
1724 setOperationAction(ISD::OR, MVT::v8i32, Legal);
1725 setOperationAction(ISD::XOR, MVT::v8i32, Legal);
1726 setOperationAction(ISD::AND, MVT::v4i32, Legal);
1727 setOperationAction(ISD::OR, MVT::v4i32, Legal);
1728 setOperationAction(ISD::XOR, MVT::v4i32, Legal);
1729 setOperationAction(ISD::SRA, MVT::v2i64, Custom);
1730 setOperationAction(ISD::SRA, MVT::v4i64, Custom);
1732 setOperationAction(ISD::SMAX, MVT::v2i64, Legal);
1733 setOperationAction(ISD::SMAX, MVT::v4i64, Legal);
1734 setOperationAction(ISD::UMAX, MVT::v2i64, Legal);
1735 setOperationAction(ISD::UMAX, MVT::v4i64, Legal);
1736 setOperationAction(ISD::SMIN, MVT::v2i64, Legal);
1737 setOperationAction(ISD::SMIN, MVT::v4i64, Legal);
1738 setOperationAction(ISD::UMIN, MVT::v2i64, Legal);
1739 setOperationAction(ISD::UMIN, MVT::v4i64, Legal);
1742 // We want to custom lower some of our intrinsics.
1743 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1744 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1745 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1746 if (!Subtarget->is64Bit()) {
1747 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1748 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
1751 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1752 // handle type legalization for these operations here.
1754 // FIXME: We really should do custom legalization for addition and
1755 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1756 // than generic legalization for 64-bit multiplication-with-overflow, though.
1757 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
1758 if (VT == MVT::i64 && !Subtarget->is64Bit())
1760 // Add/Sub/Mul with overflow operations are custom lowered.
1761 setOperationAction(ISD::SADDO, VT, Custom);
1762 setOperationAction(ISD::UADDO, VT, Custom);
1763 setOperationAction(ISD::SSUBO, VT, Custom);
1764 setOperationAction(ISD::USUBO, VT, Custom);
1765 setOperationAction(ISD::SMULO, VT, Custom);
1766 setOperationAction(ISD::UMULO, VT, Custom);
1769 if (!Subtarget->is64Bit()) {
1770 // These libcalls are not available in 32-bit.
1771 setLibcallName(RTLIB::SHL_I128, nullptr);
1772 setLibcallName(RTLIB::SRL_I128, nullptr);
1773 setLibcallName(RTLIB::SRA_I128, nullptr);
1776 // Combine sin / cos into one node or libcall if possible.
1777 if (Subtarget->hasSinCos()) {
1778 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1779 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1780 if (Subtarget->isTargetDarwin()) {
1781 // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1782 // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1783 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1784 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1788 if (Subtarget->isTargetWin64()) {
1789 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1790 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1791 setOperationAction(ISD::SREM, MVT::i128, Custom);
1792 setOperationAction(ISD::UREM, MVT::i128, Custom);
1793 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1794 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1797 // We have target-specific dag combine patterns for the following nodes:
1798 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1799 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1800 setTargetDAGCombine(ISD::BITCAST);
1801 setTargetDAGCombine(ISD::VSELECT);
1802 setTargetDAGCombine(ISD::SELECT);
1803 setTargetDAGCombine(ISD::SHL);
1804 setTargetDAGCombine(ISD::SRA);
1805 setTargetDAGCombine(ISD::SRL);
1806 setTargetDAGCombine(ISD::OR);
1807 setTargetDAGCombine(ISD::AND);
1808 setTargetDAGCombine(ISD::ADD);
1809 setTargetDAGCombine(ISD::FADD);
1810 setTargetDAGCombine(ISD::FSUB);
1811 setTargetDAGCombine(ISD::FNEG);
1812 setTargetDAGCombine(ISD::FMA);
1813 setTargetDAGCombine(ISD::FMINNUM);
1814 setTargetDAGCombine(ISD::FMAXNUM);
1815 setTargetDAGCombine(ISD::SUB);
1816 setTargetDAGCombine(ISD::LOAD);
1817 setTargetDAGCombine(ISD::MLOAD);
1818 setTargetDAGCombine(ISD::STORE);
1819 setTargetDAGCombine(ISD::MSTORE);
1820 setTargetDAGCombine(ISD::TRUNCATE);
1821 setTargetDAGCombine(ISD::ZERO_EXTEND);
1822 setTargetDAGCombine(ISD::ANY_EXTEND);
1823 setTargetDAGCombine(ISD::SIGN_EXTEND);
1824 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1825 setTargetDAGCombine(ISD::SINT_TO_FP);
1826 setTargetDAGCombine(ISD::UINT_TO_FP);
1827 setTargetDAGCombine(ISD::SETCC);
1828 setTargetDAGCombine(ISD::BUILD_VECTOR);
1829 setTargetDAGCombine(ISD::MUL);
1830 setTargetDAGCombine(ISD::XOR);
1831 setTargetDAGCombine(ISD::MSCATTER);
1832 setTargetDAGCombine(ISD::MGATHER);
1834 computeRegisterProperties(Subtarget->getRegisterInfo());
1836 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1837 MaxStoresPerMemsetOptSize = 8;
1838 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1839 MaxStoresPerMemcpyOptSize = 4;
1840 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1841 MaxStoresPerMemmoveOptSize = 4;
1842 setPrefLoopAlignment(4); // 2^4 bytes.
1844 // A predictable cmov does not hurt on an in-order CPU.
1845 // FIXME: Use a CPU attribute to trigger this, not a CPU model.
1846 PredictableSelectIsExpensive = !Subtarget->isAtom();
1847 EnableExtLdPromotion = true;
1848 setPrefFunctionAlignment(4); // 2^4 bytes.
1850 verifyIntrinsicTables();
1853 // This has so far only been implemented for 64-bit MachO.
1854 bool X86TargetLowering::useLoadStackGuardNode() const {
1855 return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1858 TargetLoweringBase::LegalizeTypeAction
1859 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1860 if (ExperimentalVectorWideningLegalization &&
1861 VT.getVectorNumElements() != 1 &&
1862 VT.getVectorElementType().getSimpleVT() != MVT::i1)
1863 return TypeWidenVector;
1865 return TargetLoweringBase::getPreferredVectorAction(VT);
1868 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1871 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1873 if (VT.isSimple()) {
1874 MVT VVT = VT.getSimpleVT();
1875 const unsigned NumElts = VVT.getVectorNumElements();
1876 const MVT EltVT = VVT.getVectorElementType();
1877 if (VVT.is512BitVector()) {
1878 if (Subtarget->hasAVX512())
1879 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1880 EltVT == MVT::f32 || EltVT == MVT::f64)
1882 case 8: return MVT::v8i1;
1883 case 16: return MVT::v16i1;
1885 if (Subtarget->hasBWI())
1886 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1888 case 32: return MVT::v32i1;
1889 case 64: return MVT::v64i1;
1893 if (VVT.is256BitVector() || VVT.is128BitVector()) {
1894 if (Subtarget->hasVLX())
1895 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1896 EltVT == MVT::f32 || EltVT == MVT::f64)
1898 case 2: return MVT::v2i1;
1899 case 4: return MVT::v4i1;
1900 case 8: return MVT::v8i1;
1902 if (Subtarget->hasBWI() && Subtarget->hasVLX())
1903 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1905 case 8: return MVT::v8i1;
1906 case 16: return MVT::v16i1;
1907 case 32: return MVT::v32i1;
1912 return VT.changeVectorElementTypeToInteger();
1915 /// Helper for getByValTypeAlignment to determine
1916 /// the desired ByVal argument alignment.
1917 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1920 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1921 if (VTy->getBitWidth() == 128)
1923 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1924 unsigned EltAlign = 0;
1925 getMaxByValAlign(ATy->getElementType(), EltAlign);
1926 if (EltAlign > MaxAlign)
1927 MaxAlign = EltAlign;
1928 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1929 for (auto *EltTy : STy->elements()) {
1930 unsigned EltAlign = 0;
1931 getMaxByValAlign(EltTy, EltAlign);
1932 if (EltAlign > MaxAlign)
1933 MaxAlign = EltAlign;
1940 /// Return the desired alignment for ByVal aggregate
1941 /// function arguments in the caller parameter area. For X86, aggregates
1942 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1943 /// are at 4-byte boundaries.
1944 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1945 const DataLayout &DL) const {
1946 if (Subtarget->is64Bit()) {
1947 // Max of 8 and alignment of type.
1948 unsigned TyAlign = DL.getABITypeAlignment(Ty);
1955 if (Subtarget->hasSSE1())
1956 getMaxByValAlign(Ty, Align);
1960 /// Returns the target specific optimal type for load
1961 /// and store operations as a result of memset, memcpy, and memmove
1962 /// lowering. If DstAlign is zero that means it's safe to destination
1963 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1964 /// means there isn't a need to check it against alignment requirement,
1965 /// probably because the source does not need to be loaded. If 'IsMemset' is
1966 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1967 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1968 /// source is constant so it does not need to be loaded.
1969 /// It returns EVT::Other if the type should be determined using generic
1970 /// target-independent logic.
1972 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1973 unsigned DstAlign, unsigned SrcAlign,
1974 bool IsMemset, bool ZeroMemset,
1976 MachineFunction &MF) const {
1977 const Function *F = MF.getFunction();
1978 if ((!IsMemset || ZeroMemset) &&
1979 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1981 (!Subtarget->isUnalignedMem16Slow() ||
1982 ((DstAlign == 0 || DstAlign >= 16) &&
1983 (SrcAlign == 0 || SrcAlign >= 16)))) {
1985 // FIXME: Check if unaligned 32-byte accesses are slow.
1986 if (Subtarget->hasInt256())
1988 if (Subtarget->hasFp256())
1991 if (Subtarget->hasSSE2())
1993 if (Subtarget->hasSSE1())
1995 } else if (!MemcpyStrSrc && Size >= 8 &&
1996 !Subtarget->is64Bit() &&
1997 Subtarget->hasSSE2()) {
1998 // Do not use f64 to lower memcpy if source is string constant. It's
1999 // better to use i32 to avoid the loads.
2003 // This is a compromise. If we reach here, unaligned accesses may be slow on
2004 // this target. However, creating smaller, aligned accesses could be even
2005 // slower and would certainly be a lot more code.
2006 if (Subtarget->is64Bit() && Size >= 8)
2011 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
2013 return X86ScalarSSEf32;
2014 else if (VT == MVT::f64)
2015 return X86ScalarSSEf64;
2020 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
2025 switch (VT.getSizeInBits()) {
2027 // 8-byte and under are always assumed to be fast.
2031 *Fast = !Subtarget->isUnalignedMem16Slow();
2034 *Fast = !Subtarget->isUnalignedMem32Slow();
2036 // TODO: What about AVX-512 (512-bit) accesses?
2039 // Misaligned accesses of any size are always allowed.
2043 /// Return the entry encoding for a jump table in the
2044 /// current function. The returned value is a member of the
2045 /// MachineJumpTableInfo::JTEntryKind enum.
2046 unsigned X86TargetLowering::getJumpTableEncoding() const {
2047 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
2049 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2050 Subtarget->isPICStyleGOT())
2051 return MachineJumpTableInfo::EK_Custom32;
2053 // Otherwise, use the normal jump table encoding heuristics.
2054 return TargetLowering::getJumpTableEncoding();
2057 bool X86TargetLowering::useSoftFloat() const {
2058 return Subtarget->useSoftFloat();
2062 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
2063 const MachineBasicBlock *MBB,
2064 unsigned uid,MCContext &Ctx) const{
2065 assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
2066 Subtarget->isPICStyleGOT());
2067 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
2069 return MCSymbolRefExpr::create(MBB->getSymbol(),
2070 MCSymbolRefExpr::VK_GOTOFF, Ctx);
2073 /// Returns relocation base for the given PIC jumptable.
2074 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
2075 SelectionDAG &DAG) const {
2076 if (!Subtarget->is64Bit())
2077 // This doesn't have SDLoc associated with it, but is not really the
2078 // same as a Register.
2079 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
2080 getPointerTy(DAG.getDataLayout()));
2084 /// This returns the relocation base for the given PIC jumptable,
2085 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
2086 const MCExpr *X86TargetLowering::
2087 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
2088 MCContext &Ctx) const {
2089 // X86-64 uses RIP relative addressing based on the jump table label.
2090 if (Subtarget->isPICStyleRIPRel())
2091 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2093 // Otherwise, the reference is relative to the PIC base.
2094 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2097 std::pair<const TargetRegisterClass *, uint8_t>
2098 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
2100 const TargetRegisterClass *RRC = nullptr;
2102 switch (VT.SimpleTy) {
2104 return TargetLowering::findRepresentativeClass(TRI, VT);
2105 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
2106 RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
2109 RRC = &X86::VR64RegClass;
2111 case MVT::f32: case MVT::f64:
2112 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
2113 case MVT::v4f32: case MVT::v2f64:
2114 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
2116 RRC = &X86::VR128RegClass;
2119 return std::make_pair(RRC, Cost);
2122 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
2123 unsigned &Offset) const {
2124 if (!Subtarget->isTargetLinux())
2127 if (Subtarget->is64Bit()) {
2128 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
2130 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2142 Value *X86TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
2143 if (!Subtarget->isTargetAndroid())
2144 return TargetLowering::getSafeStackPointerLocation(IRB);
2146 // Android provides a fixed TLS slot for the SafeStack pointer. See the
2147 // definition of TLS_SLOT_SAFESTACK in
2148 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
2149 unsigned AddressSpace, Offset;
2150 if (Subtarget->is64Bit()) {
2151 // %fs:0x48, unless we're using a Kernel code model, in which case it's %gs:
2153 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2163 return ConstantExpr::getIntToPtr(
2164 ConstantInt::get(Type::getInt32Ty(IRB.getContext()), Offset),
2165 Type::getInt8PtrTy(IRB.getContext())->getPointerTo(AddressSpace));
2168 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2169 unsigned DestAS) const {
2170 assert(SrcAS != DestAS && "Expected different address spaces!");
2172 return SrcAS < 256 && DestAS < 256;
2175 //===----------------------------------------------------------------------===//
2176 // Return Value Calling Convention Implementation
2177 //===----------------------------------------------------------------------===//
2179 #include "X86GenCallingConv.inc"
2181 bool X86TargetLowering::CanLowerReturn(
2182 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2183 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2184 SmallVector<CCValAssign, 16> RVLocs;
2185 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2186 return CCInfo.CheckReturn(Outs, RetCC_X86);
2189 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2190 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2195 X86TargetLowering::LowerReturn(SDValue Chain,
2196 CallingConv::ID CallConv, bool isVarArg,
2197 const SmallVectorImpl<ISD::OutputArg> &Outs,
2198 const SmallVectorImpl<SDValue> &OutVals,
2199 SDLoc dl, SelectionDAG &DAG) const {
2200 MachineFunction &MF = DAG.getMachineFunction();
2201 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2203 if (CallConv == CallingConv::X86_INTR && !Outs.empty())
2204 report_fatal_error("X86 interrupts may not return any value");
2206 SmallVector<CCValAssign, 16> RVLocs;
2207 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2208 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2211 SmallVector<SDValue, 6> RetOps;
2212 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2213 // Operand #1 = Bytes To Pop
2214 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2217 // Copy the result values into the output registers.
2218 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2219 CCValAssign &VA = RVLocs[i];
2220 assert(VA.isRegLoc() && "Can only return in registers!");
2221 SDValue ValToCopy = OutVals[i];
2222 EVT ValVT = ValToCopy.getValueType();
2224 // Promote values to the appropriate types.
2225 if (VA.getLocInfo() == CCValAssign::SExt)
2226 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2227 else if (VA.getLocInfo() == CCValAssign::ZExt)
2228 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2229 else if (VA.getLocInfo() == CCValAssign::AExt) {
2230 if (ValVT.isVector() && ValVT.getVectorElementType() == MVT::i1)
2231 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2233 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2235 else if (VA.getLocInfo() == CCValAssign::BCvt)
2236 ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2238 assert(VA.getLocInfo() != CCValAssign::FPExt &&
2239 "Unexpected FP-extend for return value.");
2241 // If this is x86-64, and we disabled SSE, we can't return FP values,
2242 // or SSE or MMX vectors.
2243 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2244 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2245 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2246 report_fatal_error("SSE register return with SSE disabled");
2248 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
2249 // llvm-gcc has never done it right and no one has noticed, so this
2250 // should be OK for now.
2251 if (ValVT == MVT::f64 &&
2252 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2253 report_fatal_error("SSE2 register return with SSE2 disabled");
2255 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2256 // the RET instruction and handled by the FP Stackifier.
2257 if (VA.getLocReg() == X86::FP0 ||
2258 VA.getLocReg() == X86::FP1) {
2259 // If this is a copy from an xmm register to ST(0), use an FPExtend to
2260 // change the value to the FP stack register class.
2261 if (isScalarFPTypeInSSEReg(VA.getValVT()))
2262 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2263 RetOps.push_back(ValToCopy);
2264 // Don't emit a copytoreg.
2268 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2269 // which is returned in RAX / RDX.
2270 if (Subtarget->is64Bit()) {
2271 if (ValVT == MVT::x86mmx) {
2272 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2273 ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2274 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2276 // If we don't have SSE2 available, convert to v4f32 so the generated
2277 // register is legal.
2278 if (!Subtarget->hasSSE2())
2279 ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2284 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2285 Flag = Chain.getValue(1);
2286 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2289 // All x86 ABIs require that for returning structs by value we copy
2290 // the sret argument into %rax/%eax (depending on ABI) for the return.
2291 // We saved the argument into a virtual register in the entry block,
2292 // so now we copy the value out and into %rax/%eax.
2294 // Checking Function.hasStructRetAttr() here is insufficient because the IR
2295 // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2296 // false, then an sret argument may be implicitly inserted in the SelDAG. In
2297 // either case FuncInfo->setSRetReturnReg() will have been called.
2298 if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2299 SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2300 getPointerTy(MF.getDataLayout()));
2303 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2304 X86::RAX : X86::EAX;
2305 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2306 Flag = Chain.getValue(1);
2308 // RAX/EAX now acts like a return value.
2310 DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2313 RetOps[0] = Chain; // Update chain.
2315 // Add the flag if we have it.
2317 RetOps.push_back(Flag);
2319 X86ISD::NodeType opcode = X86ISD::RET_FLAG;
2320 if (CallConv == CallingConv::X86_INTR)
2321 opcode = X86ISD::IRET;
2322 return DAG.getNode(opcode, dl, MVT::Other, RetOps);
2325 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2326 if (N->getNumValues() != 1)
2328 if (!N->hasNUsesOfValue(1, 0))
2331 SDValue TCChain = Chain;
2332 SDNode *Copy = *N->use_begin();
2333 if (Copy->getOpcode() == ISD::CopyToReg) {
2334 // If the copy has a glue operand, we conservatively assume it isn't safe to
2335 // perform a tail call.
2336 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2338 TCChain = Copy->getOperand(0);
2339 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2342 bool HasRet = false;
2343 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2345 if (UI->getOpcode() != X86ISD::RET_FLAG)
2347 // If we are returning more than one value, we can definitely
2348 // not make a tail call see PR19530
2349 if (UI->getNumOperands() > 4)
2351 if (UI->getNumOperands() == 4 &&
2352 UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2365 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2366 ISD::NodeType ExtendKind) const {
2368 // TODO: Is this also valid on 32-bit?
2369 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2370 ReturnMVT = MVT::i8;
2372 ReturnMVT = MVT::i32;
2374 EVT MinVT = getRegisterType(Context, ReturnMVT);
2375 return VT.bitsLT(MinVT) ? MinVT : VT;
2378 /// Lower the result values of a call into the
2379 /// appropriate copies out of appropriate physical registers.
2382 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2383 CallingConv::ID CallConv, bool isVarArg,
2384 const SmallVectorImpl<ISD::InputArg> &Ins,
2385 SDLoc dl, SelectionDAG &DAG,
2386 SmallVectorImpl<SDValue> &InVals) const {
2388 // Assign locations to each value returned by this call.
2389 SmallVector<CCValAssign, 16> RVLocs;
2390 bool Is64Bit = Subtarget->is64Bit();
2391 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2393 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2395 // Copy all of the result registers out of their specified physreg.
2396 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2397 CCValAssign &VA = RVLocs[i];
2398 EVT CopyVT = VA.getLocVT();
2400 // If this is x86-64, and we disabled SSE, we can't return FP values
2401 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64 || CopyVT == MVT::f128) &&
2402 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2403 report_fatal_error("SSE register return with SSE disabled");
2406 // If we prefer to use the value in xmm registers, copy it out as f80 and
2407 // use a truncate to move it from fp stack reg to xmm reg.
2408 bool RoundAfterCopy = false;
2409 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2410 isScalarFPTypeInSSEReg(VA.getValVT())) {
2412 RoundAfterCopy = (CopyVT != VA.getLocVT());
2415 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2416 CopyVT, InFlag).getValue(1);
2417 SDValue Val = Chain.getValue(0);
2420 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2421 // This truncation won't change the value.
2422 DAG.getIntPtrConstant(1, dl));
2424 if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2425 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2427 InFlag = Chain.getValue(2);
2428 InVals.push_back(Val);
2434 //===----------------------------------------------------------------------===//
2435 // C & StdCall & Fast Calling Convention implementation
2436 //===----------------------------------------------------------------------===//
2437 // StdCall calling convention seems to be standard for many Windows' API
2438 // routines and around. It differs from C calling convention just a little:
2439 // callee should clean up the stack, not caller. Symbols should be also
2440 // decorated in some fancy way :) It doesn't support any vector arguments.
2441 // For info on fast calling convention see Fast Calling Convention (tail call)
2442 // implementation LowerX86_32FastCCCallTo.
2444 /// CallIsStructReturn - Determines whether a call uses struct return
2446 enum StructReturnType {
2451 static StructReturnType
2452 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsMCU) {
2454 return NotStructReturn;
2456 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2457 if (!Flags.isSRet())
2458 return NotStructReturn;
2459 if (Flags.isInReg() || IsMCU)
2460 return RegStructReturn;
2461 return StackStructReturn;
2464 /// Determines whether a function uses struct return semantics.
2465 static StructReturnType
2466 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins, bool IsMCU) {
2468 return NotStructReturn;
2470 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2471 if (!Flags.isSRet())
2472 return NotStructReturn;
2473 if (Flags.isInReg() || IsMCU)
2474 return RegStructReturn;
2475 return StackStructReturn;
2478 /// Make a copy of an aggregate at address specified by "Src" to address
2479 /// "Dst" with size and alignment information specified by the specific
2480 /// parameter attribute. The copy will be passed as a byval function parameter.
2482 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2483 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2485 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2487 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2488 /*isVolatile*/false, /*AlwaysInline=*/true,
2489 /*isTailCall*/false,
2490 MachinePointerInfo(), MachinePointerInfo());
2493 /// Return true if the calling convention is one that we can guarantee TCO for.
2494 static bool canGuaranteeTCO(CallingConv::ID CC) {
2495 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2496 CC == CallingConv::HiPE || CC == CallingConv::HHVM);
2499 /// Return true if we might ever do TCO for calls with this calling convention.
2500 static bool mayTailCallThisCC(CallingConv::ID CC) {
2502 // C calling conventions:
2503 case CallingConv::C:
2504 case CallingConv::X86_64_Win64:
2505 case CallingConv::X86_64_SysV:
2506 // Callee pop conventions:
2507 case CallingConv::X86_ThisCall:
2508 case CallingConv::X86_StdCall:
2509 case CallingConv::X86_VectorCall:
2510 case CallingConv::X86_FastCall:
2513 return canGuaranteeTCO(CC);
2517 /// Return true if the function is being made into a tailcall target by
2518 /// changing its ABI.
2519 static bool shouldGuaranteeTCO(CallingConv::ID CC, bool GuaranteedTailCallOpt) {
2520 return GuaranteedTailCallOpt && canGuaranteeTCO(CC);
2523 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2525 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2526 if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2530 CallingConv::ID CalleeCC = CS.getCallingConv();
2531 if (!mayTailCallThisCC(CalleeCC))
2538 X86TargetLowering::LowerMemArgument(SDValue Chain,
2539 CallingConv::ID CallConv,
2540 const SmallVectorImpl<ISD::InputArg> &Ins,
2541 SDLoc dl, SelectionDAG &DAG,
2542 const CCValAssign &VA,
2543 MachineFrameInfo *MFI,
2545 // Create the nodes corresponding to a load from this parameter slot.
2546 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2547 bool AlwaysUseMutable = shouldGuaranteeTCO(
2548 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2549 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2552 // If value is passed by pointer we have address passed instead of the value
2554 bool ExtendedInMem = VA.isExtInLoc() &&
2555 VA.getValVT().getScalarType() == MVT::i1;
2557 if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2558 ValVT = VA.getLocVT();
2560 ValVT = VA.getValVT();
2562 // Calculate SP offset of interrupt parameter, re-arrange the slot normally
2563 // taken by a return address.
2565 if (CallConv == CallingConv::X86_INTR) {
2566 const X86Subtarget& Subtarget =
2567 static_cast<const X86Subtarget&>(DAG.getSubtarget());
2568 // X86 interrupts may take one or two arguments.
2569 // On the stack there will be no return address as in regular call.
2570 // Offset of last argument need to be set to -4/-8 bytes.
2571 // Where offset of the first argument out of two, should be set to 0 bytes.
2572 Offset = (Subtarget.is64Bit() ? 8 : 4) * ((i + 1) % Ins.size() - 1);
2575 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2576 // changed with more analysis.
2577 // In case of tail call optimization mark all arguments mutable. Since they
2578 // could be overwritten by lowering of arguments in case of a tail call.
2579 if (Flags.isByVal()) {
2580 unsigned Bytes = Flags.getByValSize();
2581 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2582 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2583 // Adjust SP offset of interrupt parameter.
2584 if (CallConv == CallingConv::X86_INTR) {
2585 MFI->setObjectOffset(FI, Offset);
2587 return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2589 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2590 VA.getLocMemOffset(), isImmutable);
2591 // Adjust SP offset of interrupt parameter.
2592 if (CallConv == CallingConv::X86_INTR) {
2593 MFI->setObjectOffset(FI, Offset);
2596 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2597 SDValue Val = DAG.getLoad(
2598 ValVT, dl, Chain, FIN,
2599 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2601 return ExtendedInMem ?
2602 DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2606 // FIXME: Get this from tablegen.
2607 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2608 const X86Subtarget *Subtarget) {
2609 assert(Subtarget->is64Bit());
2611 if (Subtarget->isCallingConvWin64(CallConv)) {
2612 static const MCPhysReg GPR64ArgRegsWin64[] = {
2613 X86::RCX, X86::RDX, X86::R8, X86::R9
2615 return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2618 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2619 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2621 return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2624 // FIXME: Get this from tablegen.
2625 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2626 CallingConv::ID CallConv,
2627 const X86Subtarget *Subtarget) {
2628 assert(Subtarget->is64Bit());
2629 if (Subtarget->isCallingConvWin64(CallConv)) {
2630 // The XMM registers which might contain var arg parameters are shadowed
2631 // in their paired GPR. So we only need to save the GPR to their home
2633 // TODO: __vectorcall will change this.
2637 const Function *Fn = MF.getFunction();
2638 bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2639 bool isSoftFloat = Subtarget->useSoftFloat();
2640 assert(!(isSoftFloat && NoImplicitFloatOps) &&
2641 "SSE register cannot be used when SSE is disabled!");
2642 if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2643 // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2647 static const MCPhysReg XMMArgRegs64Bit[] = {
2648 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2649 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2651 return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2654 SDValue X86TargetLowering::LowerFormalArguments(
2655 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2656 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc dl, SelectionDAG &DAG,
2657 SmallVectorImpl<SDValue> &InVals) const {
2658 MachineFunction &MF = DAG.getMachineFunction();
2659 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2660 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2662 const Function* Fn = MF.getFunction();
2663 if (Fn->hasExternalLinkage() &&
2664 Subtarget->isTargetCygMing() &&
2665 Fn->getName() == "main")
2666 FuncInfo->setForceFramePointer(true);
2668 MachineFrameInfo *MFI = MF.getFrameInfo();
2669 bool Is64Bit = Subtarget->is64Bit();
2670 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2672 assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
2673 "Var args not supported with calling convention fastcc, ghc or hipe");
2675 if (CallConv == CallingConv::X86_INTR) {
2676 bool isLegal = Ins.size() == 1 ||
2677 (Ins.size() == 2 && ((Is64Bit && Ins[1].VT == MVT::i64) ||
2678 (!Is64Bit && Ins[1].VT == MVT::i32)));
2680 report_fatal_error("X86 interrupts may take one or two arguments");
2683 // Assign locations to all of the incoming arguments.
2684 SmallVector<CCValAssign, 16> ArgLocs;
2685 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2687 // Allocate shadow area for Win64
2689 CCInfo.AllocateStack(32, 8);
2691 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2693 unsigned LastVal = ~0U;
2695 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2696 CCValAssign &VA = ArgLocs[i];
2697 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2699 assert(VA.getValNo() != LastVal &&
2700 "Don't support value assigned to multiple locs yet");
2702 LastVal = VA.getValNo();
2704 if (VA.isRegLoc()) {
2705 EVT RegVT = VA.getLocVT();
2706 const TargetRegisterClass *RC;
2707 if (RegVT == MVT::i32)
2708 RC = &X86::GR32RegClass;
2709 else if (Is64Bit && RegVT == MVT::i64)
2710 RC = &X86::GR64RegClass;
2711 else if (RegVT == MVT::f32)
2712 RC = &X86::FR32RegClass;
2713 else if (RegVT == MVT::f64)
2714 RC = &X86::FR64RegClass;
2715 else if (RegVT == MVT::f128)
2716 RC = &X86::FR128RegClass;
2717 else if (RegVT.is512BitVector())
2718 RC = &X86::VR512RegClass;
2719 else if (RegVT.is256BitVector())
2720 RC = &X86::VR256RegClass;
2721 else if (RegVT.is128BitVector())
2722 RC = &X86::VR128RegClass;
2723 else if (RegVT == MVT::x86mmx)
2724 RC = &X86::VR64RegClass;
2725 else if (RegVT == MVT::i1)
2726 RC = &X86::VK1RegClass;
2727 else if (RegVT == MVT::v8i1)
2728 RC = &X86::VK8RegClass;
2729 else if (RegVT == MVT::v16i1)
2730 RC = &X86::VK16RegClass;
2731 else if (RegVT == MVT::v32i1)
2732 RC = &X86::VK32RegClass;
2733 else if (RegVT == MVT::v64i1)
2734 RC = &X86::VK64RegClass;
2736 llvm_unreachable("Unknown argument type!");
2738 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2739 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2741 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2742 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2744 if (VA.getLocInfo() == CCValAssign::SExt)
2745 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2746 DAG.getValueType(VA.getValVT()));
2747 else if (VA.getLocInfo() == CCValAssign::ZExt)
2748 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2749 DAG.getValueType(VA.getValVT()));
2750 else if (VA.getLocInfo() == CCValAssign::BCvt)
2751 ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2753 if (VA.isExtInLoc()) {
2754 // Handle MMX values passed in XMM regs.
2755 if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2756 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2758 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2761 assert(VA.isMemLoc());
2762 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2765 // If value is passed via pointer - do a load.
2766 if (VA.getLocInfo() == CCValAssign::Indirect)
2767 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2768 MachinePointerInfo(), false, false, false, 0);
2770 InVals.push_back(ArgValue);
2773 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2774 // All x86 ABIs require that for returning structs by value we copy the
2775 // sret argument into %rax/%eax (depending on ABI) for the return. Save
2776 // the argument into a virtual register so that we can access it from the
2778 if (Ins[i].Flags.isSRet()) {
2779 unsigned Reg = FuncInfo->getSRetReturnReg();
2781 MVT PtrTy = getPointerTy(DAG.getDataLayout());
2782 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2783 FuncInfo->setSRetReturnReg(Reg);
2785 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2786 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2791 unsigned StackSize = CCInfo.getNextStackOffset();
2792 // Align stack specially for tail calls.
2793 if (shouldGuaranteeTCO(CallConv,
2794 MF.getTarget().Options.GuaranteedTailCallOpt))
2795 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2797 // If the function takes variable number of arguments, make a frame index for
2798 // the start of the first vararg value... for expansion of llvm.va_start. We
2799 // can skip this if there are no va_start calls.
2800 if (MFI->hasVAStart() &&
2801 (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2802 CallConv != CallingConv::X86_ThisCall))) {
2803 FuncInfo->setVarArgsFrameIndex(
2804 MFI->CreateFixedObject(1, StackSize, true));
2807 // Figure out if XMM registers are in use.
2808 assert(!(Subtarget->useSoftFloat() &&
2809 Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2810 "SSE register cannot be used when SSE is disabled!");
2812 // 64-bit calling conventions support varargs and register parameters, so we
2813 // have to do extra work to spill them in the prologue.
2814 if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2815 // Find the first unallocated argument registers.
2816 ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2817 ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2818 unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2819 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2820 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2821 "SSE register cannot be used when SSE is disabled!");
2823 // Gather all the live in physical registers.
2824 SmallVector<SDValue, 6> LiveGPRs;
2825 SmallVector<SDValue, 8> LiveXMMRegs;
2827 for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2828 unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2830 DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2832 if (!ArgXMMs.empty()) {
2833 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2834 ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2835 for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2836 unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2837 LiveXMMRegs.push_back(
2838 DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2843 // Get to the caller-allocated home save location. Add 8 to account
2844 // for the return address.
2845 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2846 FuncInfo->setRegSaveFrameIndex(
2847 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2848 // Fixup to set vararg frame on shadow area (4 x i64).
2850 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2852 // For X86-64, if there are vararg parameters that are passed via
2853 // registers, then we must store them to their spots on the stack so
2854 // they may be loaded by deferencing the result of va_next.
2855 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2856 FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2857 FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2858 ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2861 // Store the integer parameter registers.
2862 SmallVector<SDValue, 8> MemOps;
2863 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2864 getPointerTy(DAG.getDataLayout()));
2865 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2866 for (SDValue Val : LiveGPRs) {
2867 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2868 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2870 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2871 MachinePointerInfo::getFixedStack(
2872 DAG.getMachineFunction(),
2873 FuncInfo->getRegSaveFrameIndex(), Offset),
2875 MemOps.push_back(Store);
2879 if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2880 // Now store the XMM (fp + vector) parameter registers.
2881 SmallVector<SDValue, 12> SaveXMMOps;
2882 SaveXMMOps.push_back(Chain);
2883 SaveXMMOps.push_back(ALVal);
2884 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2885 FuncInfo->getRegSaveFrameIndex(), dl));
2886 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2887 FuncInfo->getVarArgsFPOffset(), dl));
2888 SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2890 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2891 MVT::Other, SaveXMMOps));
2894 if (!MemOps.empty())
2895 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2898 if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2899 // Find the largest legal vector type.
2900 MVT VecVT = MVT::Other;
2901 // FIXME: Only some x86_32 calling conventions support AVX512.
2902 if (Subtarget->hasAVX512() &&
2903 (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2904 CallConv == CallingConv::Intel_OCL_BI)))
2905 VecVT = MVT::v16f32;
2906 else if (Subtarget->hasAVX())
2908 else if (Subtarget->hasSSE2())
2911 // We forward some GPRs and some vector types.
2912 SmallVector<MVT, 2> RegParmTypes;
2913 MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2914 RegParmTypes.push_back(IntVT);
2915 if (VecVT != MVT::Other)
2916 RegParmTypes.push_back(VecVT);
2918 // Compute the set of forwarded registers. The rest are scratch.
2919 SmallVectorImpl<ForwardedRegister> &Forwards =
2920 FuncInfo->getForwardedMustTailRegParms();
2921 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2923 // Conservatively forward AL on x86_64, since it might be used for varargs.
2924 if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2925 unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2926 Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2929 // Copy all forwards from physical to virtual registers.
2930 for (ForwardedRegister &F : Forwards) {
2931 // FIXME: Can we use a less constrained schedule?
2932 SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2933 F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2934 Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2938 // Some CCs need callee pop.
2939 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2940 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2941 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2942 } else if (CallConv == CallingConv::X86_INTR && Ins.size() == 2) {
2943 // X86 interrupts must pop the error code if present
2944 FuncInfo->setBytesToPopOnReturn(Is64Bit ? 8 : 4);
2946 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2947 // If this is an sret function, the return should pop the hidden pointer.
2948 if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
2949 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2950 argsAreStructReturn(Ins, Subtarget->isTargetMCU()) == StackStructReturn)
2951 FuncInfo->setBytesToPopOnReturn(4);
2955 // RegSaveFrameIndex is X86-64 only.
2956 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2957 if (CallConv == CallingConv::X86_FastCall ||
2958 CallConv == CallingConv::X86_ThisCall)
2959 // fastcc functions can't have varargs.
2960 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2963 FuncInfo->setArgumentStackSize(StackSize);
2965 if (WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo()) {
2966 EHPersonality Personality = classifyEHPersonality(Fn->getPersonalityFn());
2967 if (Personality == EHPersonality::CoreCLR) {
2969 // TODO: Add a mechanism to frame lowering that will allow us to indicate
2970 // that we'd prefer this slot be allocated towards the bottom of the frame
2971 // (i.e. near the stack pointer after allocating the frame). Every
2972 // funclet needs a copy of this slot in its (mostly empty) frame, and the
2973 // offset from the bottom of this and each funclet's frame must be the
2974 // same, so the size of funclets' (mostly empty) frames is dictated by
2975 // how far this slot is from the bottom (since they allocate just enough
2976 // space to accomodate holding this slot at the correct offset).
2977 int PSPSymFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2978 EHInfo->PSPSymFrameIdx = PSPSymFI;
2986 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2987 SDValue StackPtr, SDValue Arg,
2988 SDLoc dl, SelectionDAG &DAG,
2989 const CCValAssign &VA,
2990 ISD::ArgFlagsTy Flags) const {
2991 unsigned LocMemOffset = VA.getLocMemOffset();
2992 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2993 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2995 if (Flags.isByVal())
2996 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2998 return DAG.getStore(
2999 Chain, dl, Arg, PtrOff,
3000 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
3004 /// Emit a load of return address if tail call
3005 /// optimization is performed and it is required.
3007 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
3008 SDValue &OutRetAddr, SDValue Chain,
3009 bool IsTailCall, bool Is64Bit,
3010 int FPDiff, SDLoc dl) const {
3011 // Adjust the Return address stack slot.
3012 EVT VT = getPointerTy(DAG.getDataLayout());
3013 OutRetAddr = getReturnAddressFrameIndex(DAG);
3015 // Load the "old" Return address.
3016 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
3017 false, false, false, 0);
3018 return SDValue(OutRetAddr.getNode(), 1);
3021 /// Emit a store of the return address if tail call
3022 /// optimization is performed and it is required (FPDiff!=0).
3023 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
3024 SDValue Chain, SDValue RetAddrFrIdx,
3025 EVT PtrVT, unsigned SlotSize,
3026 int FPDiff, SDLoc dl) {
3027 // Store the return address to the appropriate stack slot.
3028 if (!FPDiff) return Chain;
3029 // Calculate the new stack slot for the return address.
3030 int NewReturnAddrFI =
3031 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
3033 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
3034 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
3035 MachinePointerInfo::getFixedStack(
3036 DAG.getMachineFunction(), NewReturnAddrFI),
3041 /// Returns a vector_shuffle mask for an movs{s|d}, movd
3042 /// operation of specified width.
3043 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
3045 unsigned NumElems = VT.getVectorNumElements();
3046 SmallVector<int, 8> Mask;
3047 Mask.push_back(NumElems);
3048 for (unsigned i = 1; i != NumElems; ++i)
3050 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3054 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3055 SmallVectorImpl<SDValue> &InVals) const {
3056 SelectionDAG &DAG = CLI.DAG;
3058 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3059 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
3060 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
3061 SDValue Chain = CLI.Chain;
3062 SDValue Callee = CLI.Callee;
3063 CallingConv::ID CallConv = CLI.CallConv;
3064 bool &isTailCall = CLI.IsTailCall;
3065 bool isVarArg = CLI.IsVarArg;
3067 MachineFunction &MF = DAG.getMachineFunction();
3068 bool Is64Bit = Subtarget->is64Bit();
3069 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
3070 StructReturnType SR = callIsStructReturn(Outs, Subtarget->isTargetMCU());
3071 bool IsSibcall = false;
3072 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
3073 auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
3075 if (CallConv == CallingConv::X86_INTR)
3076 report_fatal_error("X86 interrupts may not be called directly");
3078 if (Attr.getValueAsString() == "true")
3081 if (Subtarget->isPICStyleGOT() &&
3082 !MF.getTarget().Options.GuaranteedTailCallOpt) {
3083 // If we are using a GOT, disable tail calls to external symbols with
3084 // default visibility. Tail calling such a symbol requires using a GOT
3085 // relocation, which forces early binding of the symbol. This breaks code
3086 // that require lazy function symbol resolution. Using musttail or
3087 // GuaranteedTailCallOpt will override this.
3088 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3089 if (!G || (!G->getGlobal()->hasLocalLinkage() &&
3090 G->getGlobal()->hasDefaultVisibility()))
3094 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
3096 // Force this to be a tail call. The verifier rules are enough to ensure
3097 // that we can lower this successfully without moving the return address
3100 } else if (isTailCall) {
3101 // Check if it's really possible to do a tail call.
3102 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
3103 isVarArg, SR != NotStructReturn,
3104 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
3105 Outs, OutVals, Ins, DAG);
3107 // Sibcalls are automatically detected tailcalls which do not require
3109 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
3116 assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
3117 "Var args not supported with calling convention fastcc, ghc or hipe");
3119 // Analyze operands of the call, assigning locations to each operand.
3120 SmallVector<CCValAssign, 16> ArgLocs;
3121 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
3123 // Allocate shadow area for Win64
3125 CCInfo.AllocateStack(32, 8);
3127 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3129 // Get a count of how many bytes are to be pushed on the stack.
3130 unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
3132 // This is a sibcall. The memory operands are available in caller's
3133 // own caller's stack.
3135 else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
3136 canGuaranteeTCO(CallConv))
3137 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
3140 if (isTailCall && !IsSibcall && !IsMustTail) {
3141 // Lower arguments at fp - stackoffset + fpdiff.
3142 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
3144 FPDiff = NumBytesCallerPushed - NumBytes;
3146 // Set the delta of movement of the returnaddr stackslot.
3147 // But only set if delta is greater than previous delta.
3148 if (FPDiff < X86Info->getTCReturnAddrDelta())
3149 X86Info->setTCReturnAddrDelta(FPDiff);
3152 unsigned NumBytesToPush = NumBytes;
3153 unsigned NumBytesToPop = NumBytes;
3155 // If we have an inalloca argument, all stack space has already been allocated
3156 // for us and be right at the top of the stack. We don't support multiple
3157 // arguments passed in memory when using inalloca.
3158 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
3160 if (!ArgLocs.back().isMemLoc())
3161 report_fatal_error("cannot use inalloca attribute on a register "
3163 if (ArgLocs.back().getLocMemOffset() != 0)
3164 report_fatal_error("any parameter with the inalloca attribute must be "
3165 "the only memory argument");
3169 Chain = DAG.getCALLSEQ_START(
3170 Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
3172 SDValue RetAddrFrIdx;
3173 // Load return address for tail calls.
3174 if (isTailCall && FPDiff)
3175 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3176 Is64Bit, FPDiff, dl);
3178 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3179 SmallVector<SDValue, 8> MemOpChains;
3182 // Walk the register/memloc assignments, inserting copies/loads. In the case
3183 // of tail call optimization arguments are handle later.
3184 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3185 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3186 // Skip inalloca arguments, they have already been written.
3187 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3188 if (Flags.isInAlloca())
3191 CCValAssign &VA = ArgLocs[i];
3192 EVT RegVT = VA.getLocVT();
3193 SDValue Arg = OutVals[i];
3194 bool isByVal = Flags.isByVal();
3196 // Promote the value if needed.
3197 switch (VA.getLocInfo()) {
3198 default: llvm_unreachable("Unknown loc info!");
3199 case CCValAssign::Full: break;
3200 case CCValAssign::SExt:
3201 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3203 case CCValAssign::ZExt:
3204 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3206 case CCValAssign::AExt:
3207 if (Arg.getValueType().isVector() &&
3208 Arg.getValueType().getVectorElementType() == MVT::i1)
3209 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3210 else if (RegVT.is128BitVector()) {
3211 // Special case: passing MMX values in XMM registers.
3212 Arg = DAG.getBitcast(MVT::i64, Arg);
3213 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3214 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3216 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3218 case CCValAssign::BCvt:
3219 Arg = DAG.getBitcast(RegVT, Arg);
3221 case CCValAssign::Indirect: {
3222 // Store the argument.
3223 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3224 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3225 Chain = DAG.getStore(
3226 Chain, dl, Arg, SpillSlot,
3227 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3234 if (VA.isRegLoc()) {
3235 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3236 if (isVarArg && IsWin64) {
3237 // Win64 ABI requires argument XMM reg to be copied to the corresponding
3238 // shadow reg if callee is a varargs function.
3239 unsigned ShadowReg = 0;
3240 switch (VA.getLocReg()) {
3241 case X86::XMM0: ShadowReg = X86::RCX; break;
3242 case X86::XMM1: ShadowReg = X86::RDX; break;
3243 case X86::XMM2: ShadowReg = X86::R8; break;
3244 case X86::XMM3: ShadowReg = X86::R9; break;
3247 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3249 } else if (!IsSibcall && (!isTailCall || isByVal)) {
3250 assert(VA.isMemLoc());
3251 if (!StackPtr.getNode())
3252 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3253 getPointerTy(DAG.getDataLayout()));
3254 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3255 dl, DAG, VA, Flags));
3259 if (!MemOpChains.empty())
3260 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3262 if (Subtarget->isPICStyleGOT()) {
3263 // ELF / PIC requires GOT in the EBX register before function calls via PLT
3266 RegsToPass.push_back(std::make_pair(
3267 unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3268 getPointerTy(DAG.getDataLayout()))));
3270 // If we are tail calling and generating PIC/GOT style code load the
3271 // address of the callee into ECX. The value in ecx is used as target of
3272 // the tail jump. This is done to circumvent the ebx/callee-saved problem
3273 // for tail calls on PIC/GOT architectures. Normally we would just put the
3274 // address of GOT into ebx and then call target@PLT. But for tail calls
3275 // ebx would be restored (since ebx is callee saved) before jumping to the
3278 // Note: The actual moving to ECX is done further down.
3279 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3280 if (G && !G->getGlobal()->hasLocalLinkage() &&
3281 G->getGlobal()->hasDefaultVisibility())
3282 Callee = LowerGlobalAddress(Callee, DAG);
3283 else if (isa<ExternalSymbolSDNode>(Callee))
3284 Callee = LowerExternalSymbol(Callee, DAG);
3288 if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3289 // From AMD64 ABI document:
3290 // For calls that may call functions that use varargs or stdargs
3291 // (prototype-less calls or calls to functions containing ellipsis (...) in
3292 // the declaration) %al is used as hidden argument to specify the number
3293 // of SSE registers used. The contents of %al do not need to match exactly
3294 // the number of registers, but must be an ubound on the number of SSE
3295 // registers used and is in the range 0 - 8 inclusive.
3297 // Count the number of XMM registers allocated.
3298 static const MCPhysReg XMMArgRegs[] = {
3299 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3300 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3302 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3303 assert((Subtarget->hasSSE1() || !NumXMMRegs)
3304 && "SSE registers cannot be used when SSE is disabled");
3306 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3307 DAG.getConstant(NumXMMRegs, dl,
3311 if (isVarArg && IsMustTail) {
3312 const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3313 for (const auto &F : Forwards) {
3314 SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3315 RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3319 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
3320 // don't need this because the eligibility check rejects calls that require
3321 // shuffling arguments passed in memory.
3322 if (!IsSibcall && isTailCall) {
3323 // Force all the incoming stack arguments to be loaded from the stack
3324 // before any new outgoing arguments are stored to the stack, because the
3325 // outgoing stack slots may alias the incoming argument stack slots, and
3326 // the alias isn't otherwise explicit. This is slightly more conservative
3327 // than necessary, because it means that each store effectively depends
3328 // on every argument instead of just those arguments it would clobber.
3329 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3331 SmallVector<SDValue, 8> MemOpChains2;
3334 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3335 CCValAssign &VA = ArgLocs[i];
3338 assert(VA.isMemLoc());
3339 SDValue Arg = OutVals[i];
3340 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3341 // Skip inalloca arguments. They don't require any work.
3342 if (Flags.isInAlloca())
3344 // Create frame index.
3345 int32_t Offset = VA.getLocMemOffset()+FPDiff;
3346 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3347 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3348 FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3350 if (Flags.isByVal()) {
3351 // Copy relative to framepointer.
3352 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3353 if (!StackPtr.getNode())
3354 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3355 getPointerTy(DAG.getDataLayout()));
3356 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3359 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3363 // Store relative to framepointer.
3364 MemOpChains2.push_back(DAG.getStore(
3365 ArgChain, dl, Arg, FIN,
3366 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3371 if (!MemOpChains2.empty())
3372 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3374 // Store the return address to the appropriate stack slot.
3375 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3376 getPointerTy(DAG.getDataLayout()),
3377 RegInfo->getSlotSize(), FPDiff, dl);
3380 // Build a sequence of copy-to-reg nodes chained together with token chain
3381 // and flag operands which copy the outgoing args into registers.
3383 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3384 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3385 RegsToPass[i].second, InFlag);
3386 InFlag = Chain.getValue(1);
3389 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3390 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3391 // In the 64-bit large code model, we have to make all calls
3392 // through a register, since the call instruction's 32-bit
3393 // pc-relative offset may not be large enough to hold the whole
3395 } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3396 // If the callee is a GlobalAddress node (quite common, every direct call
3397 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3399 GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3401 // We should use extra load for direct calls to dllimported functions in
3403 const GlobalValue *GV = G->getGlobal();
3404 if (!GV->hasDLLImportStorageClass()) {
3405 unsigned char OpFlags = 0;
3406 bool ExtraLoad = false;
3407 unsigned WrapperKind = ISD::DELETED_NODE;
3409 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3410 // external symbols most go through the PLT in PIC mode. If the symbol
3411 // has hidden or protected visibility, or if it is static or local, then
3412 // we don't need to use the PLT - we can directly call it.
3413 if (Subtarget->isTargetELF() &&
3414 DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3415 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3416 OpFlags = X86II::MO_PLT;
3417 } else if (Subtarget->isPICStyleStubAny() &&
3418 !GV->isStrongDefinitionForLinker() &&
3419 (!Subtarget->getTargetTriple().isMacOSX() ||
3420 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3421 // PC-relative references to external symbols should go through $stub,
3422 // unless we're building with the leopard linker or later, which
3423 // automatically synthesizes these stubs.
3424 OpFlags = X86II::MO_DARWIN_STUB;
3425 } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3426 cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3427 // If the function is marked as non-lazy, generate an indirect call
3428 // which loads from the GOT directly. This avoids runtime overhead
3429 // at the cost of eager binding (and one extra byte of encoding).
3430 OpFlags = X86II::MO_GOTPCREL;
3431 WrapperKind = X86ISD::WrapperRIP;
3435 Callee = DAG.getTargetGlobalAddress(
3436 GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3438 // Add a wrapper if needed.
3439 if (WrapperKind != ISD::DELETED_NODE)
3440 Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3441 getPointerTy(DAG.getDataLayout()), Callee);
3442 // Add extra indirection if needed.
3444 Callee = DAG.getLoad(
3445 getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3446 MachinePointerInfo::getGOT(DAG.getMachineFunction()), false, false,
3449 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3450 unsigned char OpFlags = 0;
3452 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3453 // external symbols should go through the PLT.
3454 if (Subtarget->isTargetELF() &&
3455 DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3456 OpFlags = X86II::MO_PLT;
3457 } else if (Subtarget->isPICStyleStubAny() &&
3458 (!Subtarget->getTargetTriple().isMacOSX() ||
3459 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3460 // PC-relative references to external symbols should go through $stub,
3461 // unless we're building with the leopard linker or later, which
3462 // automatically synthesizes these stubs.
3463 OpFlags = X86II::MO_DARWIN_STUB;
3466 Callee = DAG.getTargetExternalSymbol(
3467 S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3468 } else if (Subtarget->isTarget64BitILP32() &&
3469 Callee->getValueType(0) == MVT::i32) {
3470 // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3471 Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3474 // Returns a chain & a flag for retval copy to use.
3475 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3476 SmallVector<SDValue, 8> Ops;
3478 if (!IsSibcall && isTailCall) {
3479 Chain = DAG.getCALLSEQ_END(Chain,
3480 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3481 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3482 InFlag = Chain.getValue(1);
3485 Ops.push_back(Chain);
3486 Ops.push_back(Callee);
3489 Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3491 // Add argument registers to the end of the list so that they are known live
3493 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3494 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3495 RegsToPass[i].second.getValueType()));
3497 // Add a register mask operand representing the call-preserved registers.
3498 const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3499 assert(Mask && "Missing call preserved mask for calling convention");
3501 // If this is an invoke in a 32-bit function using a funclet-based
3502 // personality, assume the function clobbers all registers. If an exception
3503 // is thrown, the runtime will not restore CSRs.
3504 // FIXME: Model this more precisely so that we can register allocate across
3505 // the normal edge and spill and fill across the exceptional edge.
3506 if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3507 const Function *CallerFn = MF.getFunction();
3508 EHPersonality Pers =
3509 CallerFn->hasPersonalityFn()
3510 ? classifyEHPersonality(CallerFn->getPersonalityFn())
3511 : EHPersonality::Unknown;
3512 if (isFuncletEHPersonality(Pers))
3513 Mask = RegInfo->getNoPreservedMask();
3516 Ops.push_back(DAG.getRegisterMask(Mask));
3518 if (InFlag.getNode())
3519 Ops.push_back(InFlag);
3523 //// If this is the first return lowered for this function, add the regs
3524 //// to the liveout set for the function.
3525 // This isn't right, although it's probably harmless on x86; liveouts
3526 // should be computed from returns not tail calls. Consider a void
3527 // function making a tail call to a function returning int.
3528 MF.getFrameInfo()->setHasTailCall();
3529 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3532 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3533 InFlag = Chain.getValue(1);
3535 // Create the CALLSEQ_END node.
3536 unsigned NumBytesForCalleeToPop;
3537 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3538 DAG.getTarget().Options.GuaranteedTailCallOpt))
3539 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
3540 else if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
3541 !Subtarget->getTargetTriple().isOSMSVCRT() &&
3542 SR == StackStructReturn)
3543 // If this is a call to a struct-return function, the callee
3544 // pops the hidden struct pointer, so we have to push it back.
3545 // This is common for Darwin/X86, Linux & Mingw32 targets.
3546 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3547 NumBytesForCalleeToPop = 4;
3549 NumBytesForCalleeToPop = 0; // Callee pops nothing.
3551 // Returns a flag for retval copy to use.
3553 Chain = DAG.getCALLSEQ_END(Chain,
3554 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3555 DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3558 InFlag = Chain.getValue(1);
3561 // Handle result values, copying them out of physregs into vregs that we
3563 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3564 Ins, dl, DAG, InVals);
3567 //===----------------------------------------------------------------------===//
3568 // Fast Calling Convention (tail call) implementation
3569 //===----------------------------------------------------------------------===//
3571 // Like std call, callee cleans arguments, convention except that ECX is
3572 // reserved for storing the tail called function address. Only 2 registers are
3573 // free for argument passing (inreg). Tail call optimization is performed
3575 // * tailcallopt is enabled
3576 // * caller/callee are fastcc
3577 // On X86_64 architecture with GOT-style position independent code only local
3578 // (within module) calls are supported at the moment.
3579 // To keep the stack aligned according to platform abi the function
3580 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3581 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3582 // If a tail called function callee has more arguments than the caller the
3583 // caller needs to make sure that there is room to move the RETADDR to. This is
3584 // achieved by reserving an area the size of the argument delta right after the
3585 // original RETADDR, but before the saved framepointer or the spilled registers
3586 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3598 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
3601 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3602 SelectionDAG& DAG) const {
3603 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3604 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3605 unsigned StackAlignment = TFI.getStackAlignment();
3606 uint64_t AlignMask = StackAlignment - 1;
3607 int64_t Offset = StackSize;
3608 unsigned SlotSize = RegInfo->getSlotSize();
3609 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3610 // Number smaller than 12 so just add the difference.
3611 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3613 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3614 Offset = ((~AlignMask) & Offset) + StackAlignment +
3615 (StackAlignment-SlotSize);
3620 /// Return true if the given stack call argument is already available in the
3621 /// same position (relatively) of the caller's incoming argument stack.
3623 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3624 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3625 const X86InstrInfo *TII) {
3626 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3628 if (Arg.getOpcode() == ISD::CopyFromReg) {
3629 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3630 if (!TargetRegisterInfo::isVirtualRegister(VR))
3632 MachineInstr *Def = MRI->getVRegDef(VR);
3635 if (!Flags.isByVal()) {
3636 if (!TII->isLoadFromStackSlot(Def, FI))
3639 unsigned Opcode = Def->getOpcode();
3640 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3641 Opcode == X86::LEA64_32r) &&
3642 Def->getOperand(1).isFI()) {
3643 FI = Def->getOperand(1).getIndex();
3644 Bytes = Flags.getByValSize();
3648 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3649 if (Flags.isByVal())
3650 // ByVal argument is passed in as a pointer but it's now being
3651 // dereferenced. e.g.
3652 // define @foo(%struct.X* %A) {
3653 // tail call @bar(%struct.X* byval %A)
3656 SDValue Ptr = Ld->getBasePtr();
3657 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3660 FI = FINode->getIndex();
3661 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3662 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3663 FI = FINode->getIndex();
3664 Bytes = Flags.getByValSize();
3668 assert(FI != INT_MAX);
3669 if (!MFI->isFixedObjectIndex(FI))
3671 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3674 /// Check whether the call is eligible for tail call optimization. Targets
3675 /// that want to do tail call optimization should implement this function.
3676 bool X86TargetLowering::IsEligibleForTailCallOptimization(
3677 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
3678 bool isCalleeStructRet, bool isCallerStructRet, Type *RetTy,
3679 const SmallVectorImpl<ISD::OutputArg> &Outs,
3680 const SmallVectorImpl<SDValue> &OutVals,
3681 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3682 if (!mayTailCallThisCC(CalleeCC))
3685 // If -tailcallopt is specified, make fastcc functions tail-callable.
3686 MachineFunction &MF = DAG.getMachineFunction();
3687 const Function *CallerF = MF.getFunction();
3689 // If the function return type is x86_fp80 and the callee return type is not,
3690 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3691 // perform a tailcall optimization here.
3692 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3695 CallingConv::ID CallerCC = CallerF->getCallingConv();
3696 bool CCMatch = CallerCC == CalleeCC;
3697 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3698 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3700 // Win64 functions have extra shadow space for argument homing. Don't do the
3701 // sibcall if the caller and callee have mismatched expectations for this
3703 if (IsCalleeWin64 != IsCallerWin64)
3706 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3707 if (canGuaranteeTCO(CalleeCC) && CCMatch)
3712 // Look for obvious safe cases to perform tail call optimization that do not
3713 // require ABI changes. This is what gcc calls sibcall.
3715 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3716 // emit a special epilogue.
3717 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3718 if (RegInfo->needsStackRealignment(MF))
3721 // Also avoid sibcall optimization if either caller or callee uses struct
3722 // return semantics.
3723 if (isCalleeStructRet || isCallerStructRet)
3726 // Do not sibcall optimize vararg calls unless all arguments are passed via
3728 if (isVarArg && !Outs.empty()) {
3729 // Optimizing for varargs on Win64 is unlikely to be safe without
3730 // additional testing.
3731 if (IsCalleeWin64 || IsCallerWin64)
3734 SmallVector<CCValAssign, 16> ArgLocs;
3735 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3738 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3739 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3740 if (!ArgLocs[i].isRegLoc())
3744 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3745 // stack. Therefore, if it's not used by the call it is not safe to optimize
3746 // this into a sibcall.
3747 bool Unused = false;
3748 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3755 SmallVector<CCValAssign, 16> RVLocs;
3756 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3758 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3759 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3760 CCValAssign &VA = RVLocs[i];
3761 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3766 // If the calling conventions do not match, then we'd better make sure the
3767 // results are returned in the same way as what the caller expects.
3769 SmallVector<CCValAssign, 16> RVLocs1;
3770 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3772 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3774 SmallVector<CCValAssign, 16> RVLocs2;
3775 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3777 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3779 if (RVLocs1.size() != RVLocs2.size())
3781 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3782 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3784 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3786 if (RVLocs1[i].isRegLoc()) {
3787 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3790 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3796 unsigned StackArgsSize = 0;
3798 // If the callee takes no arguments then go on to check the results of the
3800 if (!Outs.empty()) {
3801 // Check if stack adjustment is needed. For now, do not do this if any
3802 // argument is passed on the stack.
3803 SmallVector<CCValAssign, 16> ArgLocs;
3804 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3807 // Allocate shadow area for Win64
3809 CCInfo.AllocateStack(32, 8);
3811 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3812 StackArgsSize = CCInfo.getNextStackOffset();
3814 if (CCInfo.getNextStackOffset()) {
3815 // Check if the arguments are already laid out in the right way as
3816 // the caller's fixed stack objects.
3817 MachineFrameInfo *MFI = MF.getFrameInfo();
3818 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3819 const X86InstrInfo *TII = Subtarget->getInstrInfo();
3820 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3821 CCValAssign &VA = ArgLocs[i];
3822 SDValue Arg = OutVals[i];
3823 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3824 if (VA.getLocInfo() == CCValAssign::Indirect)
3826 if (!VA.isRegLoc()) {
3827 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3834 // If the tailcall address may be in a register, then make sure it's
3835 // possible to register allocate for it. In 32-bit, the call address can
3836 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3837 // callee-saved registers are restored. These happen to be the same
3838 // registers used to pass 'inreg' arguments so watch out for those.
3839 if (!Subtarget->is64Bit() &&
3840 ((!isa<GlobalAddressSDNode>(Callee) &&
3841 !isa<ExternalSymbolSDNode>(Callee)) ||
3842 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3843 unsigned NumInRegs = 0;
3844 // In PIC we need an extra register to formulate the address computation
3846 unsigned MaxInRegs =
3847 (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3849 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3850 CCValAssign &VA = ArgLocs[i];
3853 unsigned Reg = VA.getLocReg();
3856 case X86::EAX: case X86::EDX: case X86::ECX:
3857 if (++NumInRegs == MaxInRegs)
3865 bool CalleeWillPop =
3866 X86::isCalleePop(CalleeCC, Subtarget->is64Bit(), isVarArg,
3867 MF.getTarget().Options.GuaranteedTailCallOpt);
3869 if (unsigned BytesToPop =
3870 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn()) {
3871 // If we have bytes to pop, the callee must pop them.
3872 bool CalleePopMatches = CalleeWillPop && BytesToPop == StackArgsSize;
3873 if (!CalleePopMatches)
3875 } else if (CalleeWillPop && StackArgsSize > 0) {
3876 // If we don't have bytes to pop, make sure the callee doesn't pop any.
3884 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3885 const TargetLibraryInfo *libInfo) const {
3886 return X86::createFastISel(funcInfo, libInfo);
3889 //===----------------------------------------------------------------------===//
3890 // Other Lowering Hooks
3891 //===----------------------------------------------------------------------===//
3893 static bool MayFoldLoad(SDValue Op) {
3894 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3897 static bool MayFoldIntoStore(SDValue Op) {
3898 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3901 static bool isTargetShuffle(unsigned Opcode) {
3903 default: return false;
3904 case X86ISD::BLENDI:
3905 case X86ISD::PSHUFB:
3906 case X86ISD::PSHUFD:
3907 case X86ISD::PSHUFHW:
3908 case X86ISD::PSHUFLW:
3910 case X86ISD::INSERTPS:
3911 case X86ISD::PALIGNR:
3912 case X86ISD::MOVLHPS:
3913 case X86ISD::MOVLHPD:
3914 case X86ISD::MOVHLPS:
3915 case X86ISD::MOVLPS:
3916 case X86ISD::MOVLPD:
3917 case X86ISD::MOVSHDUP:
3918 case X86ISD::MOVSLDUP:
3919 case X86ISD::MOVDDUP:
3922 case X86ISD::UNPCKL:
3923 case X86ISD::UNPCKH:
3924 case X86ISD::VPERMILPI:
3925 case X86ISD::VPERM2X128:
3926 case X86ISD::VPERMI:
3927 case X86ISD::VPERMV:
3928 case X86ISD::VPERMV3:
3933 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, MVT VT,
3934 SDValue V1, unsigned TargetMask,
3935 SelectionDAG &DAG) {
3937 default: llvm_unreachable("Unknown x86 shuffle node");
3938 case X86ISD::PSHUFD:
3939 case X86ISD::PSHUFHW:
3940 case X86ISD::PSHUFLW:
3941 case X86ISD::VPERMILPI:
3942 case X86ISD::VPERMI:
3943 return DAG.getNode(Opc, dl, VT, V1,
3944 DAG.getConstant(TargetMask, dl, MVT::i8));
3948 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, MVT VT,
3949 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3951 default: llvm_unreachable("Unknown x86 shuffle node");
3952 case X86ISD::MOVLHPS:
3953 case X86ISD::MOVLHPD:
3954 case X86ISD::MOVHLPS:
3955 case X86ISD::MOVLPS:
3956 case X86ISD::MOVLPD:
3959 case X86ISD::UNPCKL:
3960 case X86ISD::UNPCKH:
3961 return DAG.getNode(Opc, dl, VT, V1, V2);
3965 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3966 MachineFunction &MF = DAG.getMachineFunction();
3967 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3968 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3969 int ReturnAddrIndex = FuncInfo->getRAIndex();
3971 if (ReturnAddrIndex == 0) {
3972 // Set up a frame object for the return address.
3973 unsigned SlotSize = RegInfo->getSlotSize();
3974 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3977 FuncInfo->setRAIndex(ReturnAddrIndex);
3980 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3983 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3984 bool hasSymbolicDisplacement) {
3985 // Offset should fit into 32 bit immediate field.
3986 if (!isInt<32>(Offset))
3989 // If we don't have a symbolic displacement - we don't have any extra
3991 if (!hasSymbolicDisplacement)
3994 // FIXME: Some tweaks might be needed for medium code model.
3995 if (M != CodeModel::Small && M != CodeModel::Kernel)
3998 // For small code model we assume that latest object is 16MB before end of 31
3999 // bits boundary. We may also accept pretty large negative constants knowing
4000 // that all objects are in the positive half of address space.
4001 if (M == CodeModel::Small && Offset < 16*1024*1024)
4004 // For kernel code model we know that all object resist in the negative half
4005 // of 32bits address space. We may not accept negative offsets, since they may
4006 // be just off and we may accept pretty large positive ones.
4007 if (M == CodeModel::Kernel && Offset >= 0)
4013 /// Determines whether the callee is required to pop its own arguments.
4014 /// Callee pop is necessary to support tail calls.
4015 bool X86::isCalleePop(CallingConv::ID CallingConv,
4016 bool is64Bit, bool IsVarArg, bool GuaranteeTCO) {
4017 // If GuaranteeTCO is true, we force some calls to be callee pop so that we
4018 // can guarantee TCO.
4019 if (!IsVarArg && shouldGuaranteeTCO(CallingConv, GuaranteeTCO))
4022 switch (CallingConv) {
4025 case CallingConv::X86_StdCall:
4026 case CallingConv::X86_FastCall:
4027 case CallingConv::X86_ThisCall:
4028 case CallingConv::X86_VectorCall:
4033 /// \brief Return true if the condition is an unsigned comparison operation.
4034 static bool isX86CCUnsigned(unsigned X86CC) {
4036 default: llvm_unreachable("Invalid integer condition!");
4037 case X86::COND_E: return true;
4038 case X86::COND_G: return false;
4039 case X86::COND_GE: return false;
4040 case X86::COND_L: return false;
4041 case X86::COND_LE: return false;
4042 case X86::COND_NE: return true;
4043 case X86::COND_B: return true;
4044 case X86::COND_A: return true;
4045 case X86::COND_BE: return true;
4046 case X86::COND_AE: return true;
4050 static X86::CondCode TranslateIntegerX86CC(ISD::CondCode SetCCOpcode) {
4051 switch (SetCCOpcode) {
4052 default: llvm_unreachable("Invalid integer condition!");
4053 case ISD::SETEQ: return X86::COND_E;
4054 case ISD::SETGT: return X86::COND_G;
4055 case ISD::SETGE: return X86::COND_GE;
4056 case ISD::SETLT: return X86::COND_L;
4057 case ISD::SETLE: return X86::COND_LE;
4058 case ISD::SETNE: return X86::COND_NE;
4059 case ISD::SETULT: return X86::COND_B;
4060 case ISD::SETUGT: return X86::COND_A;
4061 case ISD::SETULE: return X86::COND_BE;
4062 case ISD::SETUGE: return X86::COND_AE;
4066 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
4067 /// condition code, returning the condition code and the LHS/RHS of the
4068 /// comparison to make.
4069 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
4070 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
4072 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4073 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
4074 // X > -1 -> X == 0, jump !sign.
4075 RHS = DAG.getConstant(0, DL, RHS.getValueType());
4076 return X86::COND_NS;
4078 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
4079 // X < 0 -> X == 0, jump on sign.
4082 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
4084 RHS = DAG.getConstant(0, DL, RHS.getValueType());
4085 return X86::COND_LE;
4089 return TranslateIntegerX86CC(SetCCOpcode);
4092 // First determine if it is required or is profitable to flip the operands.
4094 // If LHS is a foldable load, but RHS is not, flip the condition.
4095 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
4096 !ISD::isNON_EXTLoad(RHS.getNode())) {
4097 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
4098 std::swap(LHS, RHS);
4101 switch (SetCCOpcode) {
4107 std::swap(LHS, RHS);
4111 // On a floating point condition, the flags are set as follows:
4113 // 0 | 0 | 0 | X > Y
4114 // 0 | 0 | 1 | X < Y
4115 // 1 | 0 | 0 | X == Y
4116 // 1 | 1 | 1 | unordered
4117 switch (SetCCOpcode) {
4118 default: llvm_unreachable("Condcode should be pre-legalized away");
4120 case ISD::SETEQ: return X86::COND_E;
4121 case ISD::SETOLT: // flipped
4123 case ISD::SETGT: return X86::COND_A;
4124 case ISD::SETOLE: // flipped
4126 case ISD::SETGE: return X86::COND_AE;
4127 case ISD::SETUGT: // flipped
4129 case ISD::SETLT: return X86::COND_B;
4130 case ISD::SETUGE: // flipped
4132 case ISD::SETLE: return X86::COND_BE;
4134 case ISD::SETNE: return X86::COND_NE;
4135 case ISD::SETUO: return X86::COND_P;
4136 case ISD::SETO: return X86::COND_NP;
4138 case ISD::SETUNE: return X86::COND_INVALID;
4142 /// Is there a floating point cmov for the specific X86 condition code?
4143 /// Current x86 isa includes the following FP cmov instructions:
4144 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
4145 static bool hasFPCMov(unsigned X86CC) {
4161 /// Returns true if the target can instruction select the
4162 /// specified FP immediate natively. If false, the legalizer will
4163 /// materialize the FP immediate as a load from a constant pool.
4164 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4165 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
4166 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
4172 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
4173 ISD::LoadExtType ExtTy,
4175 // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
4176 // relocation target a movq or addq instruction: don't let the load shrink.
4177 SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
4178 if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
4179 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
4180 return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
4184 /// \brief Returns true if it is beneficial to convert a load of a constant
4185 /// to just the constant itself.
4186 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
4188 assert(Ty->isIntegerTy());
4190 unsigned BitSize = Ty->getPrimitiveSizeInBits();
4191 if (BitSize == 0 || BitSize > 64)
4196 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
4197 unsigned Index) const {
4198 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4201 return (Index == 0 || Index == ResVT.getVectorNumElements());
4204 bool X86TargetLowering::isCheapToSpeculateCttz() const {
4205 // Speculate cttz only if we can directly use TZCNT.
4206 return Subtarget->hasBMI();
4209 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4210 // Speculate ctlz only if we can directly use LZCNT.
4211 return Subtarget->hasLZCNT();
4214 /// Return true if every element in Mask, beginning
4215 /// from position Pos and ending in Pos+Size is undef.
4216 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4217 for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4223 /// Return true if Val is undef or if its value falls within the
4224 /// specified range (L, H].
4225 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4226 return (Val < 0) || (Val >= Low && Val < Hi);
4229 /// Val is either less than zero (undef) or equal to the specified value.
4230 static bool isUndefOrEqual(int Val, int CmpVal) {
4231 return (Val < 0 || Val == CmpVal);
4234 /// Return true if every element in Mask, beginning
4235 /// from position Pos and ending in Pos+Size, falls within the specified
4236 /// sequential range (Low, Low+Size]. or is undef.
4237 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4238 unsigned Pos, unsigned Size, int Low) {
4239 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4240 if (!isUndefOrEqual(Mask[i], Low))
4245 /// Return true if the specified EXTRACT_SUBVECTOR operand specifies a vector
4246 /// extract that is suitable for instruction that extract 128 or 256 bit vectors
4247 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4248 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4249 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4252 // The index should be aligned on a vecWidth-bit boundary.
4254 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4256 MVT VT = N->getSimpleValueType(0);
4257 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4258 bool Result = (Index * ElSize) % vecWidth == 0;
4263 /// Return true if the specified INSERT_SUBVECTOR
4264 /// operand specifies a subvector insert that is suitable for input to
4265 /// insertion of 128 or 256-bit subvectors
4266 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4267 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4268 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4270 // The index should be aligned on a vecWidth-bit boundary.
4272 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4274 MVT VT = N->getSimpleValueType(0);
4275 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4276 bool Result = (Index * ElSize) % vecWidth == 0;
4281 bool X86::isVINSERT128Index(SDNode *N) {
4282 return isVINSERTIndex(N, 128);
4285 bool X86::isVINSERT256Index(SDNode *N) {
4286 return isVINSERTIndex(N, 256);
4289 bool X86::isVEXTRACT128Index(SDNode *N) {
4290 return isVEXTRACTIndex(N, 128);
4293 bool X86::isVEXTRACT256Index(SDNode *N) {
4294 return isVEXTRACTIndex(N, 256);
4297 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4298 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4299 assert(isa<ConstantSDNode>(N->getOperand(1).getNode()) &&
4300 "Illegal extract subvector for VEXTRACT");
4303 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4305 MVT VecVT = N->getOperand(0).getSimpleValueType();
4306 MVT ElVT = VecVT.getVectorElementType();
4308 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4309 return Index / NumElemsPerChunk;
4312 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4313 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4314 assert(isa<ConstantSDNode>(N->getOperand(2).getNode()) &&
4315 "Illegal insert subvector for VINSERT");
4318 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4320 MVT VecVT = N->getSimpleValueType(0);
4321 MVT ElVT = VecVT.getVectorElementType();
4323 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4324 return Index / NumElemsPerChunk;
4327 /// Return the appropriate immediate to extract the specified
4328 /// EXTRACT_SUBVECTOR index with VEXTRACTF128 and VINSERTI128 instructions.
4329 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4330 return getExtractVEXTRACTImmediate(N, 128);
4333 /// Return the appropriate immediate to extract the specified
4334 /// EXTRACT_SUBVECTOR index with VEXTRACTF64x4 and VINSERTI64x4 instructions.
4335 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4336 return getExtractVEXTRACTImmediate(N, 256);
4339 /// Return the appropriate immediate to insert at the specified
4340 /// INSERT_SUBVECTOR index with VINSERTF128 and VINSERTI128 instructions.
4341 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4342 return getInsertVINSERTImmediate(N, 128);
4345 /// Return the appropriate immediate to insert at the specified
4346 /// INSERT_SUBVECTOR index with VINSERTF46x4 and VINSERTI64x4 instructions.
4347 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4348 return getInsertVINSERTImmediate(N, 256);
4351 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
4352 bool X86::isZeroNode(SDValue Elt) {
4353 return isNullConstant(Elt) || isNullFPConstant(Elt);
4356 // Build a vector of constants
4357 // Use an UNDEF node if MaskElt == -1.
4358 // Spilt 64-bit constants in the 32-bit mode.
4359 static SDValue getConstVector(ArrayRef<int> Values, MVT VT,
4361 SDLoc dl, bool IsMask = false) {
4363 SmallVector<SDValue, 32> Ops;
4366 MVT ConstVecVT = VT;
4367 unsigned NumElts = VT.getVectorNumElements();
4368 bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
4369 if (!In64BitMode && VT.getVectorElementType() == MVT::i64) {
4370 ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
4374 MVT EltVT = ConstVecVT.getVectorElementType();
4375 for (unsigned i = 0; i < NumElts; ++i) {
4376 bool IsUndef = Values[i] < 0 && IsMask;
4377 SDValue OpNode = IsUndef ? DAG.getUNDEF(EltVT) :
4378 DAG.getConstant(Values[i], dl, EltVT);
4379 Ops.push_back(OpNode);
4381 Ops.push_back(IsUndef ? DAG.getUNDEF(EltVT) :
4382 DAG.getConstant(0, dl, EltVT));
4384 SDValue ConstsNode = DAG.getNode(ISD::BUILD_VECTOR, dl, ConstVecVT, Ops);
4386 ConstsNode = DAG.getBitcast(VT, ConstsNode);
4390 /// Returns a vector of specified type with all zero elements.
4391 static SDValue getZeroVector(MVT VT, const X86Subtarget *Subtarget,
4392 SelectionDAG &DAG, SDLoc dl) {
4393 assert(VT.isVector() && "Expected a vector type");
4395 // Always build SSE zero vectors as <4 x i32> bitcasted
4396 // to their dest type. This ensures they get CSE'd.
4398 if (VT.is128BitVector()) { // SSE
4399 if (Subtarget->hasSSE2()) { // SSE2
4400 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4401 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4403 SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4404 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4406 } else if (VT.is256BitVector()) { // AVX
4407 if (Subtarget->hasInt256()) { // AVX2
4408 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4409 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4410 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4412 // 256-bit logic and arithmetic instructions in AVX are all
4413 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4414 SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4415 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4416 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4418 } else if (VT.is512BitVector()) { // AVX-512
4419 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4420 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4421 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4422 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4423 } else if (VT.getVectorElementType() == MVT::i1) {
4425 assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4426 && "Unexpected vector type");
4427 assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4428 && "Unexpected vector type");
4429 SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4430 SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4431 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4433 llvm_unreachable("Unexpected vector type");
4435 return DAG.getBitcast(VT, Vec);
4438 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4439 SelectionDAG &DAG, SDLoc dl,
4440 unsigned vectorWidth) {
4441 assert((vectorWidth == 128 || vectorWidth == 256) &&
4442 "Unsupported vector width");
4443 EVT VT = Vec.getValueType();
4444 EVT ElVT = VT.getVectorElementType();
4445 unsigned Factor = VT.getSizeInBits()/vectorWidth;
4446 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4447 VT.getVectorNumElements()/Factor);
4449 // Extract from UNDEF is UNDEF.
4450 if (Vec.getOpcode() == ISD::UNDEF)
4451 return DAG.getUNDEF(ResultVT);
4453 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
4454 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4455 assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
4457 // This is the index of the first element of the vectorWidth-bit chunk
4458 // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
4459 IdxVal &= ~(ElemsPerChunk - 1);
4461 // If the input is a buildvector just emit a smaller one.
4462 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4463 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4464 makeArrayRef(Vec->op_begin() + IdxVal, ElemsPerChunk));
4466 SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
4467 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4470 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
4471 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4472 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4473 /// instructions or a simple subregister reference. Idx is an index in the
4474 /// 128 bits we want. It need not be aligned to a 128-bit boundary. That makes
4475 /// lowering EXTRACT_VECTOR_ELT operations easier.
4476 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4477 SelectionDAG &DAG, SDLoc dl) {
4478 assert((Vec.getValueType().is256BitVector() ||
4479 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4480 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4483 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4484 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4485 SelectionDAG &DAG, SDLoc dl) {
4486 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4487 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4490 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4491 unsigned IdxVal, SelectionDAG &DAG,
4492 SDLoc dl, unsigned vectorWidth) {
4493 assert((vectorWidth == 128 || vectorWidth == 256) &&
4494 "Unsupported vector width");
4495 // Inserting UNDEF is Result
4496 if (Vec.getOpcode() == ISD::UNDEF)
4498 EVT VT = Vec.getValueType();
4499 EVT ElVT = VT.getVectorElementType();
4500 EVT ResultVT = Result.getValueType();
4502 // Insert the relevant vectorWidth bits.
4503 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4504 assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
4506 // This is the index of the first element of the vectorWidth-bit chunk
4507 // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
4508 IdxVal &= ~(ElemsPerChunk - 1);
4510 SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
4511 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4514 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
4515 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4516 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4517 /// simple superregister reference. Idx is an index in the 128 bits
4518 /// we want. It need not be aligned to a 128-bit boundary. That makes
4519 /// lowering INSERT_VECTOR_ELT operations easier.
4520 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4521 SelectionDAG &DAG, SDLoc dl) {
4522 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4524 // For insertion into the zero index (low half) of a 256-bit vector, it is
4525 // more efficient to generate a blend with immediate instead of an insert*128.
4526 // We are still creating an INSERT_SUBVECTOR below with an undef node to
4527 // extend the subvector to the size of the result vector. Make sure that
4528 // we are not recursing on that node by checking for undef here.
4529 if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4530 Result.getOpcode() != ISD::UNDEF) {
4531 EVT ResultVT = Result.getValueType();
4532 SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4533 SDValue Undef = DAG.getUNDEF(ResultVT);
4534 SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4537 // The blend instruction, and therefore its mask, depend on the data type.
4538 MVT ScalarType = ResultVT.getVectorElementType().getSimpleVT();
4539 if (ScalarType.isFloatingPoint()) {
4540 // Choose either vblendps (float) or vblendpd (double).
4541 unsigned ScalarSize = ScalarType.getSizeInBits();
4542 assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4543 unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4544 SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4545 return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4548 const X86Subtarget &Subtarget =
4549 static_cast<const X86Subtarget &>(DAG.getSubtarget());
4551 // AVX2 is needed for 256-bit integer blend support.
4552 // Integers must be cast to 32-bit because there is only vpblendd;
4553 // vpblendw can't be used for this because it has a handicapped mask.
4555 // If we don't have AVX2, then cast to float. Using a wrong domain blend
4556 // is still more efficient than using the wrong domain vinsertf128 that
4557 // will be created by InsertSubVector().
4558 MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4560 SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4561 Result = DAG.getBitcast(CastVT, Result);
4562 Vec256 = DAG.getBitcast(CastVT, Vec256);
4563 Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4564 return DAG.getBitcast(ResultVT, Vec256);
4567 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4570 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4571 SelectionDAG &DAG, SDLoc dl) {
4572 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4573 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4576 /// Insert i1-subvector to i1-vector.
4577 static SDValue Insert1BitVector(SDValue Op, SelectionDAG &DAG) {
4580 SDValue Vec = Op.getOperand(0);
4581 SDValue SubVec = Op.getOperand(1);
4582 SDValue Idx = Op.getOperand(2);
4584 if (!isa<ConstantSDNode>(Idx))
4587 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
4588 if (IdxVal == 0 && Vec.isUndef()) // the operation is legal
4591 MVT OpVT = Op.getSimpleValueType();
4592 MVT SubVecVT = SubVec.getSimpleValueType();
4593 unsigned NumElems = OpVT.getVectorNumElements();
4594 unsigned SubVecNumElems = SubVecVT.getVectorNumElements();
4596 assert(IdxVal + SubVecNumElems <= NumElems &&
4597 IdxVal % SubVecVT.getSizeInBits() == 0 &&
4598 "Unexpected index value in INSERT_SUBVECTOR");
4600 // There are 3 possible cases:
4601 // 1. Subvector should be inserted in the lower part (IdxVal == 0)
4602 // 2. Subvector should be inserted in the upper part
4603 // (IdxVal + SubVecNumElems == NumElems)
4604 // 3. Subvector should be inserted in the middle (for example v2i1
4605 // to v16i1, index 2)
4607 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
4608 SDValue Undef = DAG.getUNDEF(OpVT);
4609 SDValue WideSubVec =
4610 DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef, SubVec, ZeroIdx);
4612 return DAG.getNode(X86ISD::VSHLI, dl, OpVT, WideSubVec,
4613 DAG.getConstant(IdxVal, dl, MVT::i8));
4615 if (ISD::isBuildVectorAllZeros(Vec.getNode())) {
4616 unsigned ShiftLeft = NumElems - SubVecNumElems;
4617 unsigned ShiftRight = NumElems - SubVecNumElems - IdxVal;
4618 WideSubVec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, WideSubVec,
4619 DAG.getConstant(ShiftLeft, dl, MVT::i8));
4620 return ShiftRight ? DAG.getNode(X86ISD::VSRLI, dl, OpVT, WideSubVec,
4621 DAG.getConstant(ShiftRight, dl, MVT::i8)) : WideSubVec;
4625 // Zero lower bits of the Vec
4626 SDValue ShiftBits = DAG.getConstant(SubVecNumElems, dl, MVT::i8);
4627 Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
4628 Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
4629 // Merge them together
4630 return DAG.getNode(ISD::OR, dl, OpVT, Vec, WideSubVec);
4633 // Simple case when we put subvector in the upper part
4634 if (IdxVal + SubVecNumElems == NumElems) {
4635 // Zero upper bits of the Vec
4636 WideSubVec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec,
4637 DAG.getConstant(IdxVal, dl, MVT::i8));
4638 SDValue ShiftBits = DAG.getConstant(SubVecNumElems, dl, MVT::i8);
4639 Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
4640 Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
4641 return DAG.getNode(ISD::OR, dl, OpVT, Vec, WideSubVec);
4643 // Subvector should be inserted in the middle - use shuffle
4644 SmallVector<int, 64> Mask;
4645 for (unsigned i = 0; i < NumElems; ++i)
4646 Mask.push_back(i >= IdxVal && i < IdxVal + SubVecNumElems ?
4648 return DAG.getVectorShuffle(OpVT, dl, WideSubVec, Vec, Mask);
4651 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4652 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4653 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4654 /// large BUILD_VECTORS.
4655 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4656 unsigned NumElems, SelectionDAG &DAG,
4658 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4659 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4662 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4663 unsigned NumElems, SelectionDAG &DAG,
4665 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4666 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4669 /// Returns a vector of specified type with all bits set.
4670 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4671 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4672 /// Then bitcast to their original type, ensuring they get CSE'd.
4673 static SDValue getOnesVector(EVT VT, const X86Subtarget *Subtarget,
4674 SelectionDAG &DAG, SDLoc dl) {
4675 assert(VT.isVector() && "Expected a vector type");
4677 SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4679 if (VT.is512BitVector()) {
4680 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4681 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4682 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4683 } else if (VT.is256BitVector()) {
4684 if (Subtarget->hasInt256()) { // AVX2
4685 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4686 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4688 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4689 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4691 } else if (VT.is128BitVector()) {
4692 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4694 llvm_unreachable("Unexpected vector type");
4696 return DAG.getBitcast(VT, Vec);
4699 /// Returns a vector_shuffle node for an unpackl operation.
4700 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4702 unsigned NumElems = VT.getVectorNumElements();
4703 SmallVector<int, 8> Mask;
4704 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4706 Mask.push_back(i + NumElems);
4708 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4711 /// Returns a vector_shuffle node for an unpackh operation.
4712 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4714 unsigned NumElems = VT.getVectorNumElements();
4715 SmallVector<int, 8> Mask;
4716 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4717 Mask.push_back(i + Half);
4718 Mask.push_back(i + NumElems + Half);
4720 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4723 /// Return a vector_shuffle of the specified vector of zero or undef vector.
4724 /// This produces a shuffle where the low element of V2 is swizzled into the
4725 /// zero/undef vector, landing at element Idx.
4726 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4727 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4729 const X86Subtarget *Subtarget,
4730 SelectionDAG &DAG) {
4731 MVT VT = V2.getSimpleValueType();
4733 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4734 unsigned NumElems = VT.getVectorNumElements();
4735 SmallVector<int, 16> MaskVec;
4736 for (unsigned i = 0; i != NumElems; ++i)
4737 // If this is the insertion idx, put the low elt of V2 here.
4738 MaskVec.push_back(i == Idx ? NumElems : i);
4739 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4742 /// Calculates the shuffle mask corresponding to the target-specific opcode.
4743 /// Returns true if the Mask could be calculated. Sets IsUnary to true if only
4744 /// uses one source. Note that this will set IsUnary for shuffles which use a
4745 /// single input multiple times, and in those cases it will
4746 /// adjust the mask to only have indices within that single input.
4747 static bool getTargetShuffleMask(SDNode *N, MVT VT, bool AllowSentinelZero,
4748 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4749 unsigned NumElems = VT.getVectorNumElements();
4753 bool IsFakeUnary = false;
4754 switch(N->getOpcode()) {
4755 case X86ISD::BLENDI:
4756 ImmN = N->getOperand(N->getNumOperands()-1);
4757 DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4760 ImmN = N->getOperand(N->getNumOperands()-1);
4761 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4762 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4764 case X86ISD::INSERTPS:
4765 ImmN = N->getOperand(N->getNumOperands()-1);
4766 DecodeINSERTPSMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4767 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4769 case X86ISD::UNPCKH:
4770 DecodeUNPCKHMask(VT, Mask);
4771 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4773 case X86ISD::UNPCKL:
4774 DecodeUNPCKLMask(VT, Mask);
4775 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4777 case X86ISD::MOVHLPS:
4778 DecodeMOVHLPSMask(NumElems, Mask);
4779 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4781 case X86ISD::MOVLHPS:
4782 DecodeMOVLHPSMask(NumElems, Mask);
4783 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4785 case X86ISD::PALIGNR:
4786 ImmN = N->getOperand(N->getNumOperands()-1);
4787 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4789 case X86ISD::PSHUFD:
4790 case X86ISD::VPERMILPI:
4791 ImmN = N->getOperand(N->getNumOperands()-1);
4792 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4795 case X86ISD::PSHUFHW:
4796 ImmN = N->getOperand(N->getNumOperands()-1);
4797 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4800 case X86ISD::PSHUFLW:
4801 ImmN = N->getOperand(N->getNumOperands()-1);
4802 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4805 case X86ISD::PSHUFB: {
4807 SDValue MaskNode = N->getOperand(1);
4808 while (MaskNode->getOpcode() == ISD::BITCAST)
4809 MaskNode = MaskNode->getOperand(0);
4811 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4812 // If we have a build-vector, then things are easy.
4813 MVT VT = MaskNode.getSimpleValueType();
4814 assert(VT.isVector() &&
4815 "Can't produce a non-vector with a build_vector!");
4816 if (!VT.isInteger())
4819 int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4821 SmallVector<uint64_t, 32> RawMask;
4822 for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4823 SDValue Op = MaskNode->getOperand(i);
4824 if (Op->getOpcode() == ISD::UNDEF) {
4825 RawMask.push_back((uint64_t)SM_SentinelUndef);
4828 auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4831 APInt MaskElement = CN->getAPIntValue();
4833 // We now have to decode the element which could be any integer size and
4834 // extract each byte of it.
4835 for (int j = 0; j < NumBytesPerElement; ++j) {
4836 // Note that this is x86 and so always little endian: the low byte is
4837 // the first byte of the mask.
4838 RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4839 MaskElement = MaskElement.lshr(8);
4842 DecodePSHUFBMask(RawMask, Mask);
4846 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4850 SDValue Ptr = MaskLoad->getBasePtr();
4851 if (Ptr->getOpcode() == X86ISD::Wrapper ||
4852 Ptr->getOpcode() == X86ISD::WrapperRIP)
4853 Ptr = Ptr->getOperand(0);
4855 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4856 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4859 if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4860 DecodePSHUFBMask(C, Mask);
4866 case X86ISD::VPERMI:
4867 ImmN = N->getOperand(N->getNumOperands()-1);
4868 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4873 DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4875 case X86ISD::VPERM2X128:
4876 ImmN = N->getOperand(N->getNumOperands()-1);
4877 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4878 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4880 case X86ISD::MOVSLDUP:
4881 DecodeMOVSLDUPMask(VT, Mask);
4884 case X86ISD::MOVSHDUP:
4885 DecodeMOVSHDUPMask(VT, Mask);
4888 case X86ISD::MOVDDUP:
4889 DecodeMOVDDUPMask(VT, Mask);
4892 case X86ISD::MOVLHPD:
4893 case X86ISD::MOVLPD:
4894 case X86ISD::MOVLPS:
4895 // Not yet implemented
4897 case X86ISD::VPERMV: {
4899 SDValue MaskNode = N->getOperand(0);
4900 while (MaskNode->getOpcode() == ISD::BITCAST)
4901 MaskNode = MaskNode->getOperand(0);
4903 unsigned MaskLoBits = Log2_64(VT.getVectorNumElements());
4904 SmallVector<uint64_t, 32> RawMask;
4905 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4906 // If we have a build-vector, then things are easy.
4907 assert(MaskNode.getSimpleValueType().isInteger() &&
4908 MaskNode.getSimpleValueType().getVectorNumElements() ==
4909 VT.getVectorNumElements());
4911 for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4912 SDValue Op = MaskNode->getOperand(i);
4913 if (Op->getOpcode() == ISD::UNDEF)
4914 RawMask.push_back((uint64_t)SM_SentinelUndef);
4915 else if (isa<ConstantSDNode>(Op)) {
4916 APInt MaskElement = cast<ConstantSDNode>(Op)->getAPIntValue();
4917 RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4921 DecodeVPERMVMask(RawMask, Mask);
4924 if (MaskNode->getOpcode() == X86ISD::VBROADCAST) {
4925 unsigned NumEltsInMask = MaskNode->getNumOperands();
4926 MaskNode = MaskNode->getOperand(0);
4927 if (auto *CN = dyn_cast<ConstantSDNode>(MaskNode)) {
4928 APInt MaskEltValue = CN->getAPIntValue();
4929 for (unsigned i = 0; i < NumEltsInMask; ++i)
4930 RawMask.push_back(MaskEltValue.getLoBits(MaskLoBits).getZExtValue());
4931 DecodeVPERMVMask(RawMask, Mask);
4934 // It may be a scalar load
4937 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4941 SDValue Ptr = MaskLoad->getBasePtr();
4942 if (Ptr->getOpcode() == X86ISD::Wrapper ||
4943 Ptr->getOpcode() == X86ISD::WrapperRIP)
4944 Ptr = Ptr->getOperand(0);
4946 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4947 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4950 if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4951 DecodeVPERMVMask(C, VT, Mask);
4956 case X86ISD::VPERMV3: {
4958 SDValue MaskNode = N->getOperand(1);
4959 while (MaskNode->getOpcode() == ISD::BITCAST)
4960 MaskNode = MaskNode->getOperand(1);
4962 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4963 // If we have a build-vector, then things are easy.
4964 assert(MaskNode.getSimpleValueType().isInteger() &&
4965 MaskNode.getSimpleValueType().getVectorNumElements() ==
4966 VT.getVectorNumElements());
4968 SmallVector<uint64_t, 32> RawMask;
4969 unsigned MaskLoBits = Log2_64(VT.getVectorNumElements()*2);
4971 for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4972 SDValue Op = MaskNode->getOperand(i);
4973 if (Op->getOpcode() == ISD::UNDEF)
4974 RawMask.push_back((uint64_t)SM_SentinelUndef);
4976 auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4979 APInt MaskElement = CN->getAPIntValue();
4980 RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4983 DecodeVPERMV3Mask(RawMask, Mask);
4987 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4991 SDValue Ptr = MaskLoad->getBasePtr();
4992 if (Ptr->getOpcode() == X86ISD::Wrapper ||
4993 Ptr->getOpcode() == X86ISD::WrapperRIP)
4994 Ptr = Ptr->getOperand(0);
4996 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4997 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
5000 if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
5001 DecodeVPERMV3Mask(C, VT, Mask);
5006 default: llvm_unreachable("unknown target shuffle node");
5009 // Empty mask indicates the decode failed.
5013 // Check if we're getting a shuffle mask with zero'd elements.
5014 if (!AllowSentinelZero)
5015 if (std::any_of(Mask.begin(), Mask.end(),
5016 [](int M){ return M == SM_SentinelZero; }))
5019 // If we have a fake unary shuffle, the shuffle mask is spread across two
5020 // inputs that are actually the same node. Re-map the mask to always point
5021 // into the first input.
5024 if (M >= (int)Mask.size())
5030 /// Returns the scalar element that will make up the ith
5031 /// element of the result of the vector shuffle.
5032 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5035 return SDValue(); // Limit search depth.
5037 SDValue V = SDValue(N, 0);
5038 EVT VT = V.getValueType();
5039 unsigned Opcode = V.getOpcode();
5041 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5042 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5043 int Elt = SV->getMaskElt(Index);
5046 return DAG.getUNDEF(VT.getVectorElementType());
5048 unsigned NumElems = VT.getVectorNumElements();
5049 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5050 : SV->getOperand(1);
5051 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5054 // Recurse into target specific vector shuffles to find scalars.
5055 if (isTargetShuffle(Opcode)) {
5056 MVT ShufVT = V.getSimpleValueType();
5057 int NumElems = (int)ShufVT.getVectorNumElements();
5058 SmallVector<int, 16> ShuffleMask;
5061 if (!getTargetShuffleMask(N, ShufVT, false, ShuffleMask, IsUnary))
5064 int Elt = ShuffleMask[Index];
5065 if (Elt == SM_SentinelUndef)
5066 return DAG.getUNDEF(ShufVT.getVectorElementType());
5068 assert(0 <= Elt && Elt < (2*NumElems) && "Shuffle index out of range");
5069 SDValue NewV = (Elt < NumElems) ? N->getOperand(0) : N->getOperand(1);
5070 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5074 // Actual nodes that may contain scalar elements
5075 if (Opcode == ISD::BITCAST) {
5076 V = V.getOperand(0);
5077 EVT SrcVT = V.getValueType();
5078 unsigned NumElems = VT.getVectorNumElements();
5080 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5084 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5085 return (Index == 0) ? V.getOperand(0)
5086 : DAG.getUNDEF(VT.getVectorElementType());
5088 if (V.getOpcode() == ISD::BUILD_VECTOR)
5089 return V.getOperand(Index);
5094 /// Custom lower build_vector of v16i8.
5095 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5096 unsigned NumNonZero, unsigned NumZero,
5098 const X86Subtarget* Subtarget,
5099 const TargetLowering &TLI) {
5107 // SSE4.1 - use PINSRB to insert each byte directly.
5108 if (Subtarget->hasSSE41()) {
5109 for (unsigned i = 0; i < 16; ++i) {
5110 bool isNonZero = (NonZeros & (1 << i)) != 0;
5114 V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
5116 V = DAG.getUNDEF(MVT::v16i8);
5119 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5120 MVT::v16i8, V, Op.getOperand(i),
5121 DAG.getIntPtrConstant(i, dl));
5128 // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
5129 for (unsigned i = 0; i < 16; ++i) {
5130 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5131 if (ThisIsNonZero && First) {
5133 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5135 V = DAG.getUNDEF(MVT::v8i16);
5140 SDValue ThisElt, LastElt;
5141 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5142 if (LastIsNonZero) {
5143 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5144 MVT::i16, Op.getOperand(i-1));
5146 if (ThisIsNonZero) {
5147 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5148 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5149 ThisElt, DAG.getConstant(8, dl, MVT::i8));
5151 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5155 if (ThisElt.getNode())
5156 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5157 DAG.getIntPtrConstant(i/2, dl));
5161 return DAG.getBitcast(MVT::v16i8, V);
5164 /// Custom lower build_vector of v8i16.
5165 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5166 unsigned NumNonZero, unsigned NumZero,
5168 const X86Subtarget* Subtarget,
5169 const TargetLowering &TLI) {
5176 for (unsigned i = 0; i < 8; ++i) {
5177 bool isNonZero = (NonZeros & (1 << i)) != 0;
5181 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5183 V = DAG.getUNDEF(MVT::v8i16);
5186 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5187 MVT::v8i16, V, Op.getOperand(i),
5188 DAG.getIntPtrConstant(i, dl));
5195 /// Custom lower build_vector of v4i32 or v4f32.
5196 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
5197 const X86Subtarget *Subtarget,
5198 const TargetLowering &TLI) {
5199 // Find all zeroable elements.
5200 std::bitset<4> Zeroable;
5201 for (int i=0; i < 4; ++i) {
5202 SDValue Elt = Op->getOperand(i);
5203 Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
5205 assert(Zeroable.size() - Zeroable.count() > 1 &&
5206 "We expect at least two non-zero elements!");
5208 // We only know how to deal with build_vector nodes where elements are either
5209 // zeroable or extract_vector_elt with constant index.
5210 SDValue FirstNonZero;
5211 unsigned FirstNonZeroIdx;
5212 for (unsigned i=0; i < 4; ++i) {
5215 SDValue Elt = Op->getOperand(i);
5216 if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5217 !isa<ConstantSDNode>(Elt.getOperand(1)))
5219 // Make sure that this node is extracting from a 128-bit vector.
5220 MVT VT = Elt.getOperand(0).getSimpleValueType();
5221 if (!VT.is128BitVector())
5223 if (!FirstNonZero.getNode()) {
5225 FirstNonZeroIdx = i;
5229 assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
5230 SDValue V1 = FirstNonZero.getOperand(0);
5231 MVT VT = V1.getSimpleValueType();
5233 // See if this build_vector can be lowered as a blend with zero.
5235 unsigned EltMaskIdx, EltIdx;
5237 for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
5238 if (Zeroable[EltIdx]) {
5239 // The zero vector will be on the right hand side.
5240 Mask[EltIdx] = EltIdx+4;
5244 Elt = Op->getOperand(EltIdx);
5245 // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
5246 EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
5247 if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
5249 Mask[EltIdx] = EltIdx;
5253 // Let the shuffle legalizer deal with blend operations.
5254 SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
5255 if (V1.getSimpleValueType() != VT)
5256 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
5257 return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
5260 // See if we can lower this build_vector to a INSERTPS.
5261 if (!Subtarget->hasSSE41())
5264 SDValue V2 = Elt.getOperand(0);
5265 if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
5268 bool CanFold = true;
5269 for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
5273 SDValue Current = Op->getOperand(i);
5274 SDValue SrcVector = Current->getOperand(0);
5277 CanFold = SrcVector == V1 &&
5278 cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
5284 assert(V1.getNode() && "Expected at least two non-zero elements!");
5285 if (V1.getSimpleValueType() != MVT::v4f32)
5286 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
5287 if (V2.getSimpleValueType() != MVT::v4f32)
5288 V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
5290 // Ok, we can emit an INSERTPS instruction.
5291 unsigned ZMask = Zeroable.to_ulong();
5293 unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
5294 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
5296 SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
5297 DAG.getIntPtrConstant(InsertPSMask, DL));
5298 return DAG.getBitcast(VT, Result);
5301 /// Return a vector logical shift node.
5302 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5303 unsigned NumBits, SelectionDAG &DAG,
5304 const TargetLowering &TLI, SDLoc dl) {
5305 assert(VT.is128BitVector() && "Unknown type for VShift");
5306 MVT ShVT = MVT::v2i64;
5307 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5308 SrcOp = DAG.getBitcast(ShVT, SrcOp);
5309 MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
5310 assert(NumBits % 8 == 0 && "Only support byte sized shifts");
5311 SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
5312 return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
5316 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5318 // Check if the scalar load can be widened into a vector load. And if
5319 // the address is "base + cst" see if the cst can be "absorbed" into
5320 // the shuffle mask.
5321 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5322 SDValue Ptr = LD->getBasePtr();
5323 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5325 EVT PVT = LD->getValueType(0);
5326 if (PVT != MVT::i32 && PVT != MVT::f32)
5331 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5332 FI = FINode->getIndex();
5334 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5335 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5336 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5337 Offset = Ptr.getConstantOperandVal(1);
5338 Ptr = Ptr.getOperand(0);
5343 // FIXME: 256-bit vector instructions don't require a strict alignment,
5344 // improve this code to support it better.
5345 unsigned RequiredAlign = VT.getSizeInBits()/8;
5346 SDValue Chain = LD->getChain();
5347 // Make sure the stack object alignment is at least 16 or 32.
5348 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5349 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5350 if (MFI->isFixedObjectIndex(FI)) {
5351 // Can't change the alignment. FIXME: It's possible to compute
5352 // the exact stack offset and reference FI + adjust offset instead.
5353 // If someone *really* cares about this. That's the way to implement it.
5356 MFI->setObjectAlignment(FI, RequiredAlign);
5360 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5361 // Ptr + (Offset & ~15).
5364 if ((Offset % RequiredAlign) & 3)
5366 int64_t StartOffset = Offset & ~int64_t(RequiredAlign - 1);
5369 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5370 DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
5373 int EltNo = (Offset - StartOffset) >> 2;
5374 unsigned NumElems = VT.getVectorNumElements();
5376 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5377 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5378 LD->getPointerInfo().getWithOffset(StartOffset),
5379 false, false, false, 0);
5381 SmallVector<int, 8> Mask(NumElems, EltNo);
5383 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5389 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
5390 /// elements can be replaced by a single large load which has the same value as
5391 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
5393 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5395 /// FIXME: we'd also like to handle the case where the last elements are zero
5396 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5397 /// There's even a handy isZeroNode for that purpose.
5398 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
5399 SDLoc &DL, SelectionDAG &DAG,
5400 bool isAfterLegalize) {
5401 unsigned NumElems = Elts.size();
5403 LoadSDNode *LDBase = nullptr;
5404 unsigned LastLoadedElt = -1U;
5406 // For each element in the initializer, see if we've found a load or an undef.
5407 // If we don't find an initial load element, or later load elements are
5408 // non-consecutive, bail out.
5409 for (unsigned i = 0; i < NumElems; ++i) {
5410 SDValue Elt = Elts[i];
5411 // Look through a bitcast.
5412 if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
5413 Elt = Elt.getOperand(0);
5414 if (!Elt.getNode() ||
5415 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5418 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5420 LDBase = cast<LoadSDNode>(Elt.getNode());
5424 if (Elt.getOpcode() == ISD::UNDEF)
5427 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5428 EVT LdVT = Elt.getValueType();
5429 // Each loaded element must be the correct fractional portion of the
5430 // requested vector load.
5431 if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
5433 if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
5438 // If we have found an entire vector of loads and undefs, then return a large
5439 // load of the entire vector width starting at the base pointer. If we found
5440 // consecutive loads for the low half, generate a vzext_load node.
5441 if (LastLoadedElt == NumElems - 1) {
5442 assert(LDBase && "Did not find base load for merging consecutive loads");
5443 EVT EltVT = LDBase->getValueType(0);
5444 // Ensure that the input vector size for the merged loads matches the
5445 // cumulative size of the input elements.
5446 if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5449 if (isAfterLegalize &&
5450 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5453 SDValue NewLd = SDValue();
5455 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5456 LDBase->getPointerInfo(), LDBase->isVolatile(),
5457 LDBase->isNonTemporal(), LDBase->isInvariant(),
5458 LDBase->getAlignment());
5460 if (LDBase->hasAnyUseOfValue(1)) {
5461 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5463 SDValue(NewLd.getNode(), 1));
5464 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5465 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5466 SDValue(NewLd.getNode(), 1));
5472 //TODO: The code below fires only for for loading the low v2i32 / v2f32
5473 //of a v4i32 / v4f32. It's probably worth generalizing.
5474 EVT EltVT = VT.getVectorElementType();
5475 if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5476 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5477 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5478 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5480 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5481 LDBase->getPointerInfo(),
5482 LDBase->getAlignment(),
5483 false/*isVolatile*/, true/*ReadMem*/,
5486 // Make sure the newly-created LOAD is in the same position as LDBase in
5487 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5488 // update uses of LDBase's output chain to use the TokenFactor.
5489 if (LDBase->hasAnyUseOfValue(1)) {
5490 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5491 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5492 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5493 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5494 SDValue(ResNode.getNode(), 1));
5497 return DAG.getBitcast(VT, ResNode);
5502 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5503 /// to generate a splat value for the following cases:
5504 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5505 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5506 /// a scalar load, or a constant.
5507 /// The VBROADCAST node is returned when a pattern is found,
5508 /// or SDValue() otherwise.
5509 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5510 SelectionDAG &DAG) {
5511 // VBROADCAST requires AVX.
5512 // TODO: Splats could be generated for non-AVX CPUs using SSE
5513 // instructions, but there's less potential gain for only 128-bit vectors.
5514 if (!Subtarget->hasAVX())
5517 MVT VT = Op.getSimpleValueType();
5520 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5521 "Unsupported vector type for broadcast.");
5526 switch (Op.getOpcode()) {
5528 // Unknown pattern found.
5531 case ISD::BUILD_VECTOR: {
5532 auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5533 BitVector UndefElements;
5534 SDValue Splat = BVOp->getSplatValue(&UndefElements);
5536 // We need a splat of a single value to use broadcast, and it doesn't
5537 // make any sense if the value is only in one element of the vector.
5538 if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5542 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5543 Ld.getOpcode() == ISD::ConstantFP);
5545 // Make sure that all of the users of a non-constant load are from the
5546 // BUILD_VECTOR node.
5547 if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5552 case ISD::VECTOR_SHUFFLE: {
5553 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5555 // Shuffles must have a splat mask where the first element is
5557 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5560 SDValue Sc = Op.getOperand(0);
5561 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5562 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5564 if (!Subtarget->hasInt256())
5567 // Use the register form of the broadcast instruction available on AVX2.
5568 if (VT.getSizeInBits() >= 256)
5569 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5570 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5573 Ld = Sc.getOperand(0);
5574 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5575 Ld.getOpcode() == ISD::ConstantFP);
5577 // The scalar_to_vector node and the suspected
5578 // load node must have exactly one user.
5579 // Constants may have multiple users.
5581 // AVX-512 has register version of the broadcast
5582 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5583 Ld.getValueType().getSizeInBits() >= 32;
5584 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5591 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5592 bool IsGE256 = (VT.getSizeInBits() >= 256);
5594 // When optimizing for size, generate up to 5 extra bytes for a broadcast
5595 // instruction to save 8 or more bytes of constant pool data.
5596 // TODO: If multiple splats are generated to load the same constant,
5597 // it may be detrimental to overall size. There needs to be a way to detect
5598 // that condition to know if this is truly a size win.
5599 bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
5601 // Handle broadcasting a single constant scalar from the constant pool
5603 // On Sandybridge (no AVX2), it is still better to load a constant vector
5604 // from the constant pool and not to broadcast it from a scalar.
5605 // But override that restriction when optimizing for size.
5606 // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5607 if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5608 EVT CVT = Ld.getValueType();
5609 assert(!CVT.isVector() && "Must not broadcast a vector type");
5611 // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5612 // For size optimization, also splat v2f64 and v2i64, and for size opt
5613 // with AVX2, also splat i8 and i16.
5614 // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5615 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5616 (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5617 const Constant *C = nullptr;
5618 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5619 C = CI->getConstantIntValue();
5620 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5621 C = CF->getConstantFPValue();
5623 assert(C && "Invalid constant type");
5625 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5627 DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5628 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5630 CVT, dl, DAG.getEntryNode(), CP,
5631 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
5632 false, false, Alignment);
5634 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5638 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5640 // Handle AVX2 in-register broadcasts.
5641 if (!IsLoad && Subtarget->hasInt256() &&
5642 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5643 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5645 // The scalar source must be a normal load.
5649 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5650 (Subtarget->hasVLX() && ScalarSize == 64))
5651 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5653 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5654 // double since there is no vbroadcastsd xmm
5655 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5656 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5657 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5660 // Unsupported broadcast.
5664 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5665 /// underlying vector and index.
5667 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5669 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5671 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5672 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5675 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5677 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5679 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5680 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5683 // In this case the vector is the extract_subvector expression and the index
5684 // is 2, as specified by the shuffle.
5685 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5686 SDValue ShuffleVec = SVOp->getOperand(0);
5687 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5688 assert(ShuffleVecVT.getVectorElementType() ==
5689 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5691 int ShuffleIdx = SVOp->getMaskElt(Idx);
5692 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5693 ExtractedFromVec = ShuffleVec;
5699 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5700 MVT VT = Op.getSimpleValueType();
5702 // Skip if insert_vec_elt is not supported.
5703 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5704 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5708 unsigned NumElems = Op.getNumOperands();
5712 SmallVector<unsigned, 4> InsertIndices;
5713 SmallVector<int, 8> Mask(NumElems, -1);
5715 for (unsigned i = 0; i != NumElems; ++i) {
5716 unsigned Opc = Op.getOperand(i).getOpcode();
5718 if (Opc == ISD::UNDEF)
5721 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5722 // Quit if more than 1 elements need inserting.
5723 if (InsertIndices.size() > 1)
5726 InsertIndices.push_back(i);
5730 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5731 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5732 // Quit if non-constant index.
5733 if (!isa<ConstantSDNode>(ExtIdx))
5735 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5737 // Quit if extracted from vector of different type.
5738 if (ExtractedFromVec.getValueType() != VT)
5741 if (!VecIn1.getNode())
5742 VecIn1 = ExtractedFromVec;
5743 else if (VecIn1 != ExtractedFromVec) {
5744 if (!VecIn2.getNode())
5745 VecIn2 = ExtractedFromVec;
5746 else if (VecIn2 != ExtractedFromVec)
5747 // Quit if more than 2 vectors to shuffle
5751 if (ExtractedFromVec == VecIn1)
5753 else if (ExtractedFromVec == VecIn2)
5754 Mask[i] = Idx + NumElems;
5757 if (!VecIn1.getNode())
5760 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5761 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5762 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5763 unsigned Idx = InsertIndices[i];
5764 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5765 DAG.getIntPtrConstant(Idx, DL));
5771 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
5772 assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5773 Op.getScalarValueSizeInBits() == 1 &&
5774 "Can not convert non-constant vector");
5775 uint64_t Immediate = 0;
5776 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5777 SDValue In = Op.getOperand(idx);
5778 if (In.getOpcode() != ISD::UNDEF)
5779 Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5783 MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5784 return DAG.getConstant(Immediate, dl, VT);
5786 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5788 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5790 MVT VT = Op.getSimpleValueType();
5791 assert((VT.getVectorElementType() == MVT::i1) &&
5792 "Unexpected type in LowerBUILD_VECTORvXi1!");
5795 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5796 SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5797 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5798 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5801 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5802 SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5803 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5804 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5807 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5808 SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
5809 if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5810 return DAG.getBitcast(VT, Imm);
5811 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5812 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5813 DAG.getIntPtrConstant(0, dl));
5816 // Vector has one or more non-const elements
5817 uint64_t Immediate = 0;
5818 SmallVector<unsigned, 16> NonConstIdx;
5819 bool IsSplat = true;
5820 bool HasConstElts = false;
5822 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5823 SDValue In = Op.getOperand(idx);
5824 if (In.getOpcode() == ISD::UNDEF)
5826 if (!isa<ConstantSDNode>(In))
5827 NonConstIdx.push_back(idx);
5829 Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5830 HasConstElts = true;
5834 else if (In != Op.getOperand(SplatIdx))
5838 // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5840 return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5841 DAG.getConstant(1, dl, VT),
5842 DAG.getConstant(0, dl, VT));
5844 // insert elements one by one
5848 MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5849 Imm = DAG.getConstant(Immediate, dl, ImmVT);
5851 else if (HasConstElts)
5852 Imm = DAG.getConstant(0, dl, VT);
5854 Imm = DAG.getUNDEF(VT);
5855 if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5856 DstVec = DAG.getBitcast(VT, Imm);
5858 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5859 DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5860 DAG.getIntPtrConstant(0, dl));
5863 for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5864 unsigned InsertIdx = NonConstIdx[i];
5865 DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5866 Op.getOperand(InsertIdx),
5867 DAG.getIntPtrConstant(InsertIdx, dl));
5872 /// \brief Return true if \p N implements a horizontal binop and return the
5873 /// operands for the horizontal binop into V0 and V1.
5875 /// This is a helper function of LowerToHorizontalOp().
5876 /// This function checks that the build_vector \p N in input implements a
5877 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5878 /// operation to match.
5879 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5880 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5881 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5884 /// This function only analyzes elements of \p N whose indices are
5885 /// in range [BaseIdx, LastIdx).
5886 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5888 unsigned BaseIdx, unsigned LastIdx,
5889 SDValue &V0, SDValue &V1) {
5890 EVT VT = N->getValueType(0);
5892 assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5893 assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5894 "Invalid Vector in input!");
5896 bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5897 bool CanFold = true;
5898 unsigned ExpectedVExtractIdx = BaseIdx;
5899 unsigned NumElts = LastIdx - BaseIdx;
5900 V0 = DAG.getUNDEF(VT);
5901 V1 = DAG.getUNDEF(VT);
5903 // Check if N implements a horizontal binop.
5904 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5905 SDValue Op = N->getOperand(i + BaseIdx);
5908 if (Op->getOpcode() == ISD::UNDEF) {
5909 // Update the expected vector extract index.
5910 if (i * 2 == NumElts)
5911 ExpectedVExtractIdx = BaseIdx;
5912 ExpectedVExtractIdx += 2;
5916 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5921 SDValue Op0 = Op.getOperand(0);
5922 SDValue Op1 = Op.getOperand(1);
5924 // Try to match the following pattern:
5925 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5926 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5927 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5928 Op0.getOperand(0) == Op1.getOperand(0) &&
5929 isa<ConstantSDNode>(Op0.getOperand(1)) &&
5930 isa<ConstantSDNode>(Op1.getOperand(1)));
5934 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5935 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5937 if (i * 2 < NumElts) {
5938 if (V0.getOpcode() == ISD::UNDEF) {
5939 V0 = Op0.getOperand(0);
5940 if (V0.getValueType() != VT)
5944 if (V1.getOpcode() == ISD::UNDEF) {
5945 V1 = Op0.getOperand(0);
5946 if (V1.getValueType() != VT)
5949 if (i * 2 == NumElts)
5950 ExpectedVExtractIdx = BaseIdx;
5953 SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5954 if (I0 == ExpectedVExtractIdx)
5955 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5956 else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5957 // Try to match the following dag sequence:
5958 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5959 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5963 ExpectedVExtractIdx += 2;
5969 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5970 /// a concat_vector.
5972 /// This is a helper function of LowerToHorizontalOp().
5973 /// This function expects two 256-bit vectors called V0 and V1.
5974 /// At first, each vector is split into two separate 128-bit vectors.
5975 /// Then, the resulting 128-bit vectors are used to implement two
5976 /// horizontal binary operations.
5978 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5980 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5981 /// the two new horizontal binop.
5982 /// When Mode is set, the first horizontal binop dag node would take as input
5983 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5984 /// horizontal binop dag node would take as input the lower 128-bit of V1
5985 /// and the upper 128-bit of V1.
5987 /// HADD V0_LO, V0_HI
5988 /// HADD V1_LO, V1_HI
5990 /// Otherwise, the first horizontal binop dag node takes as input the lower
5991 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5992 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5994 /// HADD V0_LO, V1_LO
5995 /// HADD V0_HI, V1_HI
5997 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5998 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5999 /// the upper 128-bits of the result.
6000 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6001 SDLoc DL, SelectionDAG &DAG,
6002 unsigned X86Opcode, bool Mode,
6003 bool isUndefLO, bool isUndefHI) {
6004 EVT VT = V0.getValueType();
6005 assert(VT.is256BitVector() && VT == V1.getValueType() &&
6006 "Invalid nodes in input!");
6008 unsigned NumElts = VT.getVectorNumElements();
6009 SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6010 SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6011 SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6012 SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6013 EVT NewVT = V0_LO.getValueType();
6015 SDValue LO = DAG.getUNDEF(NewVT);
6016 SDValue HI = DAG.getUNDEF(NewVT);
6019 // Don't emit a horizontal binop if the result is expected to be UNDEF.
6020 if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6021 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6022 if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6023 HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6025 // Don't emit a horizontal binop if the result is expected to be UNDEF.
6026 if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6027 V1_LO->getOpcode() != ISD::UNDEF))
6028 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6030 if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6031 V1_HI->getOpcode() != ISD::UNDEF))
6032 HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6035 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6038 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
6040 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
6041 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6042 MVT VT = BV->getSimpleValueType(0);
6043 if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
6044 (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
6048 unsigned NumElts = VT.getVectorNumElements();
6049 SDValue InVec0 = DAG.getUNDEF(VT);
6050 SDValue InVec1 = DAG.getUNDEF(VT);
6052 assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6053 VT == MVT::v2f64) && "build_vector with an invalid type found!");
6055 // Odd-numbered elements in the input build vector are obtained from
6056 // adding two integer/float elements.
6057 // Even-numbered elements in the input build vector are obtained from
6058 // subtracting two integer/float elements.
6059 unsigned ExpectedOpcode = ISD::FSUB;
6060 unsigned NextExpectedOpcode = ISD::FADD;
6061 bool AddFound = false;
6062 bool SubFound = false;
6064 for (unsigned i = 0, e = NumElts; i != e; ++i) {
6065 SDValue Op = BV->getOperand(i);
6067 // Skip 'undef' values.
6068 unsigned Opcode = Op.getOpcode();
6069 if (Opcode == ISD::UNDEF) {
6070 std::swap(ExpectedOpcode, NextExpectedOpcode);
6074 // Early exit if we found an unexpected opcode.
6075 if (Opcode != ExpectedOpcode)
6078 SDValue Op0 = Op.getOperand(0);
6079 SDValue Op1 = Op.getOperand(1);
6081 // Try to match the following pattern:
6082 // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6083 // Early exit if we cannot match that sequence.
6084 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6085 Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6086 !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6087 !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6088 Op0.getOperand(1) != Op1.getOperand(1))
6091 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6095 // We found a valid add/sub node. Update the information accordingly.
6101 // Update InVec0 and InVec1.
6102 if (InVec0.getOpcode() == ISD::UNDEF) {
6103 InVec0 = Op0.getOperand(0);
6104 if (InVec0.getSimpleValueType() != VT)
6107 if (InVec1.getOpcode() == ISD::UNDEF) {
6108 InVec1 = Op1.getOperand(0);
6109 if (InVec1.getSimpleValueType() != VT)
6113 // Make sure that operands in input to each add/sub node always
6114 // come from a same pair of vectors.
6115 if (InVec0 != Op0.getOperand(0)) {
6116 if (ExpectedOpcode == ISD::FSUB)
6119 // FADD is commutable. Try to commute the operands
6120 // and then test again.
6121 std::swap(Op0, Op1);
6122 if (InVec0 != Op0.getOperand(0))
6126 if (InVec1 != Op1.getOperand(0))
6129 // Update the pair of expected opcodes.
6130 std::swap(ExpectedOpcode, NextExpectedOpcode);
6133 // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
6134 if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6135 InVec1.getOpcode() != ISD::UNDEF)
6136 return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
6141 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
6142 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
6143 const X86Subtarget *Subtarget,
6144 SelectionDAG &DAG) {
6145 MVT VT = BV->getSimpleValueType(0);
6146 unsigned NumElts = VT.getVectorNumElements();
6147 unsigned NumUndefsLO = 0;
6148 unsigned NumUndefsHI = 0;
6149 unsigned Half = NumElts/2;
6151 // Count the number of UNDEF operands in the build_vector in input.
6152 for (unsigned i = 0, e = Half; i != e; ++i)
6153 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6156 for (unsigned i = Half, e = NumElts; i != e; ++i)
6157 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6160 // Early exit if this is either a build_vector of all UNDEFs or all the
6161 // operands but one are UNDEF.
6162 if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6166 SDValue InVec0, InVec1;
6167 if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6168 // Try to match an SSE3 float HADD/HSUB.
6169 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6170 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6172 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6173 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6174 } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6175 // Try to match an SSSE3 integer HADD/HSUB.
6176 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6177 return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6179 if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6180 return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6183 if (!Subtarget->hasAVX())
6186 if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6187 // Try to match an AVX horizontal add/sub of packed single/double
6188 // precision floating point values from 256-bit vectors.
6189 SDValue InVec2, InVec3;
6190 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6191 isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6192 ((InVec0.getOpcode() == ISD::UNDEF ||
6193 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6194 ((InVec1.getOpcode() == ISD::UNDEF ||
6195 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6196 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6198 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6199 isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6200 ((InVec0.getOpcode() == ISD::UNDEF ||
6201 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6202 ((InVec1.getOpcode() == ISD::UNDEF ||
6203 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6204 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6205 } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6206 // Try to match an AVX2 horizontal add/sub of signed integers.
6207 SDValue InVec2, InVec3;
6209 bool CanFold = true;
6211 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6212 isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6213 ((InVec0.getOpcode() == ISD::UNDEF ||
6214 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6215 ((InVec1.getOpcode() == ISD::UNDEF ||
6216 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6217 X86Opcode = X86ISD::HADD;
6218 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6219 isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6220 ((InVec0.getOpcode() == ISD::UNDEF ||
6221 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6222 ((InVec1.getOpcode() == ISD::UNDEF ||
6223 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6224 X86Opcode = X86ISD::HSUB;
6229 // Fold this build_vector into a single horizontal add/sub.
6230 // Do this only if the target has AVX2.
6231 if (Subtarget->hasAVX2())
6232 return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6234 // Do not try to expand this build_vector into a pair of horizontal
6235 // add/sub if we can emit a pair of scalar add/sub.
6236 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6239 // Convert this build_vector into a pair of horizontal binop followed by
6241 bool isUndefLO = NumUndefsLO == Half;
6242 bool isUndefHI = NumUndefsHI == Half;
6243 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6244 isUndefLO, isUndefHI);
6248 if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6249 VT == MVT::v16i16) && Subtarget->hasAVX()) {
6251 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6252 X86Opcode = X86ISD::HADD;
6253 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6254 X86Opcode = X86ISD::HSUB;
6255 else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6256 X86Opcode = X86ISD::FHADD;
6257 else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6258 X86Opcode = X86ISD::FHSUB;
6262 // Don't try to expand this build_vector into a pair of horizontal add/sub
6263 // if we can simply emit a pair of scalar add/sub.
6264 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6267 // Convert this build_vector into two horizontal add/sub followed by
6269 bool isUndefLO = NumUndefsLO == Half;
6270 bool isUndefHI = NumUndefsHI == Half;
6271 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6272 isUndefLO, isUndefHI);
6279 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6282 MVT VT = Op.getSimpleValueType();
6283 MVT ExtVT = VT.getVectorElementType();
6284 unsigned NumElems = Op.getNumOperands();
6286 // Generate vectors for predicate vectors.
6287 if (VT.getVectorElementType() == MVT::i1 && Subtarget->hasAVX512())
6288 return LowerBUILD_VECTORvXi1(Op, DAG);
6290 // Vectors containing all zeros can be matched by pxor and xorps later
6291 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6292 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6293 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6294 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6297 return getZeroVector(VT, Subtarget, DAG, dl);
6300 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6301 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6302 // vpcmpeqd on 256-bit vectors.
6303 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6304 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6307 if (!VT.is512BitVector())
6308 return getOnesVector(VT, Subtarget, DAG, dl);
6311 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
6312 if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
6314 if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
6315 return HorizontalOp;
6316 if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
6319 unsigned EVTBits = ExtVT.getSizeInBits();
6321 unsigned NumZero = 0;
6322 unsigned NumNonZero = 0;
6323 uint64_t NonZeros = 0;
6324 bool IsAllConstants = true;
6325 SmallSet<SDValue, 8> Values;
6326 for (unsigned i = 0; i < NumElems; ++i) {
6327 SDValue Elt = Op.getOperand(i);
6328 if (Elt.getOpcode() == ISD::UNDEF)
6331 if (Elt.getOpcode() != ISD::Constant &&
6332 Elt.getOpcode() != ISD::ConstantFP)
6333 IsAllConstants = false;
6334 if (X86::isZeroNode(Elt))
6337 assert(i < sizeof(NonZeros) * 8); // Make sure the shift is within range.
6338 NonZeros |= ((uint64_t)1 << i);
6343 // All undef vector. Return an UNDEF. All zero vectors were handled above.
6344 if (NumNonZero == 0)
6345 return DAG.getUNDEF(VT);
6347 // Special case for single non-zero, non-undef, element.
6348 if (NumNonZero == 1) {
6349 unsigned Idx = countTrailingZeros(NonZeros);
6350 SDValue Item = Op.getOperand(Idx);
6352 // If this is an insertion of an i64 value on x86-32, and if the top bits of
6353 // the value are obviously zero, truncate the value to i32 and do the
6354 // insertion that way. Only do this if the value is non-constant or if the
6355 // value is a constant being inserted into element 0. It is cheaper to do
6356 // a constant pool load than it is to do a movd + shuffle.
6357 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6358 (!IsAllConstants || Idx == 0)) {
6359 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6361 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6362 MVT VecVT = MVT::v4i32;
6364 // Truncate the value (which may itself be a constant) to i32, and
6365 // convert it to a vector with movd (S2V+shuffle to zero extend).
6366 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6367 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6368 return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
6369 Item, Idx * 2, true, Subtarget, DAG));
6373 // If we have a constant or non-constant insertion into the low element of
6374 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6375 // the rest of the elements. This will be matched as movd/movq/movss/movsd
6376 // depending on what the source datatype is.
6379 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6381 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6382 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6383 if (VT.is512BitVector()) {
6384 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6385 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6386 Item, DAG.getIntPtrConstant(0, dl));
6388 assert((VT.is128BitVector() || VT.is256BitVector()) &&
6389 "Expected an SSE value type!");
6390 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6391 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6392 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6395 // We can't directly insert an i8 or i16 into a vector, so zero extend
6397 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6398 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6399 if (VT.is256BitVector()) {
6400 if (Subtarget->hasAVX()) {
6401 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
6402 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6404 // Without AVX, we need to extend to a 128-bit vector and then
6405 // insert into the 256-bit vector.
6406 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6407 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6408 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6411 assert(VT.is128BitVector() && "Expected an SSE value type!");
6412 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6413 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6415 return DAG.getBitcast(VT, Item);
6419 // Is it a vector logical left shift?
6420 if (NumElems == 2 && Idx == 1 &&
6421 X86::isZeroNode(Op.getOperand(0)) &&
6422 !X86::isZeroNode(Op.getOperand(1))) {
6423 unsigned NumBits = VT.getSizeInBits();
6424 return getVShift(true, VT,
6425 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6426 VT, Op.getOperand(1)),
6427 NumBits/2, DAG, *this, dl);
6430 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6433 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6434 // is a non-constant being inserted into an element other than the low one,
6435 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6436 // movd/movss) to move this into the low element, then shuffle it into
6438 if (EVTBits == 32) {
6439 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6440 return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6444 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6445 if (Values.size() == 1) {
6446 if (EVTBits == 32) {
6447 // Instead of a shuffle like this:
6448 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6449 // Check if it's possible to issue this instead.
6450 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6451 unsigned Idx = countTrailingZeros(NonZeros);
6452 SDValue Item = Op.getOperand(Idx);
6453 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6454 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6459 // A vector full of immediates; various special cases are already
6460 // handled, so this is best done with a single constant-pool load.
6464 // For AVX-length vectors, see if we can use a vector load to get all of the
6465 // elements, otherwise build the individual 128-bit pieces and use
6466 // shuffles to put them in place.
6467 if (VT.is256BitVector() || VT.is512BitVector()) {
6468 SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6470 // Check for a build vector of consecutive loads.
6471 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6474 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6476 // Build both the lower and upper subvector.
6477 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6478 makeArrayRef(&V[0], NumElems/2));
6479 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6480 makeArrayRef(&V[NumElems / 2], NumElems/2));
6482 // Recreate the wider vector with the lower and upper part.
6483 if (VT.is256BitVector())
6484 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6485 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6488 // Let legalizer expand 2-wide build_vectors.
6489 if (EVTBits == 64) {
6490 if (NumNonZero == 1) {
6491 // One half is zero or undef.
6492 unsigned Idx = countTrailingZeros(NonZeros);
6493 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6494 Op.getOperand(Idx));
6495 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6500 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6501 if (EVTBits == 8 && NumElems == 16)
6502 if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros, NumNonZero, NumZero,
6503 DAG, Subtarget, *this))
6506 if (EVTBits == 16 && NumElems == 8)
6507 if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros, NumNonZero, NumZero,
6508 DAG, Subtarget, *this))
6511 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6512 if (EVTBits == 32 && NumElems == 4)
6513 if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6516 // If element VT is == 32 bits, turn it into a number of shuffles.
6517 SmallVector<SDValue, 8> V(NumElems);
6518 if (NumElems == 4 && NumZero > 0) {
6519 for (unsigned i = 0; i < 4; ++i) {
6520 bool isZero = !(NonZeros & (1ULL << i));
6522 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6524 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6527 for (unsigned i = 0; i < 2; ++i) {
6528 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6531 V[i] = V[i*2]; // Must be a zero vector.
6534 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6537 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6540 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6545 bool Reverse1 = (NonZeros & 0x3) == 2;
6546 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6550 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6551 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6553 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6556 if (Values.size() > 1 && VT.is128BitVector()) {
6557 // Check for a build vector of consecutive loads.
6558 for (unsigned i = 0; i < NumElems; ++i)
6559 V[i] = Op.getOperand(i);
6561 // Check for elements which are consecutive loads.
6562 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6565 // Check for a build vector from mostly shuffle plus few inserting.
6566 if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6569 // For SSE 4.1, use insertps to put the high elements into the low element.
6570 if (Subtarget->hasSSE41()) {
6572 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6573 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6575 Result = DAG.getUNDEF(VT);
6577 for (unsigned i = 1; i < NumElems; ++i) {
6578 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6579 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6580 Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6585 // Otherwise, expand into a number of unpckl*, start by extending each of
6586 // our (non-undef) elements to the full vector width with the element in the
6587 // bottom slot of the vector (which generates no code for SSE).
6588 for (unsigned i = 0; i < NumElems; ++i) {
6589 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6590 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6592 V[i] = DAG.getUNDEF(VT);
6595 // Next, we iteratively mix elements, e.g. for v4f32:
6596 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6597 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6598 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6599 unsigned EltStride = NumElems >> 1;
6600 while (EltStride != 0) {
6601 for (unsigned i = 0; i < EltStride; ++i) {
6602 // If V[i+EltStride] is undef and this is the first round of mixing,
6603 // then it is safe to just drop this shuffle: V[i] is already in the
6604 // right place, the one element (since it's the first round) being
6605 // inserted as undef can be dropped. This isn't safe for successive
6606 // rounds because they will permute elements within both vectors.
6607 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6608 EltStride == NumElems/2)
6611 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6620 // 256-bit AVX can use the vinsertf128 instruction
6621 // to create 256-bit vectors from two other 128-bit ones.
6622 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6624 MVT ResVT = Op.getSimpleValueType();
6626 assert((ResVT.is256BitVector() ||
6627 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6629 SDValue V1 = Op.getOperand(0);
6630 SDValue V2 = Op.getOperand(1);
6631 unsigned NumElems = ResVT.getVectorNumElements();
6632 if (ResVT.is256BitVector())
6633 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6635 if (Op.getNumOperands() == 4) {
6636 MVT HalfVT = MVT::getVectorVT(ResVT.getVectorElementType(),
6637 ResVT.getVectorNumElements()/2);
6638 SDValue V3 = Op.getOperand(2);
6639 SDValue V4 = Op.getOperand(3);
6640 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6641 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6643 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6646 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6647 const X86Subtarget *Subtarget,
6648 SelectionDAG & DAG) {
6650 MVT ResVT = Op.getSimpleValueType();
6651 unsigned NumOfOperands = Op.getNumOperands();
6653 assert(isPowerOf2_32(NumOfOperands) &&
6654 "Unexpected number of operands in CONCAT_VECTORS");
6656 SDValue Undef = DAG.getUNDEF(ResVT);
6657 if (NumOfOperands > 2) {
6658 // Specialize the cases when all, or all but one, of the operands are undef.
6659 unsigned NumOfDefinedOps = 0;
6661 for (unsigned i = 0; i < NumOfOperands; i++)
6662 if (!Op.getOperand(i).isUndef()) {
6666 if (NumOfDefinedOps == 0)
6668 if (NumOfDefinedOps == 1) {
6669 unsigned SubVecNumElts =
6670 Op.getOperand(OpIdx).getValueType().getVectorNumElements();
6671 SDValue IdxVal = DAG.getIntPtrConstant(SubVecNumElts * OpIdx, dl);
6672 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef,
6673 Op.getOperand(OpIdx), IdxVal);
6676 MVT HalfVT = MVT::getVectorVT(ResVT.getVectorElementType(),
6677 ResVT.getVectorNumElements()/2);
6678 SmallVector<SDValue, 2> Ops;
6679 for (unsigned i = 0; i < NumOfOperands/2; i++)
6680 Ops.push_back(Op.getOperand(i));
6681 SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6683 for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6684 Ops.push_back(Op.getOperand(i));
6685 SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6686 return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6690 SDValue V1 = Op.getOperand(0);
6691 SDValue V2 = Op.getOperand(1);
6692 unsigned NumElems = ResVT.getVectorNumElements();
6693 assert(V1.getValueType() == V2.getValueType() &&
6694 V1.getValueType().getVectorNumElements() == NumElems/2 &&
6695 "Unexpected operands in CONCAT_VECTORS");
6697 if (ResVT.getSizeInBits() >= 16)
6698 return Op; // The operation is legal with KUNPCK
6700 bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6701 bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6702 SDValue ZeroVec = getZeroVector(ResVT, Subtarget, DAG, dl);
6703 if (IsZeroV1 && IsZeroV2)
6706 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6708 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6710 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, ZeroVec, V1, ZeroIdx);
6712 SDValue IdxVal = DAG.getIntPtrConstant(NumElems/2, dl);
6714 V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, IdxVal);
6717 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, ZeroVec, V2, IdxVal);
6719 V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6720 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, V1, V2, IdxVal);
6723 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6724 const X86Subtarget *Subtarget,
6725 SelectionDAG &DAG) {
6726 MVT VT = Op.getSimpleValueType();
6727 if (VT.getVectorElementType() == MVT::i1)
6728 return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6730 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6731 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6732 Op.getNumOperands() == 4)));
6734 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6735 // from two other 128-bit ones.
6737 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6738 return LowerAVXCONCAT_VECTORS(Op, DAG);
6741 //===----------------------------------------------------------------------===//
6742 // Vector shuffle lowering
6744 // This is an experimental code path for lowering vector shuffles on x86. It is
6745 // designed to handle arbitrary vector shuffles and blends, gracefully
6746 // degrading performance as necessary. It works hard to recognize idiomatic
6747 // shuffles and lower them to optimal instruction patterns without leaving
6748 // a framework that allows reasonably efficient handling of all vector shuffle
6750 //===----------------------------------------------------------------------===//
6752 /// \brief Tiny helper function to identify a no-op mask.
6754 /// This is a somewhat boring predicate function. It checks whether the mask
6755 /// array input, which is assumed to be a single-input shuffle mask of the kind
6756 /// used by the X86 shuffle instructions (not a fully general
6757 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6758 /// in-place shuffle are 'no-op's.
6759 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6760 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6761 if (Mask[i] != -1 && Mask[i] != i)
6766 /// \brief Helper function to classify a mask as a single-input mask.
6768 /// This isn't a generic single-input test because in the vector shuffle
6769 /// lowering we canonicalize single inputs to be the first input operand. This
6770 /// means we can more quickly test for a single input by only checking whether
6771 /// an input from the second operand exists. We also assume that the size of
6772 /// mask corresponds to the size of the input vectors which isn't true in the
6773 /// fully general case.
6774 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6776 if (M >= (int)Mask.size())
6781 /// \brief Test whether there are elements crossing 128-bit lanes in this
6784 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6785 /// and we routinely test for these.
6786 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6787 int LaneSize = 128 / VT.getScalarSizeInBits();
6788 int Size = Mask.size();
6789 for (int i = 0; i < Size; ++i)
6790 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6795 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6797 /// This checks a shuffle mask to see if it is performing the same
6798 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6799 /// that it is also not lane-crossing. It may however involve a blend from the
6800 /// same lane of a second vector.
6802 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6803 /// non-trivial to compute in the face of undef lanes. The representation is
6804 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6805 /// entries from both V1 and V2 inputs to the wider mask.
6807 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6808 SmallVectorImpl<int> &RepeatedMask) {
6809 int LaneSize = 128 / VT.getScalarSizeInBits();
6810 RepeatedMask.resize(LaneSize, -1);
6811 int Size = Mask.size();
6812 for (int i = 0; i < Size; ++i) {
6815 if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6816 // This entry crosses lanes, so there is no way to model this shuffle.
6819 // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6820 if (RepeatedMask[i % LaneSize] == -1)
6821 // This is the first non-undef entry in this slot of a 128-bit lane.
6822 RepeatedMask[i % LaneSize] =
6823 Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6824 else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6825 // Found a mismatch with the repeated mask.
6831 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6834 /// This is a fast way to test a shuffle mask against a fixed pattern:
6836 /// if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6838 /// It returns true if the mask is exactly as wide as the argument list, and
6839 /// each element of the mask is either -1 (signifying undef) or the value given
6840 /// in the argument.
6841 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6842 ArrayRef<int> ExpectedMask) {
6843 if (Mask.size() != ExpectedMask.size())
6846 int Size = Mask.size();
6848 // If the values are build vectors, we can look through them to find
6849 // equivalent inputs that make the shuffles equivalent.
6850 auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6851 auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6853 for (int i = 0; i < Size; ++i)
6854 if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6855 auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6856 auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6857 if (!MaskBV || !ExpectedBV ||
6858 MaskBV->getOperand(Mask[i] % Size) !=
6859 ExpectedBV->getOperand(ExpectedMask[i] % Size))
6866 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6868 /// This helper function produces an 8-bit shuffle immediate corresponding to
6869 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6870 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6873 /// NB: We rely heavily on "undef" masks preserving the input lane.
6874 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6875 SelectionDAG &DAG) {
6876 assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6877 assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6878 assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6879 assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6880 assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6883 Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6884 Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6885 Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6886 Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6887 return DAG.getConstant(Imm, DL, MVT::i8);
6890 /// \brief Compute whether each element of a shuffle is zeroable.
6892 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6893 /// Either it is an undef element in the shuffle mask, the element of the input
6894 /// referenced is undef, or the element of the input referenced is known to be
6895 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6896 /// as many lanes with this technique as possible to simplify the remaining
6898 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6899 SDValue V1, SDValue V2) {
6900 SmallBitVector Zeroable(Mask.size(), false);
6902 while (V1.getOpcode() == ISD::BITCAST)
6903 V1 = V1->getOperand(0);
6904 while (V2.getOpcode() == ISD::BITCAST)
6905 V2 = V2->getOperand(0);
6907 bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6908 bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6910 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6912 // Handle the easy cases.
6913 if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6918 // If this is an index into a build_vector node (which has the same number
6919 // of elements), dig out the input value and use it.
6920 SDValue V = M < Size ? V1 : V2;
6921 if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6924 SDValue Input = V.getOperand(M % Size);
6925 // The UNDEF opcode check really should be dead code here, but not quite
6926 // worth asserting on (it isn't invalid, just unexpected).
6927 if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6934 // X86 has dedicated unpack instructions that can handle specific blend
6935 // operations: UNPCKH and UNPCKL.
6936 static SDValue lowerVectorShuffleWithUNPCK(SDLoc DL, MVT VT, ArrayRef<int> Mask,
6937 SDValue V1, SDValue V2,
6938 SelectionDAG &DAG) {
6939 int NumElts = VT.getVectorNumElements();
6940 int NumEltsInLane = 128 / VT.getScalarSizeInBits();
6941 SmallVector<int, 8> Unpckl;
6942 SmallVector<int, 8> Unpckh;
6944 for (int i = 0; i < NumElts; ++i) {
6945 unsigned LaneStart = (i / NumEltsInLane) * NumEltsInLane;
6946 int LoPos = (i % NumEltsInLane) / 2 + LaneStart + NumElts * (i % 2);
6947 int HiPos = LoPos + NumEltsInLane / 2;
6948 Unpckl.push_back(LoPos);
6949 Unpckh.push_back(HiPos);
6952 if (isShuffleEquivalent(V1, V2, Mask, Unpckl))
6953 return DAG.getNode(X86ISD::UNPCKL, DL, VT, V1, V2);
6954 if (isShuffleEquivalent(V1, V2, Mask, Unpckh))
6955 return DAG.getNode(X86ISD::UNPCKH, DL, VT, V1, V2);
6957 // Commute and try again.
6958 ShuffleVectorSDNode::commuteMask(Unpckl);
6959 if (isShuffleEquivalent(V1, V2, Mask, Unpckl))
6960 return DAG.getNode(X86ISD::UNPCKL, DL, VT, V2, V1);
6962 ShuffleVectorSDNode::commuteMask(Unpckh);
6963 if (isShuffleEquivalent(V1, V2, Mask, Unpckh))
6964 return DAG.getNode(X86ISD::UNPCKH, DL, VT, V2, V1);
6969 /// \brief Try to emit a bitmask instruction for a shuffle.
6971 /// This handles cases where we can model a blend exactly as a bitmask due to
6972 /// one of the inputs being zeroable.
6973 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6974 SDValue V2, ArrayRef<int> Mask,
6975 SelectionDAG &DAG) {
6976 MVT EltVT = VT.getVectorElementType();
6977 int NumEltBits = EltVT.getSizeInBits();
6978 MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6979 SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6980 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6982 if (EltVT.isFloatingPoint()) {
6983 Zero = DAG.getBitcast(EltVT, Zero);
6984 AllOnes = DAG.getBitcast(EltVT, AllOnes);
6986 SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6987 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6989 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6992 if (Mask[i] % Size != i)
6993 return SDValue(); // Not a blend.
6995 V = Mask[i] < Size ? V1 : V2;
6996 else if (V != (Mask[i] < Size ? V1 : V2))
6997 return SDValue(); // Can only let one input through the mask.
6999 VMaskOps[i] = AllOnes;
7002 return SDValue(); // No non-zeroable elements!
7004 SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
7005 V = DAG.getNode(VT.isFloatingPoint()
7006 ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
7011 /// \brief Try to emit a blend instruction for a shuffle using bit math.
7013 /// This is used as a fallback approach when first class blend instructions are
7014 /// unavailable. Currently it is only suitable for integer vectors, but could
7015 /// be generalized for floating point vectors if desirable.
7016 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
7017 SDValue V2, ArrayRef<int> Mask,
7018 SelectionDAG &DAG) {
7019 assert(VT.isInteger() && "Only supports integer vector types!");
7020 MVT EltVT = VT.getVectorElementType();
7021 int NumEltBits = EltVT.getSizeInBits();
7022 SDValue Zero = DAG.getConstant(0, DL, EltVT);
7023 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
7025 SmallVector<SDValue, 16> MaskOps;
7026 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7027 if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
7028 return SDValue(); // Shuffled input!
7029 MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
7032 SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
7033 V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
7034 // We have to cast V2 around.
7035 MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
7036 V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
7037 DAG.getBitcast(MaskVT, V1Mask),
7038 DAG.getBitcast(MaskVT, V2)));
7039 return DAG.getNode(ISD::OR, DL, VT, V1, V2);
7042 /// \brief Try to emit a blend instruction for a shuffle.
7044 /// This doesn't do any checks for the availability of instructions for blending
7045 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
7046 /// be matched in the backend with the type given. What it does check for is
7047 /// that the shuffle mask is a blend, or convertible into a blend with zero.
7048 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
7049 SDValue V2, ArrayRef<int> Original,
7050 const X86Subtarget *Subtarget,
7051 SelectionDAG &DAG) {
7052 bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
7053 bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
7054 SmallVector<int, 8> Mask(Original.begin(), Original.end());
7055 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7056 bool ForceV1Zero = false, ForceV2Zero = false;
7058 // Attempt to generate the binary blend mask. If an input is zero then
7059 // we can use any lane.
7060 // TODO: generalize the zero matching to any scalar like isShuffleEquivalent.
7061 unsigned BlendMask = 0;
7062 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7068 if (M == i + Size) {
7069 BlendMask |= 1u << i;
7080 BlendMask |= 1u << i;
7085 return SDValue(); // Shuffled input!
7088 // Create a REAL zero vector - ISD::isBuildVectorAllZeros allows UNDEFs.
7090 V1 = getZeroVector(VT, Subtarget, DAG, DL);
7092 V2 = getZeroVector(VT, Subtarget, DAG, DL);
7094 auto ScaleBlendMask = [](unsigned BlendMask, int Size, int Scale) {
7095 unsigned ScaledMask = 0;
7096 for (int i = 0; i != Size; ++i)
7097 if (BlendMask & (1u << i))
7098 for (int j = 0; j != Scale; ++j)
7099 ScaledMask |= 1u << (i * Scale + j);
7103 switch (VT.SimpleTy) {
7108 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
7109 DAG.getConstant(BlendMask, DL, MVT::i8));
7113 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
7117 // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
7118 // that instruction.
7119 if (Subtarget->hasAVX2()) {
7120 // Scale the blend by the number of 32-bit dwords per element.
7121 int Scale = VT.getScalarSizeInBits() / 32;
7122 BlendMask = ScaleBlendMask(BlendMask, Mask.size(), Scale);
7123 MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
7124 V1 = DAG.getBitcast(BlendVT, V1);
7125 V2 = DAG.getBitcast(BlendVT, V2);
7126 return DAG.getBitcast(
7127 VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
7128 DAG.getConstant(BlendMask, DL, MVT::i8)));
7132 // For integer shuffles we need to expand the mask and cast the inputs to
7133 // v8i16s prior to blending.
7134 int Scale = 8 / VT.getVectorNumElements();
7135 BlendMask = ScaleBlendMask(BlendMask, Mask.size(), Scale);
7136 V1 = DAG.getBitcast(MVT::v8i16, V1);
7137 V2 = DAG.getBitcast(MVT::v8i16, V2);
7138 return DAG.getBitcast(VT,
7139 DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
7140 DAG.getConstant(BlendMask, DL, MVT::i8)));
7144 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
7145 SmallVector<int, 8> RepeatedMask;
7146 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
7147 // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
7148 assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
7150 for (int i = 0; i < 8; ++i)
7151 if (RepeatedMask[i] >= 16)
7152 BlendMask |= 1u << i;
7153 return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
7154 DAG.getConstant(BlendMask, DL, MVT::i8));
7160 assert((VT.is128BitVector() || Subtarget->hasAVX2()) &&
7161 "256-bit byte-blends require AVX2 support!");
7163 // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
7164 if (SDValue Masked = lowerVectorShuffleAsBitMask(DL, VT, V1, V2, Mask, DAG))
7167 // Scale the blend by the number of bytes per element.
7168 int Scale = VT.getScalarSizeInBits() / 8;
7170 // This form of blend is always done on bytes. Compute the byte vector
7172 MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
7174 // Compute the VSELECT mask. Note that VSELECT is really confusing in the
7175 // mix of LLVM's code generator and the x86 backend. We tell the code
7176 // generator that boolean values in the elements of an x86 vector register
7177 // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
7178 // mapping a select to operand #1, and 'false' mapping to operand #2. The
7179 // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
7180 // of the element (the remaining are ignored) and 0 in that high bit would
7181 // mean operand #1 while 1 in the high bit would mean operand #2. So while
7182 // the LLVM model for boolean values in vector elements gets the relevant
7183 // bit set, it is set backwards and over constrained relative to x86's
7185 SmallVector<SDValue, 32> VSELECTMask;
7186 for (int i = 0, Size = Mask.size(); i < Size; ++i)
7187 for (int j = 0; j < Scale; ++j)
7188 VSELECTMask.push_back(
7189 Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
7190 : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
7193 V1 = DAG.getBitcast(BlendVT, V1);
7194 V2 = DAG.getBitcast(BlendVT, V2);
7195 return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
7196 DAG.getNode(ISD::BUILD_VECTOR, DL,
7197 BlendVT, VSELECTMask),
7202 llvm_unreachable("Not a supported integer vector type!");
7206 /// \brief Try to lower as a blend of elements from two inputs followed by
7207 /// a single-input permutation.
7209 /// This matches the pattern where we can blend elements from two inputs and
7210 /// then reduce the shuffle to a single-input permutation.
7211 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
7214 SelectionDAG &DAG) {
7215 // We build up the blend mask while checking whether a blend is a viable way
7216 // to reduce the shuffle.
7217 SmallVector<int, 32> BlendMask(Mask.size(), -1);
7218 SmallVector<int, 32> PermuteMask(Mask.size(), -1);
7220 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7224 assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
7226 if (BlendMask[Mask[i] % Size] == -1)
7227 BlendMask[Mask[i] % Size] = Mask[i];
7228 else if (BlendMask[Mask[i] % Size] != Mask[i])
7229 return SDValue(); // Can't blend in the needed input!
7231 PermuteMask[i] = Mask[i] % Size;
7234 SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7235 return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
7238 /// \brief Generic routine to decompose a shuffle and blend into indepndent
7239 /// blends and permutes.
7241 /// This matches the extremely common pattern for handling combined
7242 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
7243 /// operations. It will try to pick the best arrangement of shuffles and
7245 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
7249 SelectionDAG &DAG) {
7250 // Shuffle the input elements into the desired positions in V1 and V2 and
7251 // blend them together.
7252 SmallVector<int, 32> V1Mask(Mask.size(), -1);
7253 SmallVector<int, 32> V2Mask(Mask.size(), -1);
7254 SmallVector<int, 32> BlendMask(Mask.size(), -1);
7255 for (int i = 0, Size = Mask.size(); i < Size; ++i)
7256 if (Mask[i] >= 0 && Mask[i] < Size) {
7257 V1Mask[i] = Mask[i];
7259 } else if (Mask[i] >= Size) {
7260 V2Mask[i] = Mask[i] - Size;
7261 BlendMask[i] = i + Size;
7264 // Try to lower with the simpler initial blend strategy unless one of the
7265 // input shuffles would be a no-op. We prefer to shuffle inputs as the
7266 // shuffle may be able to fold with a load or other benefit. However, when
7267 // we'll have to do 2x as many shuffles in order to achieve this, blending
7268 // first is a better strategy.
7269 if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
7270 if (SDValue BlendPerm =
7271 lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
7274 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7275 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7276 return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7279 /// \brief Try to lower a vector shuffle as a byte rotation.
7281 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
7282 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
7283 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
7284 /// try to generically lower a vector shuffle through such an pattern. It
7285 /// does not check for the profitability of lowering either as PALIGNR or
7286 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
7287 /// This matches shuffle vectors that look like:
7289 /// v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
7291 /// Essentially it concatenates V1 and V2, shifts right by some number of
7292 /// elements, and takes the low elements as the result. Note that while this is
7293 /// specified as a *right shift* because x86 is little-endian, it is a *left
7294 /// rotate* of the vector lanes.
7295 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
7298 const X86Subtarget *Subtarget,
7299 SelectionDAG &DAG) {
7300 assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
7302 int NumElts = Mask.size();
7303 int NumLanes = VT.getSizeInBits() / 128;
7304 int NumLaneElts = NumElts / NumLanes;
7306 // We need to detect various ways of spelling a rotation:
7307 // [11, 12, 13, 14, 15, 0, 1, 2]
7308 // [-1, 12, 13, 14, -1, -1, 1, -1]
7309 // [-1, -1, -1, -1, -1, -1, 1, 2]
7310 // [ 3, 4, 5, 6, 7, 8, 9, 10]
7311 // [-1, 4, 5, 6, -1, -1, 9, -1]
7312 // [-1, 4, 5, 6, -1, -1, -1, -1]
7315 for (int l = 0; l < NumElts; l += NumLaneElts) {
7316 for (int i = 0; i < NumLaneElts; ++i) {
7317 if (Mask[l + i] == -1)
7319 assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
7321 // Get the mod-Size index and lane correct it.
7322 int LaneIdx = (Mask[l + i] % NumElts) - l;
7323 // Make sure it was in this lane.
7324 if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
7327 // Determine where a rotated vector would have started.
7328 int StartIdx = i - LaneIdx;
7330 // The identity rotation isn't interesting, stop.
7333 // If we found the tail of a vector the rotation must be the missing
7334 // front. If we found the head of a vector, it must be how much of the
7336 int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
7339 Rotation = CandidateRotation;
7340 else if (Rotation != CandidateRotation)
7341 // The rotations don't match, so we can't match this mask.
7344 // Compute which value this mask is pointing at.
7345 SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
7347 // Compute which of the two target values this index should be assigned
7348 // to. This reflects whether the high elements are remaining or the low
7349 // elements are remaining.
7350 SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
7352 // Either set up this value if we've not encountered it before, or check
7353 // that it remains consistent.
7356 else if (TargetV != MaskV)
7357 // This may be a rotation, but it pulls from the inputs in some
7358 // unsupported interleaving.
7363 // Check that we successfully analyzed the mask, and normalize the results.
7364 assert(Rotation != 0 && "Failed to locate a viable rotation!");
7365 assert((Lo || Hi) && "Failed to find a rotated input vector!");
7371 // The actual rotate instruction rotates bytes, so we need to scale the
7372 // rotation based on how many bytes are in the vector lane.
7373 int Scale = 16 / NumLaneElts;
7375 // SSSE3 targets can use the palignr instruction.
7376 if (Subtarget->hasSSSE3()) {
7377 // Cast the inputs to i8 vector of correct length to match PALIGNR.
7378 MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
7379 Lo = DAG.getBitcast(AlignVT, Lo);
7380 Hi = DAG.getBitcast(AlignVT, Hi);
7382 return DAG.getBitcast(
7383 VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Lo, Hi,
7384 DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
7387 assert(VT.is128BitVector() &&
7388 "Rotate-based lowering only supports 128-bit lowering!");
7389 assert(Mask.size() <= 16 &&
7390 "Can shuffle at most 16 bytes in a 128-bit vector!");
7392 // Default SSE2 implementation
7393 int LoByteShift = 16 - Rotation * Scale;
7394 int HiByteShift = Rotation * Scale;
7396 // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
7397 Lo = DAG.getBitcast(MVT::v2i64, Lo);
7398 Hi = DAG.getBitcast(MVT::v2i64, Hi);
7400 SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
7401 DAG.getConstant(LoByteShift, DL, MVT::i8));
7402 SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
7403 DAG.getConstant(HiByteShift, DL, MVT::i8));
7404 return DAG.getBitcast(VT,
7405 DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
7408 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
7410 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
7411 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
7412 /// matches elements from one of the input vectors shuffled to the left or
7413 /// right with zeroable elements 'shifted in'. It handles both the strictly
7414 /// bit-wise element shifts and the byte shift across an entire 128-bit double
7417 /// PSHL : (little-endian) left bit shift.
7418 /// [ zz, 0, zz, 2 ]
7419 /// [ -1, 4, zz, -1 ]
7420 /// PSRL : (little-endian) right bit shift.
7422 /// [ -1, -1, 7, zz]
7423 /// PSLLDQ : (little-endian) left byte shift
7424 /// [ zz, 0, 1, 2, 3, 4, 5, 6]
7425 /// [ zz, zz, -1, -1, 2, 3, 4, -1]
7426 /// [ zz, zz, zz, zz, zz, zz, -1, 1]
7427 /// PSRLDQ : (little-endian) right byte shift
7428 /// [ 5, 6, 7, zz, zz, zz, zz, zz]
7429 /// [ -1, 5, 6, 7, zz, zz, zz, zz]
7430 /// [ 1, 2, -1, -1, -1, -1, zz, zz]
7431 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
7432 SDValue V2, ArrayRef<int> Mask,
7433 SelectionDAG &DAG) {
7434 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7436 int Size = Mask.size();
7437 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7439 auto CheckZeros = [&](int Shift, int Scale, bool Left) {
7440 for (int i = 0; i < Size; i += Scale)
7441 for (int j = 0; j < Shift; ++j)
7442 if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
7448 auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
7449 for (int i = 0; i != Size; i += Scale) {
7450 unsigned Pos = Left ? i + Shift : i;
7451 unsigned Low = Left ? i : i + Shift;
7452 unsigned Len = Scale - Shift;
7453 if (!isSequentialOrUndefInRange(Mask, Pos, Len,
7454 Low + (V == V1 ? 0 : Size)))
7458 int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
7459 bool ByteShift = ShiftEltBits > 64;
7460 unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
7461 : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
7462 int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
7464 // Normalize the scale for byte shifts to still produce an i64 element
7466 Scale = ByteShift ? Scale / 2 : Scale;
7468 // We need to round trip through the appropriate type for the shift.
7469 MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
7470 MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
7471 assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
7472 "Illegal integer vector type");
7473 V = DAG.getBitcast(ShiftVT, V);
7475 V = DAG.getNode(OpCode, DL, ShiftVT, V,
7476 DAG.getConstant(ShiftAmt, DL, MVT::i8));
7477 return DAG.getBitcast(VT, V);
7480 // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
7481 // keep doubling the size of the integer elements up to that. We can
7482 // then shift the elements of the integer vector by whole multiples of
7483 // their width within the elements of the larger integer vector. Test each
7484 // multiple to see if we can find a match with the moved element indices
7485 // and that the shifted in elements are all zeroable.
7486 for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
7487 for (int Shift = 1; Shift != Scale; ++Shift)
7488 for (bool Left : {true, false})
7489 if (CheckZeros(Shift, Scale, Left))
7490 for (SDValue V : {V1, V2})
7491 if (SDValue Match = MatchShift(Shift, Scale, Left, V))
7498 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
7499 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
7500 SDValue V2, ArrayRef<int> Mask,
7501 SelectionDAG &DAG) {
7502 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7503 assert(!Zeroable.all() && "Fully zeroable shuffle mask");
7505 int Size = Mask.size();
7506 int HalfSize = Size / 2;
7507 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7509 // Upper half must be undefined.
7510 if (!isUndefInRange(Mask, HalfSize, HalfSize))
7513 // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7514 // Remainder of lower half result is zero and upper half is all undef.
7515 auto LowerAsEXTRQ = [&]() {
7516 // Determine the extraction length from the part of the
7517 // lower half that isn't zeroable.
7519 for (; Len > 0; --Len)
7520 if (!Zeroable[Len - 1])
7522 assert(Len > 0 && "Zeroable shuffle mask");
7524 // Attempt to match first Len sequential elements from the lower half.
7527 for (int i = 0; i != Len; ++i) {
7531 SDValue &V = (M < Size ? V1 : V2);
7534 // The extracted elements must start at a valid index and all mask
7535 // elements must be in the lower half.
7536 if (i > M || M >= HalfSize)
7539 if (Idx < 0 || (Src == V && Idx == (M - i))) {
7550 assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7551 int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7552 int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7553 return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7554 DAG.getConstant(BitLen, DL, MVT::i8),
7555 DAG.getConstant(BitIdx, DL, MVT::i8));
7558 if (SDValue ExtrQ = LowerAsEXTRQ())
7561 // INSERTQ: Extract lowest Len elements from lower half of second source and
7562 // insert over first source, starting at Idx.
7563 // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7564 auto LowerAsInsertQ = [&]() {
7565 for (int Idx = 0; Idx != HalfSize; ++Idx) {
7568 // Attempt to match first source from mask before insertion point.
7569 if (isUndefInRange(Mask, 0, Idx)) {
7571 } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7573 } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7579 // Extend the extraction length looking to match both the insertion of
7580 // the second source and the remaining elements of the first.
7581 for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7586 if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7588 } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7594 // Match the remaining elements of the lower half.
7595 if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7597 } else if ((!Base || (Base == V1)) &&
7598 isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7600 } else if ((!Base || (Base == V2)) &&
7601 isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7608 // We may not have a base (first source) - this can safely be undefined.
7610 Base = DAG.getUNDEF(VT);
7612 int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7613 int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7614 return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7615 DAG.getConstant(BitLen, DL, MVT::i8),
7616 DAG.getConstant(BitIdx, DL, MVT::i8));
7623 if (SDValue InsertQ = LowerAsInsertQ())
7629 /// \brief Lower a vector shuffle as a zero or any extension.
7631 /// Given a specific number of elements, element bit width, and extension
7632 /// stride, produce either a zero or any extension based on the available
7633 /// features of the subtarget. The extended elements are consecutive and
7634 /// begin and can start from an offseted element index in the input; to
7635 /// avoid excess shuffling the offset must either being in the bottom lane
7636 /// or at the start of a higher lane. All extended elements must be from
7638 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7639 SDLoc DL, MVT VT, int Scale, int Offset, bool AnyExt, SDValue InputV,
7640 ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7641 assert(Scale > 1 && "Need a scale to extend.");
7642 int EltBits = VT.getScalarSizeInBits();
7643 int NumElements = VT.getVectorNumElements();
7644 int NumEltsPerLane = 128 / EltBits;
7645 int OffsetLane = Offset / NumEltsPerLane;
7646 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7647 "Only 8, 16, and 32 bit elements can be extended.");
7648 assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7649 assert(0 <= Offset && "Extension offset must be positive.");
7650 assert((Offset < NumEltsPerLane || Offset % NumEltsPerLane == 0) &&
7651 "Extension offset must be in the first lane or start an upper lane.");
7653 // Check that an index is in same lane as the base offset.
7654 auto SafeOffset = [&](int Idx) {
7655 return OffsetLane == (Idx / NumEltsPerLane);
7658 // Shift along an input so that the offset base moves to the first element.
7659 auto ShuffleOffset = [&](SDValue V) {
7663 SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7664 for (int i = 0; i * Scale < NumElements; ++i) {
7665 int SrcIdx = i + Offset;
7666 ShMask[i] = SafeOffset(SrcIdx) ? SrcIdx : -1;
7668 return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), ShMask);
7671 // Found a valid zext mask! Try various lowering strategies based on the
7672 // input type and available ISA extensions.
7673 if (Subtarget->hasSSE41()) {
7674 // Not worth offseting 128-bit vectors if scale == 2, a pattern using
7675 // PUNPCK will catch this in a later shuffle match.
7676 if (Offset && Scale == 2 && VT.is128BitVector())
7678 MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7679 NumElements / Scale);
7680 InputV = DAG.getNode(X86ISD::VZEXT, DL, ExtVT, ShuffleOffset(InputV));
7681 return DAG.getBitcast(VT, InputV);
7684 assert(VT.is128BitVector() && "Only 128-bit vectors can be extended.");
7686 // For any extends we can cheat for larger element sizes and use shuffle
7687 // instructions that can fold with a load and/or copy.
7688 if (AnyExt && EltBits == 32) {
7689 int PSHUFDMask[4] = {Offset, -1, SafeOffset(Offset + 1) ? Offset + 1 : -1,
7691 return DAG.getBitcast(
7692 VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7693 DAG.getBitcast(MVT::v4i32, InputV),
7694 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7696 if (AnyExt && EltBits == 16 && Scale > 2) {
7697 int PSHUFDMask[4] = {Offset / 2, -1,
7698 SafeOffset(Offset + 1) ? (Offset + 1) / 2 : -1, -1};
7699 InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7700 DAG.getBitcast(MVT::v4i32, InputV),
7701 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7702 int PSHUFWMask[4] = {1, -1, -1, -1};
7703 unsigned OddEvenOp = (Offset & 1 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW);
7704 return DAG.getBitcast(
7705 VT, DAG.getNode(OddEvenOp, DL, MVT::v8i16,
7706 DAG.getBitcast(MVT::v8i16, InputV),
7707 getV4X86ShuffleImm8ForMask(PSHUFWMask, DL, DAG)));
7710 // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7712 if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7713 assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7714 assert(VT.is128BitVector() && "Unexpected vector width!");
7716 int LoIdx = Offset * EltBits;
7717 SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7718 DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7719 DAG.getConstant(EltBits, DL, MVT::i8),
7720 DAG.getConstant(LoIdx, DL, MVT::i8)));
7722 if (isUndefInRange(Mask, NumElements / 2, NumElements / 2) ||
7723 !SafeOffset(Offset + 1))
7724 return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7726 int HiIdx = (Offset + 1) * EltBits;
7727 SDValue Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7728 DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7729 DAG.getConstant(EltBits, DL, MVT::i8),
7730 DAG.getConstant(HiIdx, DL, MVT::i8)));
7731 return DAG.getNode(ISD::BITCAST, DL, VT,
7732 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7735 // If this would require more than 2 unpack instructions to expand, use
7736 // pshufb when available. We can only use more than 2 unpack instructions
7737 // when zero extending i8 elements which also makes it easier to use pshufb.
7738 if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7739 assert(NumElements == 16 && "Unexpected byte vector width!");
7740 SDValue PSHUFBMask[16];
7741 for (int i = 0; i < 16; ++i) {
7742 int Idx = Offset + (i / Scale);
7743 PSHUFBMask[i] = DAG.getConstant(
7744 (i % Scale == 0 && SafeOffset(Idx)) ? Idx : 0x80, DL, MVT::i8);
7746 InputV = DAG.getBitcast(MVT::v16i8, InputV);
7747 return DAG.getBitcast(VT,
7748 DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7749 DAG.getNode(ISD::BUILD_VECTOR, DL,
7750 MVT::v16i8, PSHUFBMask)));
7753 // If we are extending from an offset, ensure we start on a boundary that
7754 // we can unpack from.
7755 int AlignToUnpack = Offset % (NumElements / Scale);
7756 if (AlignToUnpack) {
7757 SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7758 for (int i = AlignToUnpack; i < NumElements; ++i)
7759 ShMask[i - AlignToUnpack] = i;
7760 InputV = DAG.getVectorShuffle(VT, DL, InputV, DAG.getUNDEF(VT), ShMask);
7761 Offset -= AlignToUnpack;
7764 // Otherwise emit a sequence of unpacks.
7766 unsigned UnpackLoHi = X86ISD::UNPCKL;
7767 if (Offset >= (NumElements / 2)) {
7768 UnpackLoHi = X86ISD::UNPCKH;
7769 Offset -= (NumElements / 2);
7772 MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7773 SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7774 : getZeroVector(InputVT, Subtarget, DAG, DL);
7775 InputV = DAG.getBitcast(InputVT, InputV);
7776 InputV = DAG.getNode(UnpackLoHi, DL, InputVT, InputV, Ext);
7780 } while (Scale > 1);
7781 return DAG.getBitcast(VT, InputV);
7784 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7786 /// This routine will try to do everything in its power to cleverly lower
7787 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7788 /// check for the profitability of this lowering, it tries to aggressively
7789 /// match this pattern. It will use all of the micro-architectural details it
7790 /// can to emit an efficient lowering. It handles both blends with all-zero
7791 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7792 /// masking out later).
7794 /// The reason we have dedicated lowering for zext-style shuffles is that they
7795 /// are both incredibly common and often quite performance sensitive.
7796 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7797 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7798 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7799 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7801 int Bits = VT.getSizeInBits();
7802 int NumLanes = Bits / 128;
7803 int NumElements = VT.getVectorNumElements();
7804 int NumEltsPerLane = NumElements / NumLanes;
7805 assert(VT.getScalarSizeInBits() <= 32 &&
7806 "Exceeds 32-bit integer zero extension limit");
7807 assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7809 // Define a helper function to check a particular ext-scale and lower to it if
7811 auto Lower = [&](int Scale) -> SDValue {
7816 for (int i = 0; i < NumElements; ++i) {
7819 continue; // Valid anywhere but doesn't tell us anything.
7820 if (i % Scale != 0) {
7821 // Each of the extended elements need to be zeroable.
7825 // We no longer are in the anyext case.
7830 // Each of the base elements needs to be consecutive indices into the
7831 // same input vector.
7832 SDValue V = M < NumElements ? V1 : V2;
7833 M = M % NumElements;
7836 Offset = M - (i / Scale);
7837 } else if (InputV != V)
7838 return SDValue(); // Flip-flopping inputs.
7840 // Offset must start in the lowest 128-bit lane or at the start of an
7842 // FIXME: Is it ever worth allowing a negative base offset?
7843 if (!((0 <= Offset && Offset < NumEltsPerLane) ||
7844 (Offset % NumEltsPerLane) == 0))
7847 // If we are offsetting, all referenced entries must come from the same
7849 if (Offset && (Offset / NumEltsPerLane) != (M / NumEltsPerLane))
7852 if ((M % NumElements) != (Offset + (i / Scale)))
7853 return SDValue(); // Non-consecutive strided elements.
7857 // If we fail to find an input, we have a zero-shuffle which should always
7858 // have already been handled.
7859 // FIXME: Maybe handle this here in case during blending we end up with one?
7863 // If we are offsetting, don't extend if we only match a single input, we
7864 // can always do better by using a basic PSHUF or PUNPCK.
7865 if (Offset != 0 && Matches < 2)
7868 return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7869 DL, VT, Scale, Offset, AnyExt, InputV, Mask, Subtarget, DAG);
7872 // The widest scale possible for extending is to a 64-bit integer.
7873 assert(Bits % 64 == 0 &&
7874 "The number of bits in a vector must be divisible by 64 on x86!");
7875 int NumExtElements = Bits / 64;
7877 // Each iteration, try extending the elements half as much, but into twice as
7879 for (; NumExtElements < NumElements; NumExtElements *= 2) {
7880 assert(NumElements % NumExtElements == 0 &&
7881 "The input vector size must be divisible by the extended size.");
7882 if (SDValue V = Lower(NumElements / NumExtElements))
7886 // General extends failed, but 128-bit vectors may be able to use MOVQ.
7890 // Returns one of the source operands if the shuffle can be reduced to a
7891 // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7892 auto CanZExtLowHalf = [&]() {
7893 for (int i = NumElements / 2; i != NumElements; ++i)
7896 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7898 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7903 if (SDValue V = CanZExtLowHalf()) {
7904 V = DAG.getBitcast(MVT::v2i64, V);
7905 V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7906 return DAG.getBitcast(VT, V);
7909 // No viable ext lowering found.
7913 /// \brief Try to get a scalar value for a specific element of a vector.
7915 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7916 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7917 SelectionDAG &DAG) {
7918 MVT VT = V.getSimpleValueType();
7919 MVT EltVT = VT.getVectorElementType();
7920 while (V.getOpcode() == ISD::BITCAST)
7921 V = V.getOperand(0);
7922 // If the bitcasts shift the element size, we can't extract an equivalent
7924 MVT NewVT = V.getSimpleValueType();
7925 if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7928 if (V.getOpcode() == ISD::BUILD_VECTOR ||
7929 (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7930 // Ensure the scalar operand is the same size as the destination.
7931 // FIXME: Add support for scalar truncation where possible.
7932 SDValue S = V.getOperand(Idx);
7933 if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7934 return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7940 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7942 /// This is particularly important because the set of instructions varies
7943 /// significantly based on whether the operand is a load or not.
7944 static bool isShuffleFoldableLoad(SDValue V) {
7945 while (V.getOpcode() == ISD::BITCAST)
7946 V = V.getOperand(0);
7948 return ISD::isNON_EXTLoad(V.getNode());
7951 /// \brief Try to lower insertion of a single element into a zero vector.
7953 /// This is a common pattern that we have especially efficient patterns to lower
7954 /// across all subtarget feature sets.
7955 static SDValue lowerVectorShuffleAsElementInsertion(
7956 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7957 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7958 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7960 MVT EltVT = VT.getVectorElementType();
7962 int V2Index = std::find_if(Mask.begin(), Mask.end(),
7963 [&Mask](int M) { return M >= (int)Mask.size(); }) -
7965 bool IsV1Zeroable = true;
7966 for (int i = 0, Size = Mask.size(); i < Size; ++i)
7967 if (i != V2Index && !Zeroable[i]) {
7968 IsV1Zeroable = false;
7972 // Check for a single input from a SCALAR_TO_VECTOR node.
7973 // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7974 // all the smarts here sunk into that routine. However, the current
7975 // lowering of BUILD_VECTOR makes that nearly impossible until the old
7976 // vector shuffle lowering is dead.
7977 SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
7979 if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
7980 // We need to zext the scalar if it is smaller than an i32.
7981 V2S = DAG.getBitcast(EltVT, V2S);
7982 if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7983 // Using zext to expand a narrow element won't work for non-zero
7988 // Zero-extend directly to i32.
7990 V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7992 V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7993 } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7994 EltVT == MVT::i16) {
7995 // Either not inserting from the low element of the input or the input
7996 // element size is too small to use VZEXT_MOVL to clear the high bits.
8000 if (!IsV1Zeroable) {
8001 // If V1 can't be treated as a zero vector we have fewer options to lower
8002 // this. We can't support integer vectors or non-zero targets cheaply, and
8003 // the V1 elements can't be permuted in any way.
8004 assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
8005 if (!VT.isFloatingPoint() || V2Index != 0)
8007 SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
8008 V1Mask[V2Index] = -1;
8009 if (!isNoopShuffleMask(V1Mask))
8011 // This is essentially a special case blend operation, but if we have
8012 // general purpose blend operations, they are always faster. Bail and let
8013 // the rest of the lowering handle these as blends.
8014 if (Subtarget->hasSSE41())
8017 // Otherwise, use MOVSD or MOVSS.
8018 assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
8019 "Only two types of floating point element types to handle!");
8020 return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
8024 // This lowering only works for the low element with floating point vectors.
8025 if (VT.isFloatingPoint() && V2Index != 0)
8028 V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
8030 V2 = DAG.getBitcast(VT, V2);
8033 // If we have 4 or fewer lanes we can cheaply shuffle the element into
8034 // the desired position. Otherwise it is more efficient to do a vector
8035 // shift left. We know that we can do a vector shift left because all
8036 // the inputs are zero.
8037 if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
8038 SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
8039 V2Shuffle[V2Index] = 0;
8040 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
8042 V2 = DAG.getBitcast(MVT::v2i64, V2);
8044 X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
8045 DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
8046 DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
8047 DAG.getDataLayout(), VT)));
8048 V2 = DAG.getBitcast(VT, V2);
8054 /// \brief Try to lower broadcast of a single - truncated - integer element,
8055 /// coming from a scalar_to_vector/build_vector node \p V0 with larger elements.
8057 /// This assumes we have AVX2.
8058 static SDValue lowerVectorShuffleAsTruncBroadcast(SDLoc DL, MVT VT, SDValue V0,
8060 const X86Subtarget *Subtarget,
8061 SelectionDAG &DAG) {
8062 assert(Subtarget->hasAVX2() &&
8063 "We can only lower integer broadcasts with AVX2!");
8065 EVT EltVT = VT.getVectorElementType();
8066 EVT V0VT = V0.getValueType();
8068 assert(VT.isInteger() && "Unexpected non-integer trunc broadcast!");
8069 assert(V0VT.isVector() && "Unexpected non-vector vector-sized value!");
8071 EVT V0EltVT = V0VT.getVectorElementType();
8072 if (!V0EltVT.isInteger())
8075 const unsigned EltSize = EltVT.getSizeInBits();
8076 const unsigned V0EltSize = V0EltVT.getSizeInBits();
8078 // This is only a truncation if the original element type is larger.
8079 if (V0EltSize <= EltSize)
8082 assert(((V0EltSize % EltSize) == 0) &&
8083 "Scalar type sizes must all be powers of 2 on x86!");
8085 const unsigned V0Opc = V0.getOpcode();
8086 const unsigned Scale = V0EltSize / EltSize;
8087 const unsigned V0BroadcastIdx = BroadcastIdx / Scale;
8089 if ((V0Opc != ISD::SCALAR_TO_VECTOR || V0BroadcastIdx != 0) &&
8090 V0Opc != ISD::BUILD_VECTOR)
8093 SDValue Scalar = V0.getOperand(V0BroadcastIdx);
8095 // If we're extracting non-least-significant bits, shift so we can truncate.
8096 // Hopefully, we can fold away the trunc/srl/load into the broadcast.
8097 // Even if we can't (and !isShuffleFoldableLoad(Scalar)), prefer
8098 // vpbroadcast+vmovd+shr to vpshufb(m)+vmovd.
8099 if (const int OffsetIdx = BroadcastIdx % Scale)
8100 Scalar = DAG.getNode(ISD::SRL, DL, Scalar.getValueType(), Scalar,
8101 DAG.getConstant(OffsetIdx * EltSize, DL, Scalar.getValueType()));
8103 return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
8104 DAG.getNode(ISD::TRUNCATE, DL, EltVT, Scalar));
8107 /// \brief Try to lower broadcast of a single element.
8109 /// For convenience, this code also bundles all of the subtarget feature set
8110 /// filtering. While a little annoying to re-dispatch on type here, there isn't
8111 /// a convenient way to factor it out.
8112 /// FIXME: This is very similar to LowerVectorBroadcast - can we merge them?
8113 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
8115 const X86Subtarget *Subtarget,
8116 SelectionDAG &DAG) {
8117 if (!Subtarget->hasAVX())
8119 if (VT.isInteger() && !Subtarget->hasAVX2())
8122 // Check that the mask is a broadcast.
8123 int BroadcastIdx = -1;
8125 if (M >= 0 && BroadcastIdx == -1)
8127 else if (M >= 0 && M != BroadcastIdx)
8130 assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
8131 "a sorted mask where the broadcast "
8134 // Go up the chain of (vector) values to find a scalar load that we can
8135 // combine with the broadcast.
8137 switch (V.getOpcode()) {
8138 case ISD::CONCAT_VECTORS: {
8139 int OperandSize = Mask.size() / V.getNumOperands();
8140 V = V.getOperand(BroadcastIdx / OperandSize);
8141 BroadcastIdx %= OperandSize;
8145 case ISD::INSERT_SUBVECTOR: {
8146 SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
8147 auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
8151 int BeginIdx = (int)ConstantIdx->getZExtValue();
8153 BeginIdx + (int)VInner.getSimpleValueType().getVectorNumElements();
8154 if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
8155 BroadcastIdx -= BeginIdx;
8166 // Check if this is a broadcast of a scalar. We special case lowering
8167 // for scalars so that we can more effectively fold with loads.
8168 // First, look through bitcast: if the original value has a larger element
8169 // type than the shuffle, the broadcast element is in essence truncated.
8170 // Make that explicit to ease folding.
8171 if (V.getOpcode() == ISD::BITCAST && VT.isInteger())
8172 if (SDValue TruncBroadcast = lowerVectorShuffleAsTruncBroadcast(
8173 DL, VT, V.getOperand(0), BroadcastIdx, Subtarget, DAG))
8174 return TruncBroadcast;
8176 MVT BroadcastVT = VT;
8178 // Peek through any bitcast (only useful for loads).
8180 while (BC.getOpcode() == ISD::BITCAST)
8181 BC = BC.getOperand(0);
8183 // Also check the simpler case, where we can directly reuse the scalar.
8184 if (V.getOpcode() == ISD::BUILD_VECTOR ||
8185 (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
8186 V = V.getOperand(BroadcastIdx);
8188 // If the scalar isn't a load, we can't broadcast from it in AVX1.
8189 // Only AVX2 has register broadcasts.
8190 if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
8192 } else if (MayFoldLoad(BC) && !cast<LoadSDNode>(BC)->isVolatile()) {
8193 // 32-bit targets need to load i64 as a f64 and then bitcast the result.
8194 if (!Subtarget->is64Bit() && VT.getScalarType() == MVT::i64)
8195 BroadcastVT = MVT::getVectorVT(MVT::f64, VT.getVectorNumElements());
8197 // If we are broadcasting a load that is only used by the shuffle
8198 // then we can reduce the vector load to the broadcasted scalar load.
8199 LoadSDNode *Ld = cast<LoadSDNode>(BC);
8200 SDValue BaseAddr = Ld->getOperand(1);
8201 EVT AddrVT = BaseAddr.getValueType();
8202 EVT SVT = BroadcastVT.getScalarType();
8203 unsigned Offset = BroadcastIdx * SVT.getStoreSize();
8204 SDValue NewAddr = DAG.getNode(
8205 ISD::ADD, DL, AddrVT, BaseAddr,
8206 DAG.getConstant(Offset, DL, AddrVT));
8207 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
8208 DAG.getMachineFunction().getMachineMemOperand(
8209 Ld->getMemOperand(), Offset, SVT.getStoreSize()));
8210 } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
8211 // We can't broadcast from a vector register without AVX2, and we can only
8212 // broadcast from the zero-element of a vector register.
8216 V = DAG.getNode(X86ISD::VBROADCAST, DL, BroadcastVT, V);
8217 return DAG.getBitcast(VT, V);
8220 // Check for whether we can use INSERTPS to perform the shuffle. We only use
8221 // INSERTPS when the V1 elements are already in the correct locations
8222 // because otherwise we can just always use two SHUFPS instructions which
8223 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
8224 // perform INSERTPS if a single V1 element is out of place and all V2
8225 // elements are zeroable.
8226 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
8228 SelectionDAG &DAG) {
8229 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8230 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8231 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8232 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8234 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8237 int V1DstIndex = -1;
8238 int V2DstIndex = -1;
8239 bool V1UsedInPlace = false;
8241 for (int i = 0; i < 4; ++i) {
8242 // Synthesize a zero mask from the zeroable elements (includes undefs).
8248 // Flag if we use any V1 inputs in place.
8250 V1UsedInPlace = true;
8254 // We can only insert a single non-zeroable element.
8255 if (V1DstIndex != -1 || V2DstIndex != -1)
8259 // V1 input out of place for insertion.
8262 // V2 input for insertion.
8267 // Don't bother if we have no (non-zeroable) element for insertion.
8268 if (V1DstIndex == -1 && V2DstIndex == -1)
8271 // Determine element insertion src/dst indices. The src index is from the
8272 // start of the inserted vector, not the start of the concatenated vector.
8273 unsigned V2SrcIndex = 0;
8274 if (V1DstIndex != -1) {
8275 // If we have a V1 input out of place, we use V1 as the V2 element insertion
8276 // and don't use the original V2 at all.
8277 V2SrcIndex = Mask[V1DstIndex];
8278 V2DstIndex = V1DstIndex;
8281 V2SrcIndex = Mask[V2DstIndex] - 4;
8284 // If no V1 inputs are used in place, then the result is created only from
8285 // the zero mask and the V2 insertion - so remove V1 dependency.
8287 V1 = DAG.getUNDEF(MVT::v4f32);
8289 unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
8290 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
8292 // Insert the V2 element into the desired position.
8294 return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
8295 DAG.getConstant(InsertPSMask, DL, MVT::i8));
8298 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
8299 /// UNPCK instruction.
8301 /// This specifically targets cases where we end up with alternating between
8302 /// the two inputs, and so can permute them into something that feeds a single
8303 /// UNPCK instruction. Note that this routine only targets integer vectors
8304 /// because for floating point vectors we have a generalized SHUFPS lowering
8305 /// strategy that handles everything that doesn't *exactly* match an unpack,
8306 /// making this clever lowering unnecessary.
8307 static SDValue lowerVectorShuffleAsPermuteAndUnpack(SDLoc DL, MVT VT,
8308 SDValue V1, SDValue V2,
8310 SelectionDAG &DAG) {
8311 assert(!VT.isFloatingPoint() &&
8312 "This routine only supports integer vectors.");
8313 assert(!isSingleInputShuffleMask(Mask) &&
8314 "This routine should only be used when blending two inputs.");
8315 assert(Mask.size() >= 2 && "Single element masks are invalid.");
8317 int Size = Mask.size();
8319 int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
8320 return M >= 0 && M % Size < Size / 2;
8322 int NumHiInputs = std::count_if(
8323 Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
8325 bool UnpackLo = NumLoInputs >= NumHiInputs;
8327 auto TryUnpack = [&](MVT UnpackVT, int Scale) {
8328 SmallVector<int, 32> V1Mask(Mask.size(), -1);
8329 SmallVector<int, 32> V2Mask(Mask.size(), -1);
8331 for (int i = 0; i < Size; ++i) {
8335 // Each element of the unpack contains Scale elements from this mask.
8336 int UnpackIdx = i / Scale;
8338 // We only handle the case where V1 feeds the first slots of the unpack.
8339 // We rely on canonicalization to ensure this is the case.
8340 if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
8343 // Setup the mask for this input. The indexing is tricky as we have to
8344 // handle the unpack stride.
8345 SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
8346 VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
8350 // If we will have to shuffle both inputs to use the unpack, check whether
8351 // we can just unpack first and shuffle the result. If so, skip this unpack.
8352 if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
8353 !isNoopShuffleMask(V2Mask))
8356 // Shuffle the inputs into place.
8357 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
8358 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
8360 // Cast the inputs to the type we will use to unpack them.
8361 V1 = DAG.getBitcast(UnpackVT, V1);
8362 V2 = DAG.getBitcast(UnpackVT, V2);
8364 // Unpack the inputs and cast the result back to the desired type.
8365 return DAG.getBitcast(
8366 VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8370 // We try each unpack from the largest to the smallest to try and find one
8371 // that fits this mask.
8372 int OrigNumElements = VT.getVectorNumElements();
8373 int OrigScalarSize = VT.getScalarSizeInBits();
8374 for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
8375 int Scale = ScalarSize / OrigScalarSize;
8376 int NumElements = OrigNumElements / Scale;
8377 MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
8378 if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
8382 // If none of the unpack-rooted lowerings worked (or were profitable) try an
8384 if (NumLoInputs == 0 || NumHiInputs == 0) {
8385 assert((NumLoInputs > 0 || NumHiInputs > 0) &&
8386 "We have to have *some* inputs!");
8387 int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
8389 // FIXME: We could consider the total complexity of the permute of each
8390 // possible unpacking. Or at the least we should consider how many
8391 // half-crossings are created.
8392 // FIXME: We could consider commuting the unpacks.
8394 SmallVector<int, 32> PermMask;
8395 PermMask.assign(Size, -1);
8396 for (int i = 0; i < Size; ++i) {
8400 assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
8403 2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
8405 return DAG.getVectorShuffle(
8406 VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
8408 DAG.getUNDEF(VT), PermMask);
8414 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
8416 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
8417 /// support for floating point shuffles but not integer shuffles. These
8418 /// instructions will incur a domain crossing penalty on some chips though so
8419 /// it is better to avoid lowering through this for integer vectors where
8421 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8422 const X86Subtarget *Subtarget,
8423 SelectionDAG &DAG) {
8425 assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
8426 assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8427 assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8428 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8429 ArrayRef<int> Mask = SVOp->getMask();
8430 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8432 if (isSingleInputShuffleMask(Mask)) {
8433 // Use low duplicate instructions for masks that match their pattern.
8434 if (Subtarget->hasSSE3())
8435 if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
8436 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
8438 // Straight shuffle of a single input vector. Simulate this by using the
8439 // single input as both of the "inputs" to this instruction..
8440 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
8442 if (Subtarget->hasAVX()) {
8443 // If we have AVX, we can use VPERMILPS which will allow folding a load
8444 // into the shuffle.
8445 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
8446 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8449 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
8450 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8452 assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
8453 assert(Mask[1] >= 2 && "Non-canonicalized blend!");
8455 // If we have a single input, insert that into V1 if we can do so cheaply.
8456 if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
8457 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8458 DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
8460 // Try inverting the insertion since for v2 masks it is easy to do and we
8461 // can't reliably sort the mask one way or the other.
8462 int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
8463 Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
8464 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8465 DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
8469 // Try to use one of the special instruction patterns to handle two common
8470 // blend patterns if a zero-blend above didn't work.
8471 if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
8472 isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8473 if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
8474 // We can either use a special instruction to load over the low double or
8475 // to move just the low double.
8477 isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
8479 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
8481 if (Subtarget->hasSSE41())
8482 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
8486 // Use dedicated unpack instructions for masks that match their pattern.
8488 lowerVectorShuffleWithUNPCK(DL, MVT::v2f64, Mask, V1, V2, DAG))
8491 unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
8492 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
8493 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8496 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
8498 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
8499 /// the integer unit to minimize domain crossing penalties. However, for blends
8500 /// it falls back to the floating point shuffle operation with appropriate bit
8502 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8503 const X86Subtarget *Subtarget,
8504 SelectionDAG &DAG) {
8506 assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
8507 assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8508 assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8509 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8510 ArrayRef<int> Mask = SVOp->getMask();
8511 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8513 if (isSingleInputShuffleMask(Mask)) {
8514 // Check for being able to broadcast a single element.
8515 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
8516 Mask, Subtarget, DAG))
8519 // Straight shuffle of a single input vector. For everything from SSE2
8520 // onward this has a single fast instruction with no scary immediates.
8521 // We have to map the mask as it is actually a v4i32 shuffle instruction.
8522 V1 = DAG.getBitcast(MVT::v4i32, V1);
8523 int WidenedMask[4] = {
8524 std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
8525 std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
8526 return DAG.getBitcast(
8528 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8529 getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
8531 assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
8532 assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
8533 assert(Mask[0] < 2 && "We sort V1 to be the first input.");
8534 assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
8536 // If we have a blend of two PACKUS operations an the blend aligns with the
8537 // low and half halves, we can just merge the PACKUS operations. This is
8538 // particularly important as it lets us merge shuffles that this routine itself
8540 auto GetPackNode = [](SDValue V) {
8541 while (V.getOpcode() == ISD::BITCAST)
8542 V = V.getOperand(0);
8544 return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
8546 if (SDValue V1Pack = GetPackNode(V1))
8547 if (SDValue V2Pack = GetPackNode(V2))
8548 return DAG.getBitcast(MVT::v2i64,
8549 DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
8550 Mask[0] == 0 ? V1Pack.getOperand(0)
8551 : V1Pack.getOperand(1),
8552 Mask[1] == 2 ? V2Pack.getOperand(0)
8553 : V2Pack.getOperand(1)));
8555 // Try to use shift instructions.
8557 lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
8560 // When loading a scalar and then shuffling it into a vector we can often do
8561 // the insertion cheaply.
8562 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8563 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8565 // Try inverting the insertion since for v2 masks it is easy to do and we
8566 // can't reliably sort the mask one way or the other.
8567 int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
8568 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8569 DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
8572 // We have different paths for blend lowering, but they all must use the
8573 // *exact* same predicate.
8574 bool IsBlendSupported = Subtarget->hasSSE41();
8575 if (IsBlendSupported)
8576 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
8580 // Use dedicated unpack instructions for masks that match their pattern.
8582 lowerVectorShuffleWithUNPCK(DL, MVT::v2i64, Mask, V1, V2, DAG))
8585 // Try to use byte rotation instructions.
8586 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8587 if (Subtarget->hasSSSE3())
8588 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8589 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8592 // If we have direct support for blends, we should lower by decomposing into
8593 // a permute. That will be faster than the domain cross.
8594 if (IsBlendSupported)
8595 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
8598 // We implement this with SHUFPD which is pretty lame because it will likely
8599 // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
8600 // However, all the alternatives are still more cycles and newer chips don't
8601 // have this problem. It would be really nice if x86 had better shuffles here.
8602 V1 = DAG.getBitcast(MVT::v2f64, V1);
8603 V2 = DAG.getBitcast(MVT::v2f64, V2);
8604 return DAG.getBitcast(MVT::v2i64,
8605 DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
8608 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
8610 /// This is used to disable more specialized lowerings when the shufps lowering
8611 /// will happen to be efficient.
8612 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
8613 // This routine only handles 128-bit shufps.
8614 assert(Mask.size() == 4 && "Unsupported mask size!");
8616 // To lower with a single SHUFPS we need to have the low half and high half
8617 // each requiring a single input.
8618 if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
8620 if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
8626 /// \brief Lower a vector shuffle using the SHUFPS instruction.
8628 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
8629 /// It makes no assumptions about whether this is the *best* lowering, it simply
8631 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
8632 ArrayRef<int> Mask, SDValue V1,
8633 SDValue V2, SelectionDAG &DAG) {
8634 SDValue LowV = V1, HighV = V2;
8635 int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
8638 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8640 if (NumV2Elements == 1) {
8642 std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8645 // Compute the index adjacent to V2Index and in the same half by toggling
8647 int V2AdjIndex = V2Index ^ 1;
8649 if (Mask[V2AdjIndex] == -1) {
8650 // Handles all the cases where we have a single V2 element and an undef.
8651 // This will only ever happen in the high lanes because we commute the
8652 // vector otherwise.
8654 std::swap(LowV, HighV);
8655 NewMask[V2Index] -= 4;
8657 // Handle the case where the V2 element ends up adjacent to a V1 element.
8658 // To make this work, blend them together as the first step.
8659 int V1Index = V2AdjIndex;
8660 int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
8661 V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
8662 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8664 // Now proceed to reconstruct the final blend as we have the necessary
8665 // high or low half formed.
8672 NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8673 NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8675 } else if (NumV2Elements == 2) {
8676 if (Mask[0] < 4 && Mask[1] < 4) {
8677 // Handle the easy case where we have V1 in the low lanes and V2 in the
8681 } else if (Mask[2] < 4 && Mask[3] < 4) {
8682 // We also handle the reversed case because this utility may get called
8683 // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8684 // arrange things in the right direction.
8690 // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8691 // trying to place elements directly, just blend them and set up the final
8692 // shuffle to place them.
8694 // The first two blend mask elements are for V1, the second two are for
8696 int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8697 Mask[2] < 4 ? Mask[2] : Mask[3],
8698 (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8699 (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8700 V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8701 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8703 // Now we do a normal shuffle of V1 by giving V1 as both operands to
8706 NewMask[0] = Mask[0] < 4 ? 0 : 2;
8707 NewMask[1] = Mask[0] < 4 ? 2 : 0;
8708 NewMask[2] = Mask[2] < 4 ? 1 : 3;
8709 NewMask[3] = Mask[2] < 4 ? 3 : 1;
8712 return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8713 getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8716 /// \brief Lower 4-lane 32-bit floating point shuffles.
8718 /// Uses instructions exclusively from the floating point unit to minimize
8719 /// domain crossing penalties, as these are sufficient to implement all v4f32
8721 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8722 const X86Subtarget *Subtarget,
8723 SelectionDAG &DAG) {
8725 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8726 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8727 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8728 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8729 ArrayRef<int> Mask = SVOp->getMask();
8730 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8733 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8735 if (NumV2Elements == 0) {
8736 // Check for being able to broadcast a single element.
8737 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8738 Mask, Subtarget, DAG))
8741 // Use even/odd duplicate instructions for masks that match their pattern.
8742 if (Subtarget->hasSSE3()) {
8743 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8744 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8745 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8746 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8749 if (Subtarget->hasAVX()) {
8750 // If we have AVX, we can use VPERMILPS which will allow folding a load
8751 // into the shuffle.
8752 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8753 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8756 // Otherwise, use a straight shuffle of a single input vector. We pass the
8757 // input vector to both operands to simulate this with a SHUFPS.
8758 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8759 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8762 // There are special ways we can lower some single-element blends. However, we
8763 // have custom ways we can lower more complex single-element blends below that
8764 // we defer to if both this and BLENDPS fail to match, so restrict this to
8765 // when the V2 input is targeting element 0 of the mask -- that is the fast
8767 if (NumV2Elements == 1 && Mask[0] >= 4)
8768 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8769 Mask, Subtarget, DAG))
8772 if (Subtarget->hasSSE41()) {
8773 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8777 // Use INSERTPS if we can complete the shuffle efficiently.
8778 if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8781 if (!isSingleSHUFPSMask(Mask))
8782 if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8783 DL, MVT::v4f32, V1, V2, Mask, DAG))
8787 // Use dedicated unpack instructions for masks that match their pattern.
8789 lowerVectorShuffleWithUNPCK(DL, MVT::v4f32, Mask, V1, V2, DAG))
8792 // Otherwise fall back to a SHUFPS lowering strategy.
8793 return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8796 /// \brief Lower 4-lane i32 vector shuffles.
8798 /// We try to handle these with integer-domain shuffles where we can, but for
8799 /// blends we use the floating point domain blend instructions.
8800 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8801 const X86Subtarget *Subtarget,
8802 SelectionDAG &DAG) {
8804 assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8805 assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8806 assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8807 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8808 ArrayRef<int> Mask = SVOp->getMask();
8809 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8811 // Whenever we can lower this as a zext, that instruction is strictly faster
8812 // than any alternative. It also allows us to fold memory operands into the
8813 // shuffle in many cases.
8814 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8815 Mask, Subtarget, DAG))
8819 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8821 if (NumV2Elements == 0) {
8822 // Check for being able to broadcast a single element.
8823 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8824 Mask, Subtarget, DAG))
8827 // Straight shuffle of a single input vector. For everything from SSE2
8828 // onward this has a single fast instruction with no scary immediates.
8829 // We coerce the shuffle pattern to be compatible with UNPCK instructions
8830 // but we aren't actually going to use the UNPCK instruction because doing
8831 // so prevents folding a load into this instruction or making a copy.
8832 const int UnpackLoMask[] = {0, 0, 1, 1};
8833 const int UnpackHiMask[] = {2, 2, 3, 3};
8834 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8835 Mask = UnpackLoMask;
8836 else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8837 Mask = UnpackHiMask;
8839 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8840 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8843 // Try to use shift instructions.
8845 lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8848 // There are special ways we can lower some single-element blends.
8849 if (NumV2Elements == 1)
8850 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8851 Mask, Subtarget, DAG))
8854 // We have different paths for blend lowering, but they all must use the
8855 // *exact* same predicate.
8856 bool IsBlendSupported = Subtarget->hasSSE41();
8857 if (IsBlendSupported)
8858 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8862 if (SDValue Masked =
8863 lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8866 // Use dedicated unpack instructions for masks that match their pattern.
8868 lowerVectorShuffleWithUNPCK(DL, MVT::v4i32, Mask, V1, V2, DAG))
8871 // Try to use byte rotation instructions.
8872 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8873 if (Subtarget->hasSSSE3())
8874 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8875 DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8878 // If we have direct support for blends, we should lower by decomposing into
8879 // a permute. That will be faster than the domain cross.
8880 if (IsBlendSupported)
8881 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8884 // Try to lower by permuting the inputs into an unpack instruction.
8885 if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v4i32, V1,
8889 // We implement this with SHUFPS because it can blend from two vectors.
8890 // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8891 // up the inputs, bypassing domain shift penalties that we would encur if we
8892 // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8894 return DAG.getBitcast(
8896 DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8897 DAG.getBitcast(MVT::v4f32, V2), Mask));
8900 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8901 /// shuffle lowering, and the most complex part.
8903 /// The lowering strategy is to try to form pairs of input lanes which are
8904 /// targeted at the same half of the final vector, and then use a dword shuffle
8905 /// to place them onto the right half, and finally unpack the paired lanes into
8906 /// their final position.
8908 /// The exact breakdown of how to form these dword pairs and align them on the
8909 /// correct sides is really tricky. See the comments within the function for
8910 /// more of the details.
8912 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8913 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8914 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8915 /// vector, form the analogous 128-bit 8-element Mask.
8916 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8917 SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8918 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8919 assert(VT.getVectorElementType() == MVT::i16 && "Bad input type!");
8920 MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8922 assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8923 MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8924 MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8926 SmallVector<int, 4> LoInputs;
8927 std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8928 [](int M) { return M >= 0; });
8929 std::sort(LoInputs.begin(), LoInputs.end());
8930 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8931 SmallVector<int, 4> HiInputs;
8932 std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8933 [](int M) { return M >= 0; });
8934 std::sort(HiInputs.begin(), HiInputs.end());
8935 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8937 std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8938 int NumHToL = LoInputs.size() - NumLToL;
8940 std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8941 int NumHToH = HiInputs.size() - NumLToH;
8942 MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8943 MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8944 MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8945 MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8947 // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8948 // such inputs we can swap two of the dwords across the half mark and end up
8949 // with <=2 inputs to each half in each half. Once there, we can fall through
8950 // to the generic code below. For example:
8952 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8953 // Mask: [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8955 // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8956 // and an existing 2-into-2 on the other half. In this case we may have to
8957 // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8958 // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8959 // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8960 // because any other situation (including a 3-into-1 or 1-into-3 in the other
8961 // half than the one we target for fixing) will be fixed when we re-enter this
8962 // path. We will also combine away any sequence of PSHUFD instructions that
8963 // result into a single instruction. Here is an example of the tricky case:
8965 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8966 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8968 // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8970 // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8971 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8973 // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8974 // Mask: [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8976 // The result is fine to be handled by the generic logic.
8977 auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8978 ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8979 int AOffset, int BOffset) {
8980 assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8981 "Must call this with A having 3 or 1 inputs from the A half.");
8982 assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8983 "Must call this with B having 1 or 3 inputs from the B half.");
8984 assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8985 "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8987 bool ThreeAInputs = AToAInputs.size() == 3;
8989 // Compute the index of dword with only one word among the three inputs in
8990 // a half by taking the sum of the half with three inputs and subtracting
8991 // the sum of the actual three inputs. The difference is the remaining
8994 int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
8995 int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
8996 int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
8997 ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
8998 int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
8999 int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
9000 int TripleNonInputIdx =
9001 TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
9002 TripleDWord = TripleNonInputIdx / 2;
9004 // We use xor with one to compute the adjacent DWord to whichever one the
9006 OneInputDWord = (OneInput / 2) ^ 1;
9008 // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
9009 // and BToA inputs. If there is also such a problem with the BToB and AToB
9010 // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
9011 // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
9012 // is essential that we don't *create* a 3<-1 as then we might oscillate.
9013 if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
9014 // Compute how many inputs will be flipped by swapping these DWords. We
9016 // to balance this to ensure we don't form a 3-1 shuffle in the other
9018 int NumFlippedAToBInputs =
9019 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
9020 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
9021 int NumFlippedBToBInputs =
9022 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
9023 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
9024 if ((NumFlippedAToBInputs == 1 &&
9025 (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
9026 (NumFlippedBToBInputs == 1 &&
9027 (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
9028 // We choose whether to fix the A half or B half based on whether that
9029 // half has zero flipped inputs. At zero, we may not be able to fix it
9030 // with that half. We also bias towards fixing the B half because that
9031 // will more commonly be the high half, and we have to bias one way.
9032 auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
9033 ArrayRef<int> Inputs) {
9034 int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
9035 bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
9036 PinnedIdx ^ 1) != Inputs.end();
9037 // Determine whether the free index is in the flipped dword or the
9038 // unflipped dword based on where the pinned index is. We use this bit
9039 // in an xor to conditionally select the adjacent dword.
9040 int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
9041 bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
9042 FixFreeIdx) != Inputs.end();
9043 if (IsFixIdxInput == IsFixFreeIdxInput)
9045 IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
9046 FixFreeIdx) != Inputs.end();
9047 assert(IsFixIdxInput != IsFixFreeIdxInput &&
9048 "We need to be changing the number of flipped inputs!");
9049 int PSHUFHalfMask[] = {0, 1, 2, 3};
9050 std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
9051 V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
9053 getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
9056 if (M != -1 && M == FixIdx)
9058 else if (M != -1 && M == FixFreeIdx)
9061 if (NumFlippedBToBInputs != 0) {
9063 BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
9064 FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
9066 assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
9067 int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
9068 FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
9073 int PSHUFDMask[] = {0, 1, 2, 3};
9074 PSHUFDMask[ADWord] = BDWord;
9075 PSHUFDMask[BDWord] = ADWord;
9078 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
9079 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9081 // Adjust the mask to match the new locations of A and B.
9083 if (M != -1 && M/2 == ADWord)
9084 M = 2 * BDWord + M % 2;
9085 else if (M != -1 && M/2 == BDWord)
9086 M = 2 * ADWord + M % 2;
9088 // Recurse back into this routine to re-compute state now that this isn't
9089 // a 3 and 1 problem.
9090 return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
9093 if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
9094 return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
9095 else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
9096 return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
9098 // At this point there are at most two inputs to the low and high halves from
9099 // each half. That means the inputs can always be grouped into dwords and
9100 // those dwords can then be moved to the correct half with a dword shuffle.
9101 // We use at most one low and one high word shuffle to collect these paired
9102 // inputs into dwords, and finally a dword shuffle to place them.
9103 int PSHUFLMask[4] = {-1, -1, -1, -1};
9104 int PSHUFHMask[4] = {-1, -1, -1, -1};
9105 int PSHUFDMask[4] = {-1, -1, -1, -1};
9107 // First fix the masks for all the inputs that are staying in their
9108 // original halves. This will then dictate the targets of the cross-half
9110 auto fixInPlaceInputs =
9111 [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
9112 MutableArrayRef<int> SourceHalfMask,
9113 MutableArrayRef<int> HalfMask, int HalfOffset) {
9114 if (InPlaceInputs.empty())
9116 if (InPlaceInputs.size() == 1) {
9117 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
9118 InPlaceInputs[0] - HalfOffset;
9119 PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
9122 if (IncomingInputs.empty()) {
9123 // Just fix all of the in place inputs.
9124 for (int Input : InPlaceInputs) {
9125 SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
9126 PSHUFDMask[Input / 2] = Input / 2;
9131 assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
9132 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
9133 InPlaceInputs[0] - HalfOffset;
9134 // Put the second input next to the first so that they are packed into
9135 // a dword. We find the adjacent index by toggling the low bit.
9136 int AdjIndex = InPlaceInputs[0] ^ 1;
9137 SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
9138 std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
9139 PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
9141 fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
9142 fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
9144 // Now gather the cross-half inputs and place them into a free dword of
9145 // their target half.
9146 // FIXME: This operation could almost certainly be simplified dramatically to
9147 // look more like the 3-1 fixing operation.
9148 auto moveInputsToRightHalf = [&PSHUFDMask](
9149 MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
9150 MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
9151 MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
9153 auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
9154 return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
9156 auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
9158 int LowWord = Word & ~1;
9159 int HighWord = Word | 1;
9160 return isWordClobbered(SourceHalfMask, LowWord) ||
9161 isWordClobbered(SourceHalfMask, HighWord);
9164 if (IncomingInputs.empty())
9167 if (ExistingInputs.empty()) {
9168 // Map any dwords with inputs from them into the right half.
9169 for (int Input : IncomingInputs) {
9170 // If the source half mask maps over the inputs, turn those into
9171 // swaps and use the swapped lane.
9172 if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
9173 if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
9174 SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
9175 Input - SourceOffset;
9176 // We have to swap the uses in our half mask in one sweep.
9177 for (int &M : HalfMask)
9178 if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
9180 else if (M == Input)
9181 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
9183 assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
9184 Input - SourceOffset &&
9185 "Previous placement doesn't match!");
9187 // Note that this correctly re-maps both when we do a swap and when
9188 // we observe the other side of the swap above. We rely on that to
9189 // avoid swapping the members of the input list directly.
9190 Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
9193 // Map the input's dword into the correct half.
9194 if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
9195 PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
9197 assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
9199 "Previous placement doesn't match!");
9202 // And just directly shift any other-half mask elements to be same-half
9203 // as we will have mirrored the dword containing the element into the
9204 // same position within that half.
9205 for (int &M : HalfMask)
9206 if (M >= SourceOffset && M < SourceOffset + 4) {
9207 M = M - SourceOffset + DestOffset;
9208 assert(M >= 0 && "This should never wrap below zero!");
9213 // Ensure we have the input in a viable dword of its current half. This
9214 // is particularly tricky because the original position may be clobbered
9215 // by inputs being moved and *staying* in that half.
9216 if (IncomingInputs.size() == 1) {
9217 if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
9218 int InputFixed = std::find(std::begin(SourceHalfMask),
9219 std::end(SourceHalfMask), -1) -
9220 std::begin(SourceHalfMask) + SourceOffset;
9221 SourceHalfMask[InputFixed - SourceOffset] =
9222 IncomingInputs[0] - SourceOffset;
9223 std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
9225 IncomingInputs[0] = InputFixed;
9227 } else if (IncomingInputs.size() == 2) {
9228 if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
9229 isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
9230 // We have two non-adjacent or clobbered inputs we need to extract from
9231 // the source half. To do this, we need to map them into some adjacent
9232 // dword slot in the source mask.
9233 int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
9234 IncomingInputs[1] - SourceOffset};
9236 // If there is a free slot in the source half mask adjacent to one of
9237 // the inputs, place the other input in it. We use (Index XOR 1) to
9238 // compute an adjacent index.
9239 if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
9240 SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
9241 SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
9242 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
9243 InputsFixed[1] = InputsFixed[0] ^ 1;
9244 } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
9245 SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
9246 SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
9247 SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
9248 InputsFixed[0] = InputsFixed[1] ^ 1;
9249 } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
9250 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
9251 // The two inputs are in the same DWord but it is clobbered and the
9252 // adjacent DWord isn't used at all. Move both inputs to the free
9254 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
9255 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
9256 InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
9257 InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
9259 // The only way we hit this point is if there is no clobbering
9260 // (because there are no off-half inputs to this half) and there is no
9261 // free slot adjacent to one of the inputs. In this case, we have to
9262 // swap an input with a non-input.
9263 for (int i = 0; i < 4; ++i)
9264 assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
9265 "We can't handle any clobbers here!");
9266 assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
9267 "Cannot have adjacent inputs here!");
9269 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
9270 SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
9272 // We also have to update the final source mask in this case because
9273 // it may need to undo the above swap.
9274 for (int &M : FinalSourceHalfMask)
9275 if (M == (InputsFixed[0] ^ 1) + SourceOffset)
9276 M = InputsFixed[1] + SourceOffset;
9277 else if (M == InputsFixed[1] + SourceOffset)
9278 M = (InputsFixed[0] ^ 1) + SourceOffset;
9280 InputsFixed[1] = InputsFixed[0] ^ 1;
9283 // Point everything at the fixed inputs.
9284 for (int &M : HalfMask)
9285 if (M == IncomingInputs[0])
9286 M = InputsFixed[0] + SourceOffset;
9287 else if (M == IncomingInputs[1])
9288 M = InputsFixed[1] + SourceOffset;
9290 IncomingInputs[0] = InputsFixed[0] + SourceOffset;
9291 IncomingInputs[1] = InputsFixed[1] + SourceOffset;
9294 llvm_unreachable("Unhandled input size!");
9297 // Now hoist the DWord down to the right half.
9298 int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
9299 assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
9300 PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
9301 for (int &M : HalfMask)
9302 for (int Input : IncomingInputs)
9304 M = FreeDWord * 2 + Input % 2;
9306 moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
9307 /*SourceOffset*/ 4, /*DestOffset*/ 0);
9308 moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
9309 /*SourceOffset*/ 0, /*DestOffset*/ 4);
9311 // Now enact all the shuffles we've computed to move the inputs into their
9313 if (!isNoopShuffleMask(PSHUFLMask))
9314 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
9315 getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
9316 if (!isNoopShuffleMask(PSHUFHMask))
9317 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
9318 getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
9319 if (!isNoopShuffleMask(PSHUFDMask))
9322 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
9323 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9325 // At this point, each half should contain all its inputs, and we can then
9326 // just shuffle them into their final position.
9327 assert(std::count_if(LoMask.begin(), LoMask.end(),
9328 [](int M) { return M >= 4; }) == 0 &&
9329 "Failed to lift all the high half inputs to the low mask!");
9330 assert(std::count_if(HiMask.begin(), HiMask.end(),
9331 [](int M) { return M >= 0 && M < 4; }) == 0 &&
9332 "Failed to lift all the low half inputs to the high mask!");
9334 // Do a half shuffle for the low mask.
9335 if (!isNoopShuffleMask(LoMask))
9336 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
9337 getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
9339 // Do a half shuffle with the high mask after shifting its values down.
9340 for (int &M : HiMask)
9343 if (!isNoopShuffleMask(HiMask))
9344 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
9345 getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
9350 /// \brief Helper to form a PSHUFB-based shuffle+blend.
9351 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
9352 SDValue V2, ArrayRef<int> Mask,
9353 SelectionDAG &DAG, bool &V1InUse,
9355 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
9361 int Size = Mask.size();
9362 int Scale = 16 / Size;
9363 for (int i = 0; i < 16; ++i) {
9364 if (Mask[i / Scale] == -1) {
9365 V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
9367 const int ZeroMask = 0x80;
9368 int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
9370 int V2Idx = Mask[i / Scale] < Size
9372 : (Mask[i / Scale] - Size) * Scale + i % Scale;
9373 if (Zeroable[i / Scale])
9374 V1Idx = V2Idx = ZeroMask;
9375 V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
9376 V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
9377 V1InUse |= (ZeroMask != V1Idx);
9378 V2InUse |= (ZeroMask != V2Idx);
9383 V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9384 DAG.getBitcast(MVT::v16i8, V1),
9385 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
9387 V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9388 DAG.getBitcast(MVT::v16i8, V2),
9389 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
9391 // If we need shuffled inputs from both, blend the two.
9393 if (V1InUse && V2InUse)
9394 V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
9396 V = V1InUse ? V1 : V2;
9398 // Cast the result back to the correct type.
9399 return DAG.getBitcast(VT, V);
9402 /// \brief Generic lowering of 8-lane i16 shuffles.
9404 /// This handles both single-input shuffles and combined shuffle/blends with
9405 /// two inputs. The single input shuffles are immediately delegated to
9406 /// a dedicated lowering routine.
9408 /// The blends are lowered in one of three fundamental ways. If there are few
9409 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
9410 /// of the input is significantly cheaper when lowered as an interleaving of
9411 /// the two inputs, try to interleave them. Otherwise, blend the low and high
9412 /// halves of the inputs separately (making them have relatively few inputs)
9413 /// and then concatenate them.
9414 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9415 const X86Subtarget *Subtarget,
9416 SelectionDAG &DAG) {
9418 assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
9419 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9420 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9421 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9422 ArrayRef<int> OrigMask = SVOp->getMask();
9423 int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
9424 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
9425 MutableArrayRef<int> Mask(MaskStorage);
9427 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9429 // Whenever we can lower this as a zext, that instruction is strictly faster
9430 // than any alternative.
9431 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9432 DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
9435 auto isV1 = [](int M) { return M >= 0 && M < 8; };
9437 auto isV2 = [](int M) { return M >= 8; };
9439 int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
9441 if (NumV2Inputs == 0) {
9442 // Check for being able to broadcast a single element.
9443 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
9444 Mask, Subtarget, DAG))
9447 // Try to use shift instructions.
9449 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
9452 // Use dedicated unpack instructions for masks that match their pattern.
9454 lowerVectorShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
9457 // Try to use byte rotation instructions.
9458 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
9459 Mask, Subtarget, DAG))
9462 return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
9466 assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
9467 "All single-input shuffles should be canonicalized to be V1-input "
9470 // Try to use shift instructions.
9472 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
9475 // See if we can use SSE4A Extraction / Insertion.
9476 if (Subtarget->hasSSE4A())
9477 if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
9480 // There are special ways we can lower some single-element blends.
9481 if (NumV2Inputs == 1)
9482 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
9483 Mask, Subtarget, DAG))
9486 // We have different paths for blend lowering, but they all must use the
9487 // *exact* same predicate.
9488 bool IsBlendSupported = Subtarget->hasSSE41();
9489 if (IsBlendSupported)
9490 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
9494 if (SDValue Masked =
9495 lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
9498 // Use dedicated unpack instructions for masks that match their pattern.
9500 lowerVectorShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
9503 // Try to use byte rotation instructions.
9504 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9505 DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
9508 if (SDValue BitBlend =
9509 lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
9512 if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v8i16, V1,
9516 // If we can't directly blend but can use PSHUFB, that will be better as it
9517 // can both shuffle and set up the inefficient blend.
9518 if (!IsBlendSupported && Subtarget->hasSSSE3()) {
9519 bool V1InUse, V2InUse;
9520 return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
9524 // We can always bit-blend if we have to so the fallback strategy is to
9525 // decompose into single-input permutes and blends.
9526 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
9530 /// \brief Check whether a compaction lowering can be done by dropping even
9531 /// elements and compute how many times even elements must be dropped.
9533 /// This handles shuffles which take every Nth element where N is a power of
9534 /// two. Example shuffle masks:
9536 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14
9537 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
9538 /// N = 2: 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12
9539 /// N = 2: 0, 4, 8, 12, 16, 20, 24, 28, 0, 4, 8, 12, 16, 20, 24, 28
9540 /// N = 3: 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8
9541 /// N = 3: 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24
9543 /// Any of these lanes can of course be undef.
9545 /// This routine only supports N <= 3.
9546 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
9549 /// \returns N above, or the number of times even elements must be dropped if
9550 /// there is such a number. Otherwise returns zero.
9551 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
9552 // Figure out whether we're looping over two inputs or just one.
9553 bool IsSingleInput = isSingleInputShuffleMask(Mask);
9555 // The modulus for the shuffle vector entries is based on whether this is
9556 // a single input or not.
9557 int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
9558 assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
9559 "We should only be called with masks with a power-of-2 size!");
9561 uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
9563 // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
9564 // and 2^3 simultaneously. This is because we may have ambiguity with
9565 // partially undef inputs.
9566 bool ViableForN[3] = {true, true, true};
9568 for (int i = 0, e = Mask.size(); i < e; ++i) {
9569 // Ignore undef lanes, we'll optimistically collapse them to the pattern we
9574 bool IsAnyViable = false;
9575 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9576 if (ViableForN[j]) {
9579 // The shuffle mask must be equal to (i * 2^N) % M.
9580 if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
9583 ViableForN[j] = false;
9585 // Early exit if we exhaust the possible powers of two.
9590 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9594 // Return 0 as there is no viable power of two.
9598 /// \brief Generic lowering of v16i8 shuffles.
9600 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
9601 /// detect any complexity reducing interleaving. If that doesn't help, it uses
9602 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
9603 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
9605 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9606 const X86Subtarget *Subtarget,
9607 SelectionDAG &DAG) {
9609 assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
9610 assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9611 assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9612 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9613 ArrayRef<int> Mask = SVOp->getMask();
9614 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9616 // Try to use shift instructions.
9618 lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
9621 // Try to use byte rotation instructions.
9622 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9623 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9626 // Try to use a zext lowering.
9627 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9628 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9631 // See if we can use SSE4A Extraction / Insertion.
9632 if (Subtarget->hasSSE4A())
9633 if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
9637 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
9639 // For single-input shuffles, there are some nicer lowering tricks we can use.
9640 if (NumV2Elements == 0) {
9641 // Check for being able to broadcast a single element.
9642 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
9643 Mask, Subtarget, DAG))
9646 // Check whether we can widen this to an i16 shuffle by duplicating bytes.
9647 // Notably, this handles splat and partial-splat shuffles more efficiently.
9648 // However, it only makes sense if the pre-duplication shuffle simplifies
9649 // things significantly. Currently, this means we need to be able to
9650 // express the pre-duplication shuffle as an i16 shuffle.
9652 // FIXME: We should check for other patterns which can be widened into an
9653 // i16 shuffle as well.
9654 auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9655 for (int i = 0; i < 16; i += 2)
9656 if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9661 auto tryToWidenViaDuplication = [&]() -> SDValue {
9662 if (!canWidenViaDuplication(Mask))
9664 SmallVector<int, 4> LoInputs;
9665 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9666 [](int M) { return M >= 0 && M < 8; });
9667 std::sort(LoInputs.begin(), LoInputs.end());
9668 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9670 SmallVector<int, 4> HiInputs;
9671 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9672 [](int M) { return M >= 8; });
9673 std::sort(HiInputs.begin(), HiInputs.end());
9674 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9677 bool TargetLo = LoInputs.size() >= HiInputs.size();
9678 ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9679 ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9681 int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9682 SmallDenseMap<int, int, 8> LaneMap;
9683 for (int I : InPlaceInputs) {
9684 PreDupI16Shuffle[I/2] = I/2;
9687 int j = TargetLo ? 0 : 4, je = j + 4;
9688 for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9689 // Check if j is already a shuffle of this input. This happens when
9690 // there are two adjacent bytes after we move the low one.
9691 if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9692 // If we haven't yet mapped the input, search for a slot into which
9694 while (j < je && PreDupI16Shuffle[j] != -1)
9698 // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9701 // Map this input with the i16 shuffle.
9702 PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9705 // Update the lane map based on the mapping we ended up with.
9706 LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9708 V1 = DAG.getBitcast(
9710 DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9711 DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9713 // Unpack the bytes to form the i16s that will be shuffled into place.
9714 V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9715 MVT::v16i8, V1, V1);
9717 int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9718 for (int i = 0; i < 16; ++i)
9719 if (Mask[i] != -1) {
9720 int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9721 assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9722 if (PostDupI16Shuffle[i / 2] == -1)
9723 PostDupI16Shuffle[i / 2] = MappedMask;
9725 assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9726 "Conflicting entrties in the original shuffle!");
9728 return DAG.getBitcast(
9730 DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9731 DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9733 if (SDValue V = tryToWidenViaDuplication())
9737 if (SDValue Masked =
9738 lowerVectorShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask, DAG))
9741 // Use dedicated unpack instructions for masks that match their pattern.
9743 lowerVectorShuffleWithUNPCK(DL, MVT::v16i8, Mask, V1, V2, DAG))
9746 // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9747 // with PSHUFB. It is important to do this before we attempt to generate any
9748 // blends but after all of the single-input lowerings. If the single input
9749 // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9750 // want to preserve that and we can DAG combine any longer sequences into
9751 // a PSHUFB in the end. But once we start blending from multiple inputs,
9752 // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9753 // and there are *very* few patterns that would actually be faster than the
9754 // PSHUFB approach because of its ability to zero lanes.
9756 // FIXME: The only exceptions to the above are blends which are exact
9757 // interleavings with direct instructions supporting them. We currently don't
9758 // handle those well here.
9759 if (Subtarget->hasSSSE3()) {
9760 bool V1InUse = false;
9761 bool V2InUse = false;
9763 SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9764 DAG, V1InUse, V2InUse);
9766 // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9767 // do so. This avoids using them to handle blends-with-zero which is
9768 // important as a single pshufb is significantly faster for that.
9769 if (V1InUse && V2InUse) {
9770 if (Subtarget->hasSSE41())
9771 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9772 Mask, Subtarget, DAG))
9775 // We can use an unpack to do the blending rather than an or in some
9776 // cases. Even though the or may be (very minorly) more efficient, we
9777 // preference this lowering because there are common cases where part of
9778 // the complexity of the shuffles goes away when we do the final blend as
9780 // FIXME: It might be worth trying to detect if the unpack-feeding
9781 // shuffles will both be pshufb, in which case we shouldn't bother with
9783 if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(
9784 DL, MVT::v16i8, V1, V2, Mask, DAG))
9791 // There are special ways we can lower some single-element blends.
9792 if (NumV2Elements == 1)
9793 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9794 Mask, Subtarget, DAG))
9797 if (SDValue BitBlend =
9798 lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9801 // Check whether a compaction lowering can be done. This handles shuffles
9802 // which take every Nth element for some even N. See the helper function for
9805 // We special case these as they can be particularly efficiently handled with
9806 // the PACKUSB instruction on x86 and they show up in common patterns of
9807 // rearranging bytes to truncate wide elements.
9808 if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9809 // NumEvenDrops is the power of two stride of the elements. Another way of
9810 // thinking about it is that we need to drop the even elements this many
9811 // times to get the original input.
9812 bool IsSingleInput = isSingleInputShuffleMask(Mask);
9814 // First we need to zero all the dropped bytes.
9815 assert(NumEvenDrops <= 3 &&
9816 "No support for dropping even elements more than 3 times.");
9817 // We use the mask type to pick which bytes are preserved based on how many
9818 // elements are dropped.
9819 MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9820 SDValue ByteClearMask = DAG.getBitcast(
9821 MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9822 V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9824 V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9826 // Now pack things back together.
9827 V1 = DAG.getBitcast(MVT::v8i16, V1);
9828 V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9829 SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9830 for (int i = 1; i < NumEvenDrops; ++i) {
9831 Result = DAG.getBitcast(MVT::v8i16, Result);
9832 Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9838 // Handle multi-input cases by blending single-input shuffles.
9839 if (NumV2Elements > 0)
9840 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9843 // The fallback path for single-input shuffles widens this into two v8i16
9844 // vectors with unpacks, shuffles those, and then pulls them back together
9848 int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9849 int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9850 for (int i = 0; i < 16; ++i)
9852 (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9854 SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9856 SDValue VLoHalf, VHiHalf;
9857 // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9858 // them out and avoid using UNPCK{L,H} to extract the elements of V as
9860 if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9861 [](int M) { return M >= 0 && M % 2 == 1; }) &&
9862 std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9863 [](int M) { return M >= 0 && M % 2 == 1; })) {
9864 // Use a mask to drop the high bytes.
9865 VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9866 VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9867 DAG.getConstant(0x00FF, DL, MVT::v8i16));
9869 // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9870 VHiHalf = DAG.getUNDEF(MVT::v8i16);
9872 // Squash the masks to point directly into VLoHalf.
9873 for (int &M : LoBlendMask)
9876 for (int &M : HiBlendMask)
9880 // Otherwise just unpack the low half of V into VLoHalf and the high half into
9881 // VHiHalf so that we can blend them as i16s.
9882 VLoHalf = DAG.getBitcast(
9883 MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9884 VHiHalf = DAG.getBitcast(
9885 MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9888 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9889 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9891 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9894 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9896 /// This routine breaks down the specific type of 128-bit shuffle and
9897 /// dispatches to the lowering routines accordingly.
9898 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9899 MVT VT, const X86Subtarget *Subtarget,
9900 SelectionDAG &DAG) {
9901 switch (VT.SimpleTy) {
9903 return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9905 return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9907 return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9909 return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9911 return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9913 return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9916 llvm_unreachable("Unimplemented!");
9920 /// \brief Helper function to test whether a shuffle mask could be
9921 /// simplified by widening the elements being shuffled.
9923 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9924 /// leaves it in an unspecified state.
9926 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9927 /// shuffle masks. The latter have the special property of a '-2' representing
9928 /// a zero-ed lane of a vector.
9929 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9930 SmallVectorImpl<int> &WidenedMask) {
9931 for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9932 // If both elements are undef, its trivial.
9933 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9934 WidenedMask.push_back(SM_SentinelUndef);
9938 // Check for an undef mask and a mask value properly aligned to fit with
9939 // a pair of values. If we find such a case, use the non-undef mask's value.
9940 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9941 WidenedMask.push_back(Mask[i + 1] / 2);
9944 if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9945 WidenedMask.push_back(Mask[i] / 2);
9949 // When zeroing, we need to spread the zeroing across both lanes to widen.
9950 if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9951 if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9952 (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9953 WidenedMask.push_back(SM_SentinelZero);
9959 // Finally check if the two mask values are adjacent and aligned with
9961 if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9962 WidenedMask.push_back(Mask[i] / 2);
9966 // Otherwise we can't safely widen the elements used in this shuffle.
9969 assert(WidenedMask.size() == Mask.size() / 2 &&
9970 "Incorrect size of mask after widening the elements!");
9975 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9977 /// This routine just extracts two subvectors, shuffles them independently, and
9978 /// then concatenates them back together. This should work effectively with all
9979 /// AVX vector shuffle types.
9980 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9981 SDValue V2, ArrayRef<int> Mask,
9982 SelectionDAG &DAG) {
9983 assert(VT.getSizeInBits() >= 256 &&
9984 "Only for 256-bit or wider vector shuffles!");
9985 assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9986 assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9988 ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9989 ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9991 int NumElements = VT.getVectorNumElements();
9992 int SplitNumElements = NumElements / 2;
9993 MVT ScalarVT = VT.getVectorElementType();
9994 MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9996 // Rather than splitting build-vectors, just build two narrower build
9997 // vectors. This helps shuffling with splats and zeros.
9998 auto SplitVector = [&](SDValue V) {
9999 while (V.getOpcode() == ISD::BITCAST)
10000 V = V->getOperand(0);
10002 MVT OrigVT = V.getSimpleValueType();
10003 int OrigNumElements = OrigVT.getVectorNumElements();
10004 int OrigSplitNumElements = OrigNumElements / 2;
10005 MVT OrigScalarVT = OrigVT.getVectorElementType();
10006 MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
10010 auto *BV = dyn_cast<BuildVectorSDNode>(V);
10012 LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
10013 DAG.getIntPtrConstant(0, DL));
10014 HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
10015 DAG.getIntPtrConstant(OrigSplitNumElements, DL));
10018 SmallVector<SDValue, 16> LoOps, HiOps;
10019 for (int i = 0; i < OrigSplitNumElements; ++i) {
10020 LoOps.push_back(BV->getOperand(i));
10021 HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
10023 LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
10024 HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
10026 return std::make_pair(DAG.getBitcast(SplitVT, LoV),
10027 DAG.getBitcast(SplitVT, HiV));
10030 SDValue LoV1, HiV1, LoV2, HiV2;
10031 std::tie(LoV1, HiV1) = SplitVector(V1);
10032 std::tie(LoV2, HiV2) = SplitVector(V2);
10034 // Now create two 4-way blends of these half-width vectors.
10035 auto HalfBlend = [&](ArrayRef<int> HalfMask) {
10036 bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
10037 SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
10038 for (int i = 0; i < SplitNumElements; ++i) {
10039 int M = HalfMask[i];
10040 if (M >= NumElements) {
10041 if (M >= NumElements + SplitNumElements)
10045 V2BlendMask.push_back(M - NumElements);
10046 V1BlendMask.push_back(-1);
10047 BlendMask.push_back(SplitNumElements + i);
10048 } else if (M >= 0) {
10049 if (M >= SplitNumElements)
10053 V2BlendMask.push_back(-1);
10054 V1BlendMask.push_back(M);
10055 BlendMask.push_back(i);
10057 V2BlendMask.push_back(-1);
10058 V1BlendMask.push_back(-1);
10059 BlendMask.push_back(-1);
10063 // Because the lowering happens after all combining takes place, we need to
10064 // manually combine these blend masks as much as possible so that we create
10065 // a minimal number of high-level vector shuffle nodes.
10067 // First try just blending the halves of V1 or V2.
10068 if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
10069 return DAG.getUNDEF(SplitVT);
10070 if (!UseLoV2 && !UseHiV2)
10071 return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
10072 if (!UseLoV1 && !UseHiV1)
10073 return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
10075 SDValue V1Blend, V2Blend;
10076 if (UseLoV1 && UseHiV1) {
10078 DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
10080 // We only use half of V1 so map the usage down into the final blend mask.
10081 V1Blend = UseLoV1 ? LoV1 : HiV1;
10082 for (int i = 0; i < SplitNumElements; ++i)
10083 if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
10084 BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
10086 if (UseLoV2 && UseHiV2) {
10088 DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
10090 // We only use half of V2 so map the usage down into the final blend mask.
10091 V2Blend = UseLoV2 ? LoV2 : HiV2;
10092 for (int i = 0; i < SplitNumElements; ++i)
10093 if (BlendMask[i] >= SplitNumElements)
10094 BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
10096 return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
10098 SDValue Lo = HalfBlend(LoMask);
10099 SDValue Hi = HalfBlend(HiMask);
10100 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
10103 /// \brief Either split a vector in halves or decompose the shuffles and the
10106 /// This is provided as a good fallback for many lowerings of non-single-input
10107 /// shuffles with more than one 128-bit lane. In those cases, we want to select
10108 /// between splitting the shuffle into 128-bit components and stitching those
10109 /// back together vs. extracting the single-input shuffles and blending those
10111 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
10112 SDValue V2, ArrayRef<int> Mask,
10113 SelectionDAG &DAG) {
10114 assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
10115 "lower single-input shuffles as it "
10116 "could then recurse on itself.");
10117 int Size = Mask.size();
10119 // If this can be modeled as a broadcast of two elements followed by a blend,
10120 // prefer that lowering. This is especially important because broadcasts can
10121 // often fold with memory operands.
10122 auto DoBothBroadcast = [&] {
10123 int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
10126 if (V2BroadcastIdx == -1)
10127 V2BroadcastIdx = M - Size;
10128 else if (M - Size != V2BroadcastIdx)
10130 } else if (M >= 0) {
10131 if (V1BroadcastIdx == -1)
10132 V1BroadcastIdx = M;
10133 else if (M != V1BroadcastIdx)
10138 if (DoBothBroadcast())
10139 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
10142 // If the inputs all stem from a single 128-bit lane of each input, then we
10143 // split them rather than blending because the split will decompose to
10144 // unusually few instructions.
10145 int LaneCount = VT.getSizeInBits() / 128;
10146 int LaneSize = Size / LaneCount;
10147 SmallBitVector LaneInputs[2];
10148 LaneInputs[0].resize(LaneCount, false);
10149 LaneInputs[1].resize(LaneCount, false);
10150 for (int i = 0; i < Size; ++i)
10152 LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
10153 if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
10154 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10156 // Otherwise, just fall back to decomposed shuffles and a blend. This requires
10157 // that the decomposed single-input shuffles don't end up here.
10158 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
10161 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
10162 /// a permutation and blend of those lanes.
10164 /// This essentially blends the out-of-lane inputs to each lane into the lane
10165 /// from a permuted copy of the vector. This lowering strategy results in four
10166 /// instructions in the worst case for a single-input cross lane shuffle which
10167 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
10168 /// of. Special cases for each particular shuffle pattern should be handled
10169 /// prior to trying this lowering.
10170 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
10171 SDValue V1, SDValue V2,
10172 ArrayRef<int> Mask,
10173 SelectionDAG &DAG) {
10174 // FIXME: This should probably be generalized for 512-bit vectors as well.
10175 assert(VT.is256BitVector() && "Only for 256-bit vector shuffles!");
10176 int LaneSize = Mask.size() / 2;
10178 // If there are only inputs from one 128-bit lane, splitting will in fact be
10179 // less expensive. The flags track whether the given lane contains an element
10180 // that crosses to another lane.
10181 bool LaneCrossing[2] = {false, false};
10182 for (int i = 0, Size = Mask.size(); i < Size; ++i)
10183 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
10184 LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
10185 if (!LaneCrossing[0] || !LaneCrossing[1])
10186 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10188 if (isSingleInputShuffleMask(Mask)) {
10189 SmallVector<int, 32> FlippedBlendMask;
10190 for (int i = 0, Size = Mask.size(); i < Size; ++i)
10191 FlippedBlendMask.push_back(
10192 Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
10194 : Mask[i] % LaneSize +
10195 (i / LaneSize) * LaneSize + Size));
10197 // Flip the vector, and blend the results which should now be in-lane. The
10198 // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
10199 // 5 for the high source. The value 3 selects the high half of source 2 and
10200 // the value 2 selects the low half of source 2. We only use source 2 to
10201 // allow folding it into a memory operand.
10202 unsigned PERMMask = 3 | 2 << 4;
10203 SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
10204 V1, DAG.getConstant(PERMMask, DL, MVT::i8));
10205 return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
10208 // This now reduces to two single-input shuffles of V1 and V2 which at worst
10209 // will be handled by the above logic and a blend of the results, much like
10210 // other patterns in AVX.
10211 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
10214 /// \brief Handle lowering 2-lane 128-bit shuffles.
10215 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
10216 SDValue V2, ArrayRef<int> Mask,
10217 const X86Subtarget *Subtarget,
10218 SelectionDAG &DAG) {
10219 // TODO: If minimizing size and one of the inputs is a zero vector and the
10220 // the zero vector has only one use, we could use a VPERM2X128 to save the
10221 // instruction bytes needed to explicitly generate the zero vector.
10223 // Blends are faster and handle all the non-lane-crossing cases.
10224 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
10228 bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
10229 bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
10231 // If either input operand is a zero vector, use VPERM2X128 because its mask
10232 // allows us to replace the zero input with an implicit zero.
10233 if (!IsV1Zero && !IsV2Zero) {
10234 // Check for patterns which can be matched with a single insert of a 128-bit
10236 bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
10237 if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
10238 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
10239 VT.getVectorNumElements() / 2);
10240 SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
10241 DAG.getIntPtrConstant(0, DL));
10242 SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
10243 OnlyUsesV1 ? V1 : V2,
10244 DAG.getIntPtrConstant(0, DL));
10245 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
10249 // Otherwise form a 128-bit permutation. After accounting for undefs,
10250 // convert the 64-bit shuffle mask selection values into 128-bit
10251 // selection bits by dividing the indexes by 2 and shifting into positions
10252 // defined by a vperm2*128 instruction's immediate control byte.
10254 // The immediate permute control byte looks like this:
10255 // [1:0] - select 128 bits from sources for low half of destination
10257 // [3] - zero low half of destination
10258 // [5:4] - select 128 bits from sources for high half of destination
10260 // [7] - zero high half of destination
10262 int MaskLO = Mask[0];
10263 if (MaskLO == SM_SentinelUndef)
10264 MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
10266 int MaskHI = Mask[2];
10267 if (MaskHI == SM_SentinelUndef)
10268 MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
10270 unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
10272 // If either input is a zero vector, replace it with an undef input.
10273 // Shuffle mask values < 4 are selecting elements of V1.
10274 // Shuffle mask values >= 4 are selecting elements of V2.
10275 // Adjust each half of the permute mask by clearing the half that was
10276 // selecting the zero vector and setting the zero mask bit.
10278 V1 = DAG.getUNDEF(VT);
10280 PermMask = (PermMask & 0xf0) | 0x08;
10282 PermMask = (PermMask & 0x0f) | 0x80;
10285 V2 = DAG.getUNDEF(VT);
10287 PermMask = (PermMask & 0xf0) | 0x08;
10289 PermMask = (PermMask & 0x0f) | 0x80;
10292 return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
10293 DAG.getConstant(PermMask, DL, MVT::i8));
10296 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
10297 /// shuffling each lane.
10299 /// This will only succeed when the result of fixing the 128-bit lanes results
10300 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
10301 /// each 128-bit lanes. This handles many cases where we can quickly blend away
10302 /// the lane crosses early and then use simpler shuffles within each lane.
10304 /// FIXME: It might be worthwhile at some point to support this without
10305 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
10306 /// in x86 only floating point has interesting non-repeating shuffles, and even
10307 /// those are still *marginally* more expensive.
10308 static SDValue lowerVectorShuffleByMerging128BitLanes(
10309 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
10310 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
10311 assert(!isSingleInputShuffleMask(Mask) &&
10312 "This is only useful with multiple inputs.");
10314 int Size = Mask.size();
10315 int LaneSize = 128 / VT.getScalarSizeInBits();
10316 int NumLanes = Size / LaneSize;
10317 assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
10319 // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
10320 // check whether the in-128-bit lane shuffles share a repeating pattern.
10321 SmallVector<int, 4> Lanes;
10322 Lanes.resize(NumLanes, -1);
10323 SmallVector<int, 4> InLaneMask;
10324 InLaneMask.resize(LaneSize, -1);
10325 for (int i = 0; i < Size; ++i) {
10329 int j = i / LaneSize;
10331 if (Lanes[j] < 0) {
10332 // First entry we've seen for this lane.
10333 Lanes[j] = Mask[i] / LaneSize;
10334 } else if (Lanes[j] != Mask[i] / LaneSize) {
10335 // This doesn't match the lane selected previously!
10339 // Check that within each lane we have a consistent shuffle mask.
10340 int k = i % LaneSize;
10341 if (InLaneMask[k] < 0) {
10342 InLaneMask[k] = Mask[i] % LaneSize;
10343 } else if (InLaneMask[k] != Mask[i] % LaneSize) {
10344 // This doesn't fit a repeating in-lane mask.
10349 // First shuffle the lanes into place.
10350 MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
10351 VT.getSizeInBits() / 64);
10352 SmallVector<int, 8> LaneMask;
10353 LaneMask.resize(NumLanes * 2, -1);
10354 for (int i = 0; i < NumLanes; ++i)
10355 if (Lanes[i] >= 0) {
10356 LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
10357 LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
10360 V1 = DAG.getBitcast(LaneVT, V1);
10361 V2 = DAG.getBitcast(LaneVT, V2);
10362 SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
10364 // Cast it back to the type we actually want.
10365 LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
10367 // Now do a simple shuffle that isn't lane crossing.
10368 SmallVector<int, 8> NewMask;
10369 NewMask.resize(Size, -1);
10370 for (int i = 0; i < Size; ++i)
10372 NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
10373 assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
10374 "Must not introduce lane crosses at this point!");
10376 return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
10379 /// Lower shuffles where an entire half of a 256-bit vector is UNDEF.
10380 /// This allows for fast cases such as subvector extraction/insertion
10381 /// or shuffling smaller vector types which can lower more efficiently.
10382 static SDValue lowerVectorShuffleWithUndefHalf(SDLoc DL, MVT VT, SDValue V1,
10383 SDValue V2, ArrayRef<int> Mask,
10384 const X86Subtarget *Subtarget,
10385 SelectionDAG &DAG) {
10386 assert(VT.getSizeInBits() == 256 && "Expected 256-bit vector");
10388 unsigned NumElts = VT.getVectorNumElements();
10389 unsigned HalfNumElts = NumElts / 2;
10390 MVT HalfVT = MVT::getVectorVT(VT.getVectorElementType(), HalfNumElts);
10392 bool UndefLower = isUndefInRange(Mask, 0, HalfNumElts);
10393 bool UndefUpper = isUndefInRange(Mask, HalfNumElts, HalfNumElts);
10394 if (!UndefLower && !UndefUpper)
10397 // Upper half is undef and lower half is whole upper subvector.
10398 // e.g. vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
10400 isSequentialOrUndefInRange(Mask, 0, HalfNumElts, HalfNumElts)) {
10401 SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
10402 DAG.getIntPtrConstant(HalfNumElts, DL));
10403 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), Hi,
10404 DAG.getIntPtrConstant(0, DL));
10407 // Lower half is undef and upper half is whole lower subvector.
10408 // e.g. vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
10410 isSequentialOrUndefInRange(Mask, HalfNumElts, HalfNumElts, 0)) {
10411 SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
10412 DAG.getIntPtrConstant(0, DL));
10413 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), Hi,
10414 DAG.getIntPtrConstant(HalfNumElts, DL));
10417 // AVX2 supports efficient immediate 64-bit element cross-lane shuffles.
10418 if (UndefLower && Subtarget->hasAVX2() &&
10419 (VT == MVT::v4f64 || VT == MVT::v4i64))
10422 // If the shuffle only uses the lower halves of the input operands,
10423 // then extract them and perform the 'half' shuffle at half width.
10424 // e.g. vector_shuffle <X, X, X, X, u, u, u, u> or <X, X, u, u>
10425 int HalfIdx1 = -1, HalfIdx2 = -1;
10426 SmallVector<int, 8> HalfMask;
10427 unsigned Offset = UndefLower ? HalfNumElts : 0;
10428 for (unsigned i = 0; i != HalfNumElts; ++i) {
10429 int M = Mask[i + Offset];
10431 HalfMask.push_back(M);
10435 // Determine which of the 4 half vectors this element is from.
10436 // i.e. 0 = Lower V1, 1 = Upper V1, 2 = Lower V2, 3 = Upper V2.
10437 int HalfIdx = M / HalfNumElts;
10439 // Only shuffle using the lower halves of the inputs.
10440 // TODO: Investigate usefulness of shuffling with upper halves.
10441 if (HalfIdx != 0 && HalfIdx != 2)
10444 // Determine the element index into its half vector source.
10445 int HalfElt = M % HalfNumElts;
10447 // We can shuffle with up to 2 half vectors, set the new 'half'
10448 // shuffle mask accordingly.
10449 if (-1 == HalfIdx1 || HalfIdx1 == HalfIdx) {
10450 HalfMask.push_back(HalfElt);
10451 HalfIdx1 = HalfIdx;
10454 if (-1 == HalfIdx2 || HalfIdx2 == HalfIdx) {
10455 HalfMask.push_back(HalfElt + HalfNumElts);
10456 HalfIdx2 = HalfIdx;
10460 // Too many half vectors referenced.
10463 assert(HalfMask.size() == HalfNumElts && "Unexpected shuffle mask length");
10465 auto GetHalfVector = [&](int HalfIdx) {
10467 return DAG.getUNDEF(HalfVT);
10468 SDValue V = (HalfIdx < 2 ? V1 : V2);
10469 HalfIdx = (HalfIdx % 2) * HalfNumElts;
10470 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V,
10471 DAG.getIntPtrConstant(HalfIdx, DL));
10474 SDValue Half1 = GetHalfVector(HalfIdx1);
10475 SDValue Half2 = GetHalfVector(HalfIdx2);
10476 SDValue V = DAG.getVectorShuffle(HalfVT, DL, Half1, Half2, HalfMask);
10477 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V,
10478 DAG.getIntPtrConstant(Offset, DL));
10481 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
10484 /// This returns true if the elements from a particular input are already in the
10485 /// slot required by the given mask and require no permutation.
10486 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
10487 assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
10488 int Size = Mask.size();
10489 for (int i = 0; i < Size; ++i)
10490 if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
10496 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
10497 ArrayRef<int> Mask, SDValue V1,
10498 SDValue V2, SelectionDAG &DAG) {
10500 // Mask for V8F64: 0/1, 8/9, 2/3, 10/11, 4/5, ..
10501 // Mask for V4F64; 0/1, 4/5, 2/3, 6/7..
10502 assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
10503 int NumElts = VT.getVectorNumElements();
10504 bool ShufpdMask = true;
10505 bool CommutableMask = true;
10506 unsigned Immediate = 0;
10507 for (int i = 0; i < NumElts; ++i) {
10510 int Val = (i & 6) + NumElts * (i & 1);
10511 int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
10512 if (Mask[i] < Val || Mask[i] > Val + 1)
10513 ShufpdMask = false;
10514 if (Mask[i] < CommutVal || Mask[i] > CommutVal + 1)
10515 CommutableMask = false;
10516 Immediate |= (Mask[i] % 2) << i;
10519 return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
10520 DAG.getConstant(Immediate, DL, MVT::i8));
10521 if (CommutableMask)
10522 return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
10523 DAG.getConstant(Immediate, DL, MVT::i8));
10527 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
10529 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
10530 /// isn't available.
10531 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10532 const X86Subtarget *Subtarget,
10533 SelectionDAG &DAG) {
10535 assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10536 assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10537 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10538 ArrayRef<int> Mask = SVOp->getMask();
10539 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10541 SmallVector<int, 4> WidenedMask;
10542 if (canWidenShuffleElements(Mask, WidenedMask))
10543 return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
10546 if (isSingleInputShuffleMask(Mask)) {
10547 // Check for being able to broadcast a single element.
10548 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
10549 Mask, Subtarget, DAG))
10552 // Use low duplicate instructions for masks that match their pattern.
10553 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
10554 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
10556 if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
10557 // Non-half-crossing single input shuffles can be lowerid with an
10558 // interleaved permutation.
10559 unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
10560 ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
10561 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
10562 DAG.getConstant(VPERMILPMask, DL, MVT::i8));
10565 // With AVX2 we have direct support for this permutation.
10566 if (Subtarget->hasAVX2())
10567 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
10568 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10570 // Otherwise, fall back.
10571 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
10575 // Use dedicated unpack instructions for masks that match their pattern.
10577 lowerVectorShuffleWithUNPCK(DL, MVT::v4f64, Mask, V1, V2, DAG))
10580 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
10584 // Check if the blend happens to exactly fit that of SHUFPD.
10586 lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
10589 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10590 // shuffle. However, if we have AVX2 and either inputs are already in place,
10591 // we will be able to shuffle even across lanes the other input in a single
10592 // instruction so skip this pattern.
10593 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10594 isShuffleMaskInputInPlace(1, Mask))))
10595 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10596 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
10599 // If we have AVX2 then we always want to lower with a blend because an v4 we
10600 // can fully permute the elements.
10601 if (Subtarget->hasAVX2())
10602 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
10605 // Otherwise fall back on generic lowering.
10606 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
10609 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
10611 /// This routine is only called when we have AVX2 and thus a reasonable
10612 /// instruction set for v4i64 shuffling..
10613 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10614 const X86Subtarget *Subtarget,
10615 SelectionDAG &DAG) {
10617 assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10618 assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10619 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10620 ArrayRef<int> Mask = SVOp->getMask();
10621 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10622 assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
10624 SmallVector<int, 4> WidenedMask;
10625 if (canWidenShuffleElements(Mask, WidenedMask))
10626 return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
10629 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
10633 // Check for being able to broadcast a single element.
10634 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
10635 Mask, Subtarget, DAG))
10638 // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
10639 // use lower latency instructions that will operate on both 128-bit lanes.
10640 SmallVector<int, 2> RepeatedMask;
10641 if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
10642 if (isSingleInputShuffleMask(Mask)) {
10643 int PSHUFDMask[] = {-1, -1, -1, -1};
10644 for (int i = 0; i < 2; ++i)
10645 if (RepeatedMask[i] >= 0) {
10646 PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
10647 PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
10649 return DAG.getBitcast(
10651 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
10652 DAG.getBitcast(MVT::v8i32, V1),
10653 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
10657 // AVX2 provides a direct instruction for permuting a single input across
10659 if (isSingleInputShuffleMask(Mask))
10660 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
10661 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10663 // Try to use shift instructions.
10664 if (SDValue Shift =
10665 lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
10668 // Use dedicated unpack instructions for masks that match their pattern.
10670 lowerVectorShuffleWithUNPCK(DL, MVT::v4i64, Mask, V1, V2, DAG))
10673 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10674 // shuffle. However, if we have AVX2 and either inputs are already in place,
10675 // we will be able to shuffle even across lanes the other input in a single
10676 // instruction so skip this pattern.
10677 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10678 isShuffleMaskInputInPlace(1, Mask))))
10679 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10680 DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
10683 // Otherwise fall back on generic blend lowering.
10684 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
10688 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
10690 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
10691 /// isn't available.
10692 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10693 const X86Subtarget *Subtarget,
10694 SelectionDAG &DAG) {
10696 assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10697 assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10698 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10699 ArrayRef<int> Mask = SVOp->getMask();
10700 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10702 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
10706 // Check for being able to broadcast a single element.
10707 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
10708 Mask, Subtarget, DAG))
10711 // If the shuffle mask is repeated in each 128-bit lane, we have many more
10712 // options to efficiently lower the shuffle.
10713 SmallVector<int, 4> RepeatedMask;
10714 if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
10715 assert(RepeatedMask.size() == 4 &&
10716 "Repeated masks must be half the mask width!");
10718 // Use even/odd duplicate instructions for masks that match their pattern.
10719 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
10720 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
10721 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
10722 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
10724 if (isSingleInputShuffleMask(Mask))
10725 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
10726 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10728 // Use dedicated unpack instructions for masks that match their pattern.
10730 lowerVectorShuffleWithUNPCK(DL, MVT::v8f32, Mask, V1, V2, DAG))
10733 // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10734 // have already handled any direct blends. We also need to squash the
10735 // repeated mask into a simulated v4f32 mask.
10736 for (int i = 0; i < 4; ++i)
10737 if (RepeatedMask[i] >= 8)
10738 RepeatedMask[i] -= 4;
10739 return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10742 // If we have a single input shuffle with different shuffle patterns in the
10743 // two 128-bit lanes use the variable mask to VPERMILPS.
10744 if (isSingleInputShuffleMask(Mask)) {
10745 SDValue VPermMask[8];
10746 for (int i = 0; i < 8; ++i)
10747 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10748 : DAG.getConstant(Mask[i], DL, MVT::i32);
10749 if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10750 return DAG.getNode(
10751 X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10752 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10754 if (Subtarget->hasAVX2())
10755 return DAG.getNode(
10756 X86ISD::VPERMV, DL, MVT::v8f32,
10757 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10759 // Otherwise, fall back.
10760 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10764 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10766 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10767 DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10770 // If we have AVX2 then we always want to lower with a blend because at v8 we
10771 // can fully permute the elements.
10772 if (Subtarget->hasAVX2())
10773 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10776 // Otherwise fall back on generic lowering.
10777 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10780 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10782 /// This routine is only called when we have AVX2 and thus a reasonable
10783 /// instruction set for v8i32 shuffling..
10784 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10785 const X86Subtarget *Subtarget,
10786 SelectionDAG &DAG) {
10788 assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10789 assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10790 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10791 ArrayRef<int> Mask = SVOp->getMask();
10792 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10793 assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10795 // Whenever we can lower this as a zext, that instruction is strictly faster
10796 // than any alternative. It also allows us to fold memory operands into the
10797 // shuffle in many cases.
10798 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10799 Mask, Subtarget, DAG))
10802 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10806 // Check for being able to broadcast a single element.
10807 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10808 Mask, Subtarget, DAG))
10811 // If the shuffle mask is repeated in each 128-bit lane we can use more
10812 // efficient instructions that mirror the shuffles across the two 128-bit
10814 SmallVector<int, 4> RepeatedMask;
10815 if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10816 assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10817 if (isSingleInputShuffleMask(Mask))
10818 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10819 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10821 // Use dedicated unpack instructions for masks that match their pattern.
10823 lowerVectorShuffleWithUNPCK(DL, MVT::v8i32, Mask, V1, V2, DAG))
10827 // Try to use shift instructions.
10828 if (SDValue Shift =
10829 lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10832 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10833 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10836 // If the shuffle patterns aren't repeated but it is a single input, directly
10837 // generate a cross-lane VPERMD instruction.
10838 if (isSingleInputShuffleMask(Mask)) {
10839 SDValue VPermMask[8];
10840 for (int i = 0; i < 8; ++i)
10841 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10842 : DAG.getConstant(Mask[i], DL, MVT::i32);
10843 return DAG.getNode(
10844 X86ISD::VPERMV, DL, MVT::v8i32,
10845 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10848 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10850 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10851 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10854 // Otherwise fall back on generic blend lowering.
10855 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10859 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10861 /// This routine is only called when we have AVX2 and thus a reasonable
10862 /// instruction set for v16i16 shuffling..
10863 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10864 const X86Subtarget *Subtarget,
10865 SelectionDAG &DAG) {
10867 assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10868 assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10869 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10870 ArrayRef<int> Mask = SVOp->getMask();
10871 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10872 assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10874 // Whenever we can lower this as a zext, that instruction is strictly faster
10875 // than any alternative. It also allows us to fold memory operands into the
10876 // shuffle in many cases.
10877 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10878 Mask, Subtarget, DAG))
10881 // Check for being able to broadcast a single element.
10882 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10883 Mask, Subtarget, DAG))
10886 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10890 // Use dedicated unpack instructions for masks that match their pattern.
10892 lowerVectorShuffleWithUNPCK(DL, MVT::v16i16, Mask, V1, V2, DAG))
10895 // Try to use shift instructions.
10896 if (SDValue Shift =
10897 lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10900 // Try to use byte rotation instructions.
10901 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10902 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10905 if (isSingleInputShuffleMask(Mask)) {
10906 // There are no generalized cross-lane shuffle operations available on i16
10908 if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10909 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10912 SmallVector<int, 8> RepeatedMask;
10913 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10914 // As this is a single-input shuffle, the repeated mask should be
10915 // a strictly valid v8i16 mask that we can pass through to the v8i16
10916 // lowering to handle even the v16 case.
10917 return lowerV8I16GeneralSingleInputVectorShuffle(
10918 DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10921 SDValue PSHUFBMask[32];
10922 for (int i = 0; i < 16; ++i) {
10923 if (Mask[i] == -1) {
10924 PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10928 int M = i < 8 ? Mask[i] : Mask[i] - 8;
10929 assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10930 PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10931 PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10933 return DAG.getBitcast(MVT::v16i16,
10934 DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10935 DAG.getBitcast(MVT::v32i8, V1),
10936 DAG.getNode(ISD::BUILD_VECTOR, DL,
10937 MVT::v32i8, PSHUFBMask)));
10940 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10942 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10943 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10946 // Otherwise fall back on generic lowering.
10947 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10950 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10952 /// This routine is only called when we have AVX2 and thus a reasonable
10953 /// instruction set for v32i8 shuffling..
10954 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10955 const X86Subtarget *Subtarget,
10956 SelectionDAG &DAG) {
10958 assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10959 assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10960 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10961 ArrayRef<int> Mask = SVOp->getMask();
10962 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10963 assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10965 // Whenever we can lower this as a zext, that instruction is strictly faster
10966 // than any alternative. It also allows us to fold memory operands into the
10967 // shuffle in many cases.
10968 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10969 Mask, Subtarget, DAG))
10972 // Check for being able to broadcast a single element.
10973 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10974 Mask, Subtarget, DAG))
10977 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10981 // Use dedicated unpack instructions for masks that match their pattern.
10983 lowerVectorShuffleWithUNPCK(DL, MVT::v32i8, Mask, V1, V2, DAG))
10986 // Try to use shift instructions.
10987 if (SDValue Shift =
10988 lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10991 // Try to use byte rotation instructions.
10992 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10993 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10996 if (isSingleInputShuffleMask(Mask)) {
10997 // There are no generalized cross-lane shuffle operations available on i8
10999 if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
11000 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
11003 SDValue PSHUFBMask[32];
11004 for (int i = 0; i < 32; ++i)
11007 ? DAG.getUNDEF(MVT::i8)
11008 : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
11011 return DAG.getNode(
11012 X86ISD::PSHUFB, DL, MVT::v32i8, V1,
11013 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
11016 // Try to simplify this by merging 128-bit lanes to enable a lane-based
11018 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
11019 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
11022 // Otherwise fall back on generic lowering.
11023 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
11026 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
11028 /// This routine either breaks down the specific type of a 256-bit x86 vector
11029 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
11030 /// together based on the available instructions.
11031 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11032 MVT VT, const X86Subtarget *Subtarget,
11033 SelectionDAG &DAG) {
11035 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11036 ArrayRef<int> Mask = SVOp->getMask();
11038 // If we have a single input to the zero element, insert that into V1 if we
11039 // can do so cheaply.
11040 int NumElts = VT.getVectorNumElements();
11041 int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
11042 return M >= NumElts;
11045 if (NumV2Elements == 1 && Mask[0] >= NumElts)
11046 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
11047 DL, VT, V1, V2, Mask, Subtarget, DAG))
11050 // Handle special cases where the lower or upper half is UNDEF.
11052 lowerVectorShuffleWithUndefHalf(DL, VT, V1, V2, Mask, Subtarget, DAG))
11055 // There is a really nice hard cut-over between AVX1 and AVX2 that means we
11056 // can check for those subtargets here and avoid much of the subtarget
11057 // querying in the per-vector-type lowering routines. With AVX1 we have
11058 // essentially *zero* ability to manipulate a 256-bit vector with integer
11059 // types. Since we'll use floating point types there eventually, just
11060 // immediately cast everything to a float and operate entirely in that domain.
11061 if (VT.isInteger() && !Subtarget->hasAVX2()) {
11062 int ElementBits = VT.getScalarSizeInBits();
11063 if (ElementBits < 32)
11064 // No floating point type available, decompose into 128-bit vectors.
11065 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
11067 MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
11068 VT.getVectorNumElements());
11069 V1 = DAG.getBitcast(FpVT, V1);
11070 V2 = DAG.getBitcast(FpVT, V2);
11071 return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
11074 switch (VT.SimpleTy) {
11076 return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11078 return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11080 return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11082 return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11084 return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
11086 return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
11089 llvm_unreachable("Not a valid 256-bit x86 vector type!");
11093 /// \brief Try to lower a vector shuffle as a 128-bit shuffles.
11094 static SDValue lowerV4X128VectorShuffle(SDLoc DL, MVT VT,
11095 ArrayRef<int> Mask,
11096 SDValue V1, SDValue V2,
11097 SelectionDAG &DAG) {
11098 assert(VT.getScalarSizeInBits() == 64 &&
11099 "Unexpected element type size for 128bit shuffle.");
11101 // To handle 256 bit vector requires VLX and most probably
11102 // function lowerV2X128VectorShuffle() is better solution.
11103 assert(VT.is512BitVector() && "Unexpected vector size for 128bit shuffle.");
11105 SmallVector<int, 4> WidenedMask;
11106 if (!canWidenShuffleElements(Mask, WidenedMask))
11109 // Form a 128-bit permutation.
11110 // Convert the 64-bit shuffle mask selection values into 128-bit selection
11111 // bits defined by a vshuf64x2 instruction's immediate control byte.
11112 unsigned PermMask = 0, Imm = 0;
11113 unsigned ControlBitsNum = WidenedMask.size() / 2;
11115 for (int i = 0, Size = WidenedMask.size(); i < Size; ++i) {
11116 if (WidenedMask[i] == SM_SentinelZero)
11119 // Use first element in place of undef mask.
11120 Imm = (WidenedMask[i] == SM_SentinelUndef) ? 0 : WidenedMask[i];
11121 PermMask |= (Imm % WidenedMask.size()) << (i * ControlBitsNum);
11124 return DAG.getNode(X86ISD::SHUF128, DL, VT, V1, V2,
11125 DAG.getConstant(PermMask, DL, MVT::i8));
11128 static SDValue lowerVectorShuffleWithPERMV(SDLoc DL, MVT VT,
11129 ArrayRef<int> Mask, SDValue V1,
11130 SDValue V2, SelectionDAG &DAG) {
11132 assert(VT.getScalarSizeInBits() >= 16 && "Unexpected data type for PERMV");
11134 MVT MaskEltVT = MVT::getIntegerVT(VT.getScalarSizeInBits());
11135 MVT MaskVecVT = MVT::getVectorVT(MaskEltVT, VT.getVectorNumElements());
11137 SDValue MaskNode = getConstVector(Mask, MaskVecVT, DAG, DL, true);
11138 if (isSingleInputShuffleMask(Mask))
11139 return DAG.getNode(X86ISD::VPERMV, DL, VT, MaskNode, V1);
11141 return DAG.getNode(X86ISD::VPERMV3, DL, VT, V1, MaskNode, V2);
11144 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
11145 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11146 const X86Subtarget *Subtarget,
11147 SelectionDAG &DAG) {
11149 assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
11150 assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
11151 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11152 ArrayRef<int> Mask = SVOp->getMask();
11153 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
11155 if (SDValue Shuf128 =
11156 lowerV4X128VectorShuffle(DL, MVT::v8f64, Mask, V1, V2, DAG))
11159 if (SDValue Unpck =
11160 lowerVectorShuffleWithUNPCK(DL, MVT::v8f64, Mask, V1, V2, DAG))
11163 return lowerVectorShuffleWithPERMV(DL, MVT::v8f64, Mask, V1, V2, DAG);
11166 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
11167 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11168 const X86Subtarget *Subtarget,
11169 SelectionDAG &DAG) {
11171 assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
11172 assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
11173 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11174 ArrayRef<int> Mask = SVOp->getMask();
11175 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
11177 if (SDValue Unpck =
11178 lowerVectorShuffleWithUNPCK(DL, MVT::v16f32, Mask, V1, V2, DAG))
11181 return lowerVectorShuffleWithPERMV(DL, MVT::v16f32, Mask, V1, V2, DAG);
11184 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
11185 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11186 const X86Subtarget *Subtarget,
11187 SelectionDAG &DAG) {
11189 assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
11190 assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
11191 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11192 ArrayRef<int> Mask = SVOp->getMask();
11193 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
11195 if (SDValue Shuf128 =
11196 lowerV4X128VectorShuffle(DL, MVT::v8i64, Mask, V1, V2, DAG))
11199 if (SDValue Unpck =
11200 lowerVectorShuffleWithUNPCK(DL, MVT::v8i64, Mask, V1, V2, DAG))
11203 return lowerVectorShuffleWithPERMV(DL, MVT::v8i64, Mask, V1, V2, DAG);
11206 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
11207 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11208 const X86Subtarget *Subtarget,
11209 SelectionDAG &DAG) {
11211 assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
11212 assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
11213 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11214 ArrayRef<int> Mask = SVOp->getMask();
11215 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
11217 if (SDValue Unpck =
11218 lowerVectorShuffleWithUNPCK(DL, MVT::v16i32, Mask, V1, V2, DAG))
11221 return lowerVectorShuffleWithPERMV(DL, MVT::v16i32, Mask, V1, V2, DAG);
11224 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
11225 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11226 const X86Subtarget *Subtarget,
11227 SelectionDAG &DAG) {
11229 assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
11230 assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
11231 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11232 ArrayRef<int> Mask = SVOp->getMask();
11233 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
11234 assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
11236 return lowerVectorShuffleWithPERMV(DL, MVT::v32i16, Mask, V1, V2, DAG);
11239 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
11240 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11241 const X86Subtarget *Subtarget,
11242 SelectionDAG &DAG) {
11244 assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
11245 assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
11246 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11247 ArrayRef<int> Mask = SVOp->getMask();
11248 assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
11249 assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
11251 // FIXME: Implement direct support for this type!
11252 return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
11255 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
11257 /// This routine either breaks down the specific type of a 512-bit x86 vector
11258 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
11259 /// together based on the available instructions.
11260 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11261 MVT VT, const X86Subtarget *Subtarget,
11262 SelectionDAG &DAG) {
11264 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11265 ArrayRef<int> Mask = SVOp->getMask();
11266 assert(Subtarget->hasAVX512() &&
11267 "Cannot lower 512-bit vectors w/ basic ISA!");
11269 // Check for being able to broadcast a single element.
11270 if (SDValue Broadcast =
11271 lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
11274 // Dispatch to each element type for lowering. If we don't have supprot for
11275 // specific element type shuffles at 512 bits, immediately split them and
11276 // lower them. Each lowering routine of a given type is allowed to assume that
11277 // the requisite ISA extensions for that element type are available.
11278 switch (VT.SimpleTy) {
11280 return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11282 return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11284 return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11286 return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11288 if (Subtarget->hasBWI())
11289 return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
11292 if (Subtarget->hasBWI())
11293 return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
11297 llvm_unreachable("Not a valid 512-bit x86 vector type!");
11300 // Otherwise fall back on splitting.
11301 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
11304 // Lower vXi1 vector shuffles.
11305 // There is no a dedicated instruction on AVX-512 that shuffles the masks.
11306 // The only way to shuffle bits is to sign-extend the mask vector to SIMD
11307 // vector, shuffle and then truncate it back.
11308 static SDValue lower1BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11309 MVT VT, const X86Subtarget *Subtarget,
11310 SelectionDAG &DAG) {
11312 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11313 ArrayRef<int> Mask = SVOp->getMask();
11314 assert(Subtarget->hasAVX512() &&
11315 "Cannot lower 512-bit vectors w/o basic ISA!");
11317 switch (VT.SimpleTy) {
11319 llvm_unreachable("Expected a vector of i1 elements");
11321 ExtVT = MVT::v2i64;
11324 ExtVT = MVT::v4i32;
11327 ExtVT = MVT::v8i64; // Take 512-bit type, more shuffles on KNL
11330 ExtVT = MVT::v16i32;
11333 ExtVT = MVT::v32i16;
11336 ExtVT = MVT::v64i8;
11340 if (ISD::isBuildVectorAllZeros(V1.getNode()))
11341 V1 = getZeroVector(ExtVT, Subtarget, DAG, DL);
11342 else if (ISD::isBuildVectorAllOnes(V1.getNode()))
11343 V1 = getOnesVector(ExtVT, Subtarget, DAG, DL);
11345 V1 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V1);
11348 V2 = DAG.getUNDEF(ExtVT);
11349 else if (ISD::isBuildVectorAllZeros(V2.getNode()))
11350 V2 = getZeroVector(ExtVT, Subtarget, DAG, DL);
11351 else if (ISD::isBuildVectorAllOnes(V2.getNode()))
11352 V2 = getOnesVector(ExtVT, Subtarget, DAG, DL);
11354 V2 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V2);
11355 return DAG.getNode(ISD::TRUNCATE, DL, VT,
11356 DAG.getVectorShuffle(ExtVT, DL, V1, V2, Mask));
11358 /// \brief Top-level lowering for x86 vector shuffles.
11360 /// This handles decomposition, canonicalization, and lowering of all x86
11361 /// vector shuffles. Most of the specific lowering strategies are encapsulated
11362 /// above in helper routines. The canonicalization attempts to widen shuffles
11363 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
11364 /// s.t. only one of the two inputs needs to be tested, etc.
11365 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
11366 SelectionDAG &DAG) {
11367 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11368 ArrayRef<int> Mask = SVOp->getMask();
11369 SDValue V1 = Op.getOperand(0);
11370 SDValue V2 = Op.getOperand(1);
11371 MVT VT = Op.getSimpleValueType();
11372 int NumElements = VT.getVectorNumElements();
11374 bool Is1BitVector = (VT.getVectorElementType() == MVT::i1);
11376 assert((VT.getSizeInBits() != 64 || Is1BitVector) &&
11377 "Can't lower MMX shuffles");
11379 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
11380 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
11381 if (V1IsUndef && V2IsUndef)
11382 return DAG.getUNDEF(VT);
11384 // When we create a shuffle node we put the UNDEF node to second operand,
11385 // but in some cases the first operand may be transformed to UNDEF.
11386 // In this case we should just commute the node.
11388 return DAG.getCommutedVectorShuffle(*SVOp);
11390 // Check for non-undef masks pointing at an undef vector and make the masks
11391 // undef as well. This makes it easier to match the shuffle based solely on
11395 if (M >= NumElements) {
11396 SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
11397 for (int &M : NewMask)
11398 if (M >= NumElements)
11400 return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
11403 // We actually see shuffles that are entirely re-arrangements of a set of
11404 // zero inputs. This mostly happens while decomposing complex shuffles into
11405 // simple ones. Directly lower these as a buildvector of zeros.
11406 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
11407 if (Zeroable.all())
11408 return getZeroVector(VT, Subtarget, DAG, dl);
11410 // Try to collapse shuffles into using a vector type with fewer elements but
11411 // wider element types. We cap this to not form integers or floating point
11412 // elements wider than 64 bits, but it might be interesting to form i128
11413 // integers to handle flipping the low and high halves of AVX 256-bit vectors.
11414 SmallVector<int, 16> WidenedMask;
11415 if (VT.getScalarSizeInBits() < 64 && !Is1BitVector &&
11416 canWidenShuffleElements(Mask, WidenedMask)) {
11417 MVT NewEltVT = VT.isFloatingPoint()
11418 ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
11419 : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
11420 MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
11421 // Make sure that the new vector type is legal. For example, v2f64 isn't
11423 if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
11424 V1 = DAG.getBitcast(NewVT, V1);
11425 V2 = DAG.getBitcast(NewVT, V2);
11426 return DAG.getBitcast(
11427 VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
11431 int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
11432 for (int M : SVOp->getMask())
11434 ++NumUndefElements;
11435 else if (M < NumElements)
11440 // Commute the shuffle as needed such that more elements come from V1 than
11441 // V2. This allows us to match the shuffle pattern strictly on how many
11442 // elements come from V1 without handling the symmetric cases.
11443 if (NumV2Elements > NumV1Elements)
11444 return DAG.getCommutedVectorShuffle(*SVOp);
11446 // When the number of V1 and V2 elements are the same, try to minimize the
11447 // number of uses of V2 in the low half of the vector. When that is tied,
11448 // ensure that the sum of indices for V1 is equal to or lower than the sum
11449 // indices for V2. When those are equal, try to ensure that the number of odd
11450 // indices for V1 is lower than the number of odd indices for V2.
11451 if (NumV1Elements == NumV2Elements) {
11452 int LowV1Elements = 0, LowV2Elements = 0;
11453 for (int M : SVOp->getMask().slice(0, NumElements / 2))
11454 if (M >= NumElements)
11458 if (LowV2Elements > LowV1Elements) {
11459 return DAG.getCommutedVectorShuffle(*SVOp);
11460 } else if (LowV2Elements == LowV1Elements) {
11461 int SumV1Indices = 0, SumV2Indices = 0;
11462 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11463 if (SVOp->getMask()[i] >= NumElements)
11465 else if (SVOp->getMask()[i] >= 0)
11467 if (SumV2Indices < SumV1Indices) {
11468 return DAG.getCommutedVectorShuffle(*SVOp);
11469 } else if (SumV2Indices == SumV1Indices) {
11470 int NumV1OddIndices = 0, NumV2OddIndices = 0;
11471 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11472 if (SVOp->getMask()[i] >= NumElements)
11473 NumV2OddIndices += i % 2;
11474 else if (SVOp->getMask()[i] >= 0)
11475 NumV1OddIndices += i % 2;
11476 if (NumV2OddIndices < NumV1OddIndices)
11477 return DAG.getCommutedVectorShuffle(*SVOp);
11482 // For each vector width, delegate to a specialized lowering routine.
11483 if (VT.is128BitVector())
11484 return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11486 if (VT.is256BitVector())
11487 return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11489 if (VT.is512BitVector())
11490 return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11493 return lower1BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11494 llvm_unreachable("Unimplemented!");
11497 // This function assumes its argument is a BUILD_VECTOR of constants or
11498 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
11500 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
11501 unsigned &MaskValue) {
11503 unsigned NumElems = BuildVector->getNumOperands();
11505 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
11506 // We don't handle the >2 lanes case right now.
11507 unsigned NumLanes = (NumElems - 1) / 8 + 1;
11511 unsigned NumElemsInLane = NumElems / NumLanes;
11513 // Blend for v16i16 should be symmetric for the both lanes.
11514 for (unsigned i = 0; i < NumElemsInLane; ++i) {
11515 SDValue EltCond = BuildVector->getOperand(i);
11516 SDValue SndLaneEltCond =
11517 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
11519 int Lane1Cond = -1, Lane2Cond = -1;
11520 if (isa<ConstantSDNode>(EltCond))
11521 Lane1Cond = !isNullConstant(EltCond);
11522 if (isa<ConstantSDNode>(SndLaneEltCond))
11523 Lane2Cond = !isNullConstant(SndLaneEltCond);
11525 unsigned LaneMask = 0;
11526 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
11527 // Lane1Cond != 0, means we want the first argument.
11528 // Lane1Cond == 0, means we want the second argument.
11529 // The encoding of this argument is 0 for the first argument, 1
11530 // for the second. Therefore, invert the condition.
11531 LaneMask = !Lane1Cond << i;
11532 else if (Lane1Cond < 0)
11533 LaneMask = !Lane2Cond << i;
11537 MaskValue |= LaneMask;
11539 MaskValue |= LaneMask << NumElemsInLane;
11544 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
11545 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
11546 const X86Subtarget *Subtarget,
11547 SelectionDAG &DAG) {
11548 SDValue Cond = Op.getOperand(0);
11549 SDValue LHS = Op.getOperand(1);
11550 SDValue RHS = Op.getOperand(2);
11552 MVT VT = Op.getSimpleValueType();
11554 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
11556 auto *CondBV = cast<BuildVectorSDNode>(Cond);
11558 // Only non-legal VSELECTs reach this lowering, convert those into generic
11559 // shuffles and re-use the shuffle lowering path for blends.
11560 SmallVector<int, 32> Mask;
11561 for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
11562 SDValue CondElt = CondBV->getOperand(i);
11564 isa<ConstantSDNode>(CondElt) ? i + (isNullConstant(CondElt) ? Size : 0)
11567 return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
11570 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
11571 // A vselect where all conditions and data are constants can be optimized into
11572 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
11573 if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
11574 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
11575 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
11578 // Try to lower this to a blend-style vector shuffle. This can handle all
11579 // constant condition cases.
11580 if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
11583 // Variable blends are only legal from SSE4.1 onward.
11584 if (!Subtarget->hasSSE41())
11587 // Only some types will be legal on some subtargets. If we can emit a legal
11588 // VSELECT-matching blend, return Op, and but if we need to expand, return
11590 switch (Op.getSimpleValueType().SimpleTy) {
11592 // Most of the vector types have blends past SSE4.1.
11596 // The byte blends for AVX vectors were introduced only in AVX2.
11597 if (Subtarget->hasAVX2())
11604 // AVX-512 BWI and VLX features support VSELECT with i16 elements.
11605 if (Subtarget->hasBWI() && Subtarget->hasVLX())
11608 // FIXME: We should custom lower this by fixing the condition and using i8
11614 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
11615 MVT VT = Op.getSimpleValueType();
11618 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
11621 if (VT.getSizeInBits() == 8) {
11622 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
11623 Op.getOperand(0), Op.getOperand(1));
11624 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11625 DAG.getValueType(VT));
11626 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11629 if (VT.getSizeInBits() == 16) {
11630 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
11631 if (isNullConstant(Op.getOperand(1)))
11632 return DAG.getNode(
11633 ISD::TRUNCATE, dl, MVT::i16,
11634 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11635 DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11636 Op.getOperand(1)));
11637 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
11638 Op.getOperand(0), Op.getOperand(1));
11639 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11640 DAG.getValueType(VT));
11641 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11644 if (VT == MVT::f32) {
11645 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
11646 // the result back to FR32 register. It's only worth matching if the
11647 // result has a single use which is a store or a bitcast to i32. And in
11648 // the case of a store, it's not worth it if the index is a constant 0,
11649 // because a MOVSSmr can be used instead, which is smaller and faster.
11650 if (!Op.hasOneUse())
11652 SDNode *User = *Op.getNode()->use_begin();
11653 if ((User->getOpcode() != ISD::STORE ||
11654 isNullConstant(Op.getOperand(1))) &&
11655 (User->getOpcode() != ISD::BITCAST ||
11656 User->getValueType(0) != MVT::i32))
11658 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11659 DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11661 return DAG.getBitcast(MVT::f32, Extract);
11664 if (VT == MVT::i32 || VT == MVT::i64) {
11665 // ExtractPS/pextrq works with constant index.
11666 if (isa<ConstantSDNode>(Op.getOperand(1)))
11672 /// Extract one bit from mask vector, like v16i1 or v8i1.
11673 /// AVX-512 feature.
11675 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
11676 SDValue Vec = Op.getOperand(0);
11678 MVT VecVT = Vec.getSimpleValueType();
11679 SDValue Idx = Op.getOperand(1);
11680 MVT EltVT = Op.getSimpleValueType();
11682 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
11683 assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
11684 "Unexpected vector type in ExtractBitFromMaskVector");
11686 // variable index can't be handled in mask registers,
11687 // extend vector to VR512
11688 if (!isa<ConstantSDNode>(Idx)) {
11689 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
11690 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
11691 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
11692 ExtVT.getVectorElementType(), Ext, Idx);
11693 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
11696 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11697 const TargetRegisterClass* rc = getRegClassFor(VecVT);
11698 if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
11699 rc = getRegClassFor(MVT::v16i1);
11700 unsigned MaxSift = rc->getSize()*8 - 1;
11701 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
11702 DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
11703 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
11704 DAG.getConstant(MaxSift, dl, MVT::i8));
11705 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
11706 DAG.getIntPtrConstant(0, dl));
11710 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
11711 SelectionDAG &DAG) const {
11713 SDValue Vec = Op.getOperand(0);
11714 MVT VecVT = Vec.getSimpleValueType();
11715 SDValue Idx = Op.getOperand(1);
11717 if (Op.getSimpleValueType() == MVT::i1)
11718 return ExtractBitFromMaskVector(Op, DAG);
11720 if (!isa<ConstantSDNode>(Idx)) {
11721 if (VecVT.is512BitVector() ||
11722 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
11723 VecVT.getVectorElementType().getSizeInBits() == 32)) {
11726 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
11727 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
11728 MaskEltVT.getSizeInBits());
11730 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
11731 auto PtrVT = getPointerTy(DAG.getDataLayout());
11732 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
11733 getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
11734 DAG.getConstant(0, dl, PtrVT));
11735 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
11736 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
11737 DAG.getConstant(0, dl, PtrVT));
11742 // If this is a 256-bit vector result, first extract the 128-bit vector and
11743 // then extract the element from the 128-bit vector.
11744 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
11746 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11747 // Get the 128-bit vector.
11748 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
11749 MVT EltVT = VecVT.getVectorElementType();
11751 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
11752 assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
11754 // Find IdxVal modulo ElemsPerChunk. Since ElemsPerChunk is a power of 2
11755 // this can be done with a mask.
11756 IdxVal &= ElemsPerChunk - 1;
11757 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
11758 DAG.getConstant(IdxVal, dl, MVT::i32));
11761 assert(VecVT.is128BitVector() && "Unexpected vector length");
11763 if (Subtarget->hasSSE41())
11764 if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
11767 MVT VT = Op.getSimpleValueType();
11768 // TODO: handle v16i8.
11769 if (VT.getSizeInBits() == 16) {
11770 SDValue Vec = Op.getOperand(0);
11771 if (isNullConstant(Op.getOperand(1)))
11772 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
11773 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11774 DAG.getBitcast(MVT::v4i32, Vec),
11775 Op.getOperand(1)));
11776 // Transform it so it match pextrw which produces a 32-bit result.
11777 MVT EltVT = MVT::i32;
11778 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
11779 Op.getOperand(0), Op.getOperand(1));
11780 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
11781 DAG.getValueType(VT));
11782 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11785 if (VT.getSizeInBits() == 32) {
11786 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11790 // SHUFPS the element to the lowest double word, then movss.
11791 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
11792 MVT VVT = Op.getOperand(0).getSimpleValueType();
11793 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11794 DAG.getUNDEF(VVT), Mask);
11795 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11796 DAG.getIntPtrConstant(0, dl));
11799 if (VT.getSizeInBits() == 64) {
11800 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
11801 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
11802 // to match extract_elt for f64.
11803 if (isNullConstant(Op.getOperand(1)))
11806 // UNPCKHPD the element to the lowest double word, then movsd.
11807 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
11808 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
11809 int Mask[2] = { 1, -1 };
11810 MVT VVT = Op.getOperand(0).getSimpleValueType();
11811 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11812 DAG.getUNDEF(VVT), Mask);
11813 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11814 DAG.getIntPtrConstant(0, dl));
11820 /// Insert one bit to mask vector, like v16i1 or v8i1.
11821 /// AVX-512 feature.
11823 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11825 SDValue Vec = Op.getOperand(0);
11826 SDValue Elt = Op.getOperand(1);
11827 SDValue Idx = Op.getOperand(2);
11828 MVT VecVT = Vec.getSimpleValueType();
11830 if (!isa<ConstantSDNode>(Idx)) {
11831 // Non constant index. Extend source and destination,
11832 // insert element and then truncate the result.
11833 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
11834 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
11835 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11836 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11837 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11838 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11841 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11842 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11844 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11845 DAG.getConstant(IdxVal, dl, MVT::i8));
11846 if (Vec.getOpcode() == ISD::UNDEF)
11848 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11851 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11852 SelectionDAG &DAG) const {
11853 MVT VT = Op.getSimpleValueType();
11854 MVT EltVT = VT.getVectorElementType();
11856 if (EltVT == MVT::i1)
11857 return InsertBitToMaskVector(Op, DAG);
11860 SDValue N0 = Op.getOperand(0);
11861 SDValue N1 = Op.getOperand(1);
11862 SDValue N2 = Op.getOperand(2);
11863 if (!isa<ConstantSDNode>(N2))
11865 auto *N2C = cast<ConstantSDNode>(N2);
11866 unsigned IdxVal = N2C->getZExtValue();
11868 // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11869 // into that, and then insert the subvector back into the result.
11870 if (VT.is256BitVector() || VT.is512BitVector()) {
11871 // With a 256-bit vector, we can insert into the zero element efficiently
11872 // using a blend if we have AVX or AVX2 and the right data type.
11873 if (VT.is256BitVector() && IdxVal == 0) {
11874 // TODO: It is worthwhile to cast integer to floating point and back
11875 // and incur a domain crossing penalty if that's what we'll end up
11876 // doing anyway after extracting to a 128-bit vector.
11877 if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11878 (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11879 SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11880 N2 = DAG.getIntPtrConstant(1, dl);
11881 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11885 // Get the desired 128-bit vector chunk.
11886 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11888 // Insert the element into the desired chunk.
11889 unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11890 assert(isPowerOf2_32(NumEltsIn128));
11891 // Since NumEltsIn128 is a power of 2 we can use mask instead of modulo.
11892 unsigned IdxIn128 = IdxVal & (NumEltsIn128 - 1);
11894 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11895 DAG.getConstant(IdxIn128, dl, MVT::i32));
11897 // Insert the changed part back into the bigger vector
11898 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11900 assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11902 if (Subtarget->hasSSE41()) {
11903 if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11905 if (VT == MVT::v8i16) {
11906 Opc = X86ISD::PINSRW;
11908 assert(VT == MVT::v16i8);
11909 Opc = X86ISD::PINSRB;
11912 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11914 if (N1.getValueType() != MVT::i32)
11915 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11916 if (N2.getValueType() != MVT::i32)
11917 N2 = DAG.getIntPtrConstant(IdxVal, dl);
11918 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11921 if (EltVT == MVT::f32) {
11922 // Bits [7:6] of the constant are the source select. This will always be
11923 // zero here. The DAG Combiner may combine an extract_elt index into
11924 // these bits. For example (insert (extract, 3), 2) could be matched by
11925 // putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11926 // Bits [5:4] of the constant are the destination select. This is the
11927 // value of the incoming immediate.
11928 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11929 // combine either bitwise AND or insert of float 0.0 to set these bits.
11931 bool MinSize = DAG.getMachineFunction().getFunction()->optForMinSize();
11932 if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11933 // If this is an insertion of 32-bits into the low 32-bits of
11934 // a vector, we prefer to generate a blend with immediate rather
11935 // than an insertps. Blends are simpler operations in hardware and so
11936 // will always have equal or better performance than insertps.
11937 // But if optimizing for size and there's a load folding opportunity,
11938 // generate insertps because blendps does not have a 32-bit memory
11940 N2 = DAG.getIntPtrConstant(1, dl);
11941 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11942 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11944 N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11945 // Create this as a scalar to vector..
11946 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11947 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11950 if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11951 // PINSR* works with constant index.
11956 if (EltVT == MVT::i8)
11959 if (EltVT.getSizeInBits() == 16) {
11960 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11961 // as its second argument.
11962 if (N1.getValueType() != MVT::i32)
11963 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11964 if (N2.getValueType() != MVT::i32)
11965 N2 = DAG.getIntPtrConstant(IdxVal, dl);
11966 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11971 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11973 MVT OpVT = Op.getSimpleValueType();
11975 // If this is a 256-bit vector result, first insert into a 128-bit
11976 // vector and then insert into the 256-bit vector.
11977 if (!OpVT.is128BitVector()) {
11978 // Insert into a 128-bit vector.
11979 unsigned SizeFactor = OpVT.getSizeInBits()/128;
11980 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11981 OpVT.getVectorNumElements() / SizeFactor);
11983 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11985 // Insert the 128-bit vector.
11986 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11989 if (OpVT == MVT::v1i64 &&
11990 Op.getOperand(0).getValueType() == MVT::i64)
11991 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11993 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11994 assert(OpVT.is128BitVector() && "Expected an SSE type!");
11995 return DAG.getBitcast(
11996 OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11999 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
12000 // a simple subregister reference or explicit instructions to grab
12001 // upper bits of a vector.
12002 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
12003 SelectionDAG &DAG) {
12005 SDValue In = Op.getOperand(0);
12006 SDValue Idx = Op.getOperand(1);
12007 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12008 MVT ResVT = Op.getSimpleValueType();
12009 MVT InVT = In.getSimpleValueType();
12011 if (Subtarget->hasFp256()) {
12012 if (ResVT.is128BitVector() &&
12013 (InVT.is256BitVector() || InVT.is512BitVector()) &&
12014 isa<ConstantSDNode>(Idx)) {
12015 return Extract128BitVector(In, IdxVal, DAG, dl);
12017 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
12018 isa<ConstantSDNode>(Idx)) {
12019 return Extract256BitVector(In, IdxVal, DAG, dl);
12025 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
12026 // simple superregister reference or explicit instructions to insert
12027 // the upper bits of a vector.
12028 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
12029 SelectionDAG &DAG) {
12030 if (!Subtarget->hasAVX())
12034 SDValue Vec = Op.getOperand(0);
12035 SDValue SubVec = Op.getOperand(1);
12036 SDValue Idx = Op.getOperand(2);
12038 if (!isa<ConstantSDNode>(Idx))
12041 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
12042 MVT OpVT = Op.getSimpleValueType();
12043 MVT SubVecVT = SubVec.getSimpleValueType();
12045 // Fold two 16-byte subvector loads into one 32-byte load:
12046 // (insert_subvector (insert_subvector undef, (load addr), 0),
12047 // (load addr + 16), Elts/2)
12049 if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
12050 Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
12051 OpVT.is256BitVector() && SubVecVT.is128BitVector()) {
12052 auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2));
12053 if (Idx2 && Idx2->getZExtValue() == 0) {
12054 SDValue SubVec2 = Vec.getOperand(1);
12055 // If needed, look through a bitcast to get to the load.
12056 if (SubVec2.getNode() && SubVec2.getOpcode() == ISD::BITCAST)
12057 SubVec2 = SubVec2.getOperand(0);
12059 if (auto *FirstLd = dyn_cast<LoadSDNode>(SubVec2)) {
12061 unsigned Alignment = FirstLd->getAlignment();
12062 unsigned AS = FirstLd->getAddressSpace();
12063 const X86TargetLowering *TLI = Subtarget->getTargetLowering();
12064 if (TLI->allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
12065 OpVT, AS, Alignment, &Fast) && Fast) {
12066 SDValue Ops[] = { SubVec2, SubVec };
12067 if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
12074 if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
12075 SubVecVT.is128BitVector())
12076 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
12078 if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
12079 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
12081 if (OpVT.getVectorElementType() == MVT::i1)
12082 return Insert1BitVector(Op, DAG);
12087 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
12088 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
12089 // one of the above mentioned nodes. It has to be wrapped because otherwise
12090 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
12091 // be used to form addressing mode. These wrapped nodes will be selected
12094 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
12095 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
12097 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12098 // global base reg.
12099 unsigned char OpFlag = 0;
12100 unsigned WrapperKind = X86ISD::Wrapper;
12101 CodeModel::Model M = DAG.getTarget().getCodeModel();
12103 if (Subtarget->isPICStyleRIPRel() &&
12104 (M == CodeModel::Small || M == CodeModel::Kernel))
12105 WrapperKind = X86ISD::WrapperRIP;
12106 else if (Subtarget->isPICStyleGOT())
12107 OpFlag = X86II::MO_GOTOFF;
12108 else if (Subtarget->isPICStyleStubPIC())
12109 OpFlag = X86II::MO_PIC_BASE_OFFSET;
12111 auto PtrVT = getPointerTy(DAG.getDataLayout());
12112 SDValue Result = DAG.getTargetConstantPool(
12113 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
12115 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12116 // With PIC, the address is actually $g + Offset.
12119 DAG.getNode(ISD::ADD, DL, PtrVT,
12120 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
12126 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
12127 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
12129 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12130 // global base reg.
12131 unsigned char OpFlag = 0;
12132 unsigned WrapperKind = X86ISD::Wrapper;
12133 CodeModel::Model M = DAG.getTarget().getCodeModel();
12135 if (Subtarget->isPICStyleRIPRel() &&
12136 (M == CodeModel::Small || M == CodeModel::Kernel))
12137 WrapperKind = X86ISD::WrapperRIP;
12138 else if (Subtarget->isPICStyleGOT())
12139 OpFlag = X86II::MO_GOTOFF;
12140 else if (Subtarget->isPICStyleStubPIC())
12141 OpFlag = X86II::MO_PIC_BASE_OFFSET;
12143 auto PtrVT = getPointerTy(DAG.getDataLayout());
12144 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
12146 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12148 // With PIC, the address is actually $g + Offset.
12151 DAG.getNode(ISD::ADD, DL, PtrVT,
12152 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
12158 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
12159 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
12161 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12162 // global base reg.
12163 unsigned char OpFlag = 0;
12164 unsigned WrapperKind = X86ISD::Wrapper;
12165 CodeModel::Model M = DAG.getTarget().getCodeModel();
12167 if (Subtarget->isPICStyleRIPRel() &&
12168 (M == CodeModel::Small || M == CodeModel::Kernel)) {
12169 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
12170 OpFlag = X86II::MO_GOTPCREL;
12171 WrapperKind = X86ISD::WrapperRIP;
12172 } else if (Subtarget->isPICStyleGOT()) {
12173 OpFlag = X86II::MO_GOT;
12174 } else if (Subtarget->isPICStyleStubPIC()) {
12175 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
12176 } else if (Subtarget->isPICStyleStubNoDynamic()) {
12177 OpFlag = X86II::MO_DARWIN_NONLAZY;
12180 auto PtrVT = getPointerTy(DAG.getDataLayout());
12181 SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
12184 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12186 // With PIC, the address is actually $g + Offset.
12187 if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
12188 !Subtarget->is64Bit()) {
12190 DAG.getNode(ISD::ADD, DL, PtrVT,
12191 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
12194 // For symbols that require a load from a stub to get the address, emit the
12196 if (isGlobalStubReference(OpFlag))
12197 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
12198 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12199 false, false, false, 0);
12205 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
12206 // Create the TargetBlockAddressAddress node.
12207 unsigned char OpFlags =
12208 Subtarget->ClassifyBlockAddressReference();
12209 CodeModel::Model M = DAG.getTarget().getCodeModel();
12210 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
12211 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
12213 auto PtrVT = getPointerTy(DAG.getDataLayout());
12214 SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
12216 if (Subtarget->isPICStyleRIPRel() &&
12217 (M == CodeModel::Small || M == CodeModel::Kernel))
12218 Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
12220 Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
12222 // With PIC, the address is actually $g + Offset.
12223 if (isGlobalRelativeToPICBase(OpFlags)) {
12224 Result = DAG.getNode(ISD::ADD, dl, PtrVT,
12225 DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
12232 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
12233 int64_t Offset, SelectionDAG &DAG) const {
12234 // Create the TargetGlobalAddress node, folding in the constant
12235 // offset if it is legal.
12236 unsigned char OpFlags =
12237 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
12238 CodeModel::Model M = DAG.getTarget().getCodeModel();
12239 auto PtrVT = getPointerTy(DAG.getDataLayout());
12241 if (OpFlags == X86II::MO_NO_FLAG &&
12242 X86::isOffsetSuitableForCodeModel(Offset, M)) {
12243 // A direct static reference to a global.
12244 Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
12247 Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
12250 if (Subtarget->isPICStyleRIPRel() &&
12251 (M == CodeModel::Small || M == CodeModel::Kernel))
12252 Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
12254 Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
12256 // With PIC, the address is actually $g + Offset.
12257 if (isGlobalRelativeToPICBase(OpFlags)) {
12258 Result = DAG.getNode(ISD::ADD, dl, PtrVT,
12259 DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
12262 // For globals that require a load from a stub to get the address, emit the
12264 if (isGlobalStubReference(OpFlags))
12265 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
12266 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12267 false, false, false, 0);
12269 // If there was a non-zero offset that we didn't fold, create an explicit
12270 // addition for it.
12272 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
12273 DAG.getConstant(Offset, dl, PtrVT));
12279 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
12280 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
12281 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
12282 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
12286 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
12287 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
12288 unsigned char OperandFlags, bool LocalDynamic = false) {
12289 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12290 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12292 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12293 GA->getValueType(0),
12297 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
12301 SDValue Ops[] = { Chain, TGA, *InFlag };
12302 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
12304 SDValue Ops[] = { Chain, TGA };
12305 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
12308 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
12309 MFI->setAdjustsStack(true);
12310 MFI->setHasCalls(true);
12312 SDValue Flag = Chain.getValue(1);
12313 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
12316 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
12318 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12321 SDLoc dl(GA); // ? function entry point might be better
12322 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
12323 DAG.getNode(X86ISD::GlobalBaseReg,
12324 SDLoc(), PtrVT), InFlag);
12325 InFlag = Chain.getValue(1);
12327 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
12330 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
12332 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12334 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
12335 X86::RAX, X86II::MO_TLSGD);
12338 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
12344 // Get the start address of the TLS block for this module.
12345 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
12346 .getInfo<X86MachineFunctionInfo>();
12347 MFI->incNumLocalDynamicTLSAccesses();
12351 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
12352 X86II::MO_TLSLD, /*LocalDynamic=*/true);
12355 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
12356 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
12357 InFlag = Chain.getValue(1);
12358 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
12359 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
12362 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
12366 unsigned char OperandFlags = X86II::MO_DTPOFF;
12367 unsigned WrapperKind = X86ISD::Wrapper;
12368 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12369 GA->getValueType(0),
12370 GA->getOffset(), OperandFlags);
12371 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
12373 // Add x@dtpoff with the base.
12374 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
12377 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
12378 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12379 const EVT PtrVT, TLSModel::Model model,
12380 bool is64Bit, bool isPIC) {
12383 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
12384 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
12385 is64Bit ? 257 : 256));
12387 SDValue ThreadPointer =
12388 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
12389 MachinePointerInfo(Ptr), false, false, false, 0);
12391 unsigned char OperandFlags = 0;
12392 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
12394 unsigned WrapperKind = X86ISD::Wrapper;
12395 if (model == TLSModel::LocalExec) {
12396 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
12397 } else if (model == TLSModel::InitialExec) {
12399 OperandFlags = X86II::MO_GOTTPOFF;
12400 WrapperKind = X86ISD::WrapperRIP;
12402 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
12405 llvm_unreachable("Unexpected model");
12408 // emit "addl x@ntpoff,%eax" (local exec)
12409 // or "addl x@indntpoff,%eax" (initial exec)
12410 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
12412 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
12413 GA->getOffset(), OperandFlags);
12414 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
12416 if (model == TLSModel::InitialExec) {
12417 if (isPIC && !is64Bit) {
12418 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
12419 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12423 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
12424 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12425 false, false, false, 0);
12428 // The address of the thread local variable is the add of the thread
12429 // pointer with the offset of the variable.
12430 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
12434 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
12436 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
12438 // Cygwin uses emutls.
12439 // FIXME: It may be EmulatedTLS-generic also for X86-Android.
12440 if (Subtarget->isTargetWindowsCygwin())
12441 return LowerToTLSEmulatedModel(GA, DAG);
12443 const GlobalValue *GV = GA->getGlobal();
12444 auto PtrVT = getPointerTy(DAG.getDataLayout());
12446 if (Subtarget->isTargetELF()) {
12447 if (DAG.getTarget().Options.EmulatedTLS)
12448 return LowerToTLSEmulatedModel(GA, DAG);
12449 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
12451 case TLSModel::GeneralDynamic:
12452 if (Subtarget->is64Bit())
12453 return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
12454 return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
12455 case TLSModel::LocalDynamic:
12456 return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
12457 Subtarget->is64Bit());
12458 case TLSModel::InitialExec:
12459 case TLSModel::LocalExec:
12460 return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
12461 DAG.getTarget().getRelocationModel() ==
12464 llvm_unreachable("Unknown TLS model.");
12467 if (Subtarget->isTargetDarwin()) {
12468 // Darwin only has one model of TLS. Lower to that.
12469 unsigned char OpFlag = 0;
12470 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
12471 X86ISD::WrapperRIP : X86ISD::Wrapper;
12473 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12474 // global base reg.
12475 bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
12476 !Subtarget->is64Bit();
12478 OpFlag = X86II::MO_TLVP_PIC_BASE;
12480 OpFlag = X86II::MO_TLVP;
12482 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
12483 GA->getValueType(0),
12484 GA->getOffset(), OpFlag);
12485 SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12487 // With PIC32, the address is actually $g + Offset.
12489 Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
12490 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12493 // Lowering the machine isd will make sure everything is in the right
12495 SDValue Chain = DAG.getEntryNode();
12496 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12497 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, DL, true), DL);
12498 SDValue Args[] = { Chain, Offset };
12499 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
12501 DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, DL, true),
12502 DAG.getIntPtrConstant(0, DL, true), SDValue(), DL);
12504 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
12505 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12506 MFI->setAdjustsStack(true);
12508 // And our return value (tls address) is in the standard call return value
12510 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12511 return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
12514 if (Subtarget->isTargetKnownWindowsMSVC() ||
12515 Subtarget->isTargetWindowsGNU()) {
12516 // Just use the implicit TLS architecture
12517 // Need to generate someting similar to:
12518 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
12520 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
12521 // mov rcx, qword [rdx+rcx*8]
12522 // mov eax, .tls$:tlsvar
12523 // [rax+rcx] contains the address
12524 // Windows 64bit: gs:0x58
12525 // Windows 32bit: fs:__tls_array
12528 SDValue Chain = DAG.getEntryNode();
12530 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
12531 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
12532 // use its literal value of 0x2C.
12533 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
12534 ? Type::getInt8PtrTy(*DAG.getContext(),
12536 : Type::getInt32PtrTy(*DAG.getContext(),
12539 SDValue TlsArray = Subtarget->is64Bit()
12540 ? DAG.getIntPtrConstant(0x58, dl)
12541 : (Subtarget->isTargetWindowsGNU()
12542 ? DAG.getIntPtrConstant(0x2C, dl)
12543 : DAG.getExternalSymbol("_tls_array", PtrVT));
12545 SDValue ThreadPointer =
12546 DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
12550 if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
12551 res = ThreadPointer;
12553 // Load the _tls_index variable
12554 SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
12555 if (Subtarget->is64Bit())
12556 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
12557 MachinePointerInfo(), MVT::i32, false, false,
12560 IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
12563 auto &DL = DAG.getDataLayout();
12565 DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
12566 IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
12568 res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
12571 res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
12574 // Get the offset of start of .tls section
12575 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12576 GA->getValueType(0),
12577 GA->getOffset(), X86II::MO_SECREL);
12578 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
12580 // The address of the thread local variable is the add of the thread
12581 // pointer with the offset of the variable.
12582 return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
12585 llvm_unreachable("TLS not implemented for this target.");
12588 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
12589 /// and take a 2 x i32 value to shift plus a shift amount.
12590 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
12591 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
12592 MVT VT = Op.getSimpleValueType();
12593 unsigned VTBits = VT.getSizeInBits();
12595 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
12596 SDValue ShOpLo = Op.getOperand(0);
12597 SDValue ShOpHi = Op.getOperand(1);
12598 SDValue ShAmt = Op.getOperand(2);
12599 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
12600 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
12602 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12603 DAG.getConstant(VTBits - 1, dl, MVT::i8));
12604 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
12605 DAG.getConstant(VTBits - 1, dl, MVT::i8))
12606 : DAG.getConstant(0, dl, VT);
12608 SDValue Tmp2, Tmp3;
12609 if (Op.getOpcode() == ISD::SHL_PARTS) {
12610 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
12611 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
12613 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
12614 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
12617 // If the shift amount is larger or equal than the width of a part we can't
12618 // rely on the results of shld/shrd. Insert a test and select the appropriate
12619 // values for large shift amounts.
12620 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12621 DAG.getConstant(VTBits, dl, MVT::i8));
12622 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
12623 AndNode, DAG.getConstant(0, dl, MVT::i8));
12626 SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
12627 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
12628 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
12630 if (Op.getOpcode() == ISD::SHL_PARTS) {
12631 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12632 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12634 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12635 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12638 SDValue Ops[2] = { Lo, Hi };
12639 return DAG.getMergeValues(Ops, dl);
12642 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
12643 SelectionDAG &DAG) const {
12644 SDValue Src = Op.getOperand(0);
12645 MVT SrcVT = Src.getSimpleValueType();
12646 MVT VT = Op.getSimpleValueType();
12649 if (SrcVT.isVector()) {
12650 if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
12651 return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
12652 DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
12653 DAG.getUNDEF(SrcVT)));
12655 if (SrcVT.getVectorElementType() == MVT::i1) {
12656 MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
12657 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12658 DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
12663 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
12664 "Unknown SINT_TO_FP to lower!");
12666 // These are really Legal; return the operand so the caller accepts it as
12668 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
12670 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
12671 Subtarget->is64Bit()) {
12675 unsigned Size = SrcVT.getSizeInBits()/8;
12676 MachineFunction &MF = DAG.getMachineFunction();
12677 auto PtrVT = getPointerTy(MF.getDataLayout());
12678 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
12679 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12680 SDValue Chain = DAG.getStore(
12681 DAG.getEntryNode(), dl, Op.getOperand(0), StackSlot,
12682 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI), false,
12684 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
12687 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
12689 SelectionDAG &DAG) const {
12693 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
12695 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
12697 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
12699 unsigned ByteSize = SrcVT.getSizeInBits()/8;
12701 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
12702 MachineMemOperand *MMO;
12704 int SSFI = FI->getIndex();
12705 MMO = DAG.getMachineFunction().getMachineMemOperand(
12706 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12707 MachineMemOperand::MOLoad, ByteSize, ByteSize);
12709 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
12710 StackSlot = StackSlot.getOperand(1);
12712 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
12713 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
12715 Tys, Ops, SrcVT, MMO);
12718 Chain = Result.getValue(1);
12719 SDValue InFlag = Result.getValue(2);
12721 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
12722 // shouldn't be necessary except that RFP cannot be live across
12723 // multiple blocks. When stackifier is fixed, they can be uncoupled.
12724 MachineFunction &MF = DAG.getMachineFunction();
12725 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
12726 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
12727 auto PtrVT = getPointerTy(MF.getDataLayout());
12728 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12729 Tys = DAG.getVTList(MVT::Other);
12731 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
12733 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12734 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12735 MachineMemOperand::MOStore, SSFISize, SSFISize);
12737 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
12738 Ops, Op.getValueType(), MMO);
12739 Result = DAG.getLoad(
12740 Op.getValueType(), DL, Chain, StackSlot,
12741 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12742 false, false, false, 0);
12748 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
12749 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
12750 SelectionDAG &DAG) const {
12751 // This algorithm is not obvious. Here it is what we're trying to output:
12754 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
12755 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
12757 haddpd %xmm0, %xmm0
12759 pshufd $0x4e, %xmm0, %xmm1
12765 LLVMContext *Context = DAG.getContext();
12767 // Build some magic constants.
12768 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
12769 Constant *C0 = ConstantDataVector::get(*Context, CV0);
12770 auto PtrVT = getPointerTy(DAG.getDataLayout());
12771 SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
12773 SmallVector<Constant*,2> CV1;
12775 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12776 APInt(64, 0x4330000000000000ULL))));
12778 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12779 APInt(64, 0x4530000000000000ULL))));
12780 Constant *C1 = ConstantVector::get(CV1);
12781 SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
12783 // Load the 64-bit value into an XMM register.
12784 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
12787 DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
12788 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12789 false, false, false, 16);
12791 getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
12794 DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
12795 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12796 false, false, false, 16);
12797 SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
12798 // TODO: Are there any fast-math-flags to propagate here?
12799 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
12802 if (Subtarget->hasSSE3()) {
12803 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
12804 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
12806 SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
12807 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
12809 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
12810 DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
12813 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
12814 DAG.getIntPtrConstant(0, dl));
12817 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
12818 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
12819 SelectionDAG &DAG) const {
12821 // FP constant to bias correct the final result.
12822 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
12825 // Load the 32-bit value into an XMM register.
12826 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12829 // Zero out the upper parts of the register.
12830 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12832 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12833 DAG.getBitcast(MVT::v2f64, Load),
12834 DAG.getIntPtrConstant(0, dl));
12836 // Or the load with the bias.
12837 SDValue Or = DAG.getNode(
12838 ISD::OR, dl, MVT::v2i64,
12839 DAG.getBitcast(MVT::v2i64,
12840 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12841 DAG.getBitcast(MVT::v2i64,
12842 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12844 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12845 DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12847 // Subtract the bias.
12848 // TODO: Are there any fast-math-flags to propagate here?
12849 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12851 // Handle final rounding.
12852 MVT DestVT = Op.getSimpleValueType();
12854 if (DestVT.bitsLT(MVT::f64))
12855 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12856 DAG.getIntPtrConstant(0, dl));
12857 if (DestVT.bitsGT(MVT::f64))
12858 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12860 // Handle final rounding.
12864 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12865 const X86Subtarget &Subtarget) {
12866 // The algorithm is the following:
12867 // #ifdef __SSE4_1__
12868 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12869 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12870 // (uint4) 0x53000000, 0xaa);
12872 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12873 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
12875 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12876 // return (float4) lo + fhi;
12878 // We shouldn't use it when unsafe-fp-math is enabled though: we might later
12879 // reassociate the two FADDs, and if we do that, the algorithm fails
12880 // spectacularly (PR24512).
12881 // FIXME: If we ever have some kind of Machine FMF, this should be marked
12882 // as non-fast and always be enabled. Why isn't SDAG FMF enough? Because
12883 // there's also the MachineCombiner reassociations happening on Machine IR.
12884 if (DAG.getTarget().Options.UnsafeFPMath)
12888 SDValue V = Op->getOperand(0);
12889 MVT VecIntVT = V.getSimpleValueType();
12890 bool Is128 = VecIntVT == MVT::v4i32;
12891 MVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12892 // If we convert to something else than the supported type, e.g., to v4f64,
12894 if (VecFloatVT != Op->getSimpleValueType(0))
12897 unsigned NumElts = VecIntVT.getVectorNumElements();
12898 assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12899 "Unsupported custom type");
12900 assert(NumElts <= 8 && "The size of the constant array must be fixed");
12902 // In the #idef/#else code, we have in common:
12903 // - The vector of constants:
12909 // Create the splat vector for 0x4b000000.
12910 SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12911 SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12912 CstLow, CstLow, CstLow, CstLow};
12913 SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12914 makeArrayRef(&CstLowArray[0], NumElts));
12915 // Create the splat vector for 0x53000000.
12916 SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12917 SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12918 CstHigh, CstHigh, CstHigh, CstHigh};
12919 SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12920 makeArrayRef(&CstHighArray[0], NumElts));
12922 // Create the right shift.
12923 SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12924 SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12925 CstShift, CstShift, CstShift, CstShift};
12926 SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12927 makeArrayRef(&CstShiftArray[0], NumElts));
12928 SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12931 if (Subtarget.hasSSE41()) {
12932 MVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12933 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12934 SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12935 SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12936 // Low will be bitcasted right away, so do not bother bitcasting back to its
12938 Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12939 VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12940 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12941 // (uint4) 0x53000000, 0xaa);
12942 SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12943 SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12944 // High will be bitcasted right away, so do not bother bitcasting back to
12945 // its original type.
12946 High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12947 VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12949 SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12950 SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12951 CstMask, CstMask, CstMask);
12952 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12953 SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12954 Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12956 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
12957 High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12960 // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12961 SDValue CstFAdd = DAG.getConstantFP(
12962 APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12963 SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12964 CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12965 SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12966 makeArrayRef(&CstFAddArray[0], NumElts));
12968 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12969 SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12970 // TODO: Are there any fast-math-flags to propagate here?
12972 DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12973 // return (float4) lo + fhi;
12974 SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12975 return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12978 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12979 SelectionDAG &DAG) const {
12980 SDValue N0 = Op.getOperand(0);
12981 MVT SVT = N0.getSimpleValueType();
12984 switch (SVT.SimpleTy) {
12986 llvm_unreachable("Custom UINT_TO_FP is not supported!");
12991 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12992 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12993 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12997 return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
13000 assert(Subtarget->hasAVX512());
13001 return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
13002 DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
13006 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
13007 SelectionDAG &DAG) const {
13008 SDValue N0 = Op.getOperand(0);
13010 auto PtrVT = getPointerTy(DAG.getDataLayout());
13012 if (Op.getSimpleValueType().isVector())
13013 return lowerUINT_TO_FP_vec(Op, DAG);
13015 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
13016 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
13017 // the optimization here.
13018 if (DAG.SignBitIsZero(N0))
13019 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
13021 MVT SrcVT = N0.getSimpleValueType();
13022 MVT DstVT = Op.getSimpleValueType();
13024 if (Subtarget->hasAVX512() && isScalarFPTypeInSSEReg(DstVT) &&
13025 (SrcVT == MVT::i32 || (SrcVT == MVT::i64 && Subtarget->is64Bit()))) {
13026 // Conversions from unsigned i32 to f32/f64 are legal,
13027 // using VCVTUSI2SS/SD. Same for i64 in 64-bit mode.
13031 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
13032 return LowerUINT_TO_FP_i64(Op, DAG);
13033 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
13034 return LowerUINT_TO_FP_i32(Op, DAG);
13035 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
13038 // Make a 64-bit buffer, and use it to build an FILD.
13039 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
13040 if (SrcVT == MVT::i32) {
13041 SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
13042 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
13043 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
13044 StackSlot, MachinePointerInfo(),
13046 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
13047 OffsetSlot, MachinePointerInfo(),
13049 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
13053 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
13054 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
13055 StackSlot, MachinePointerInfo(),
13057 // For i64 source, we need to add the appropriate power of 2 if the input
13058 // was negative. This is the same as the optimization in
13059 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
13060 // we must be careful to do the computation in x87 extended precision, not
13061 // in SSE. (The generic code can't know it's OK to do this, or how to.)
13062 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
13063 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
13064 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
13065 MachineMemOperand::MOLoad, 8, 8);
13067 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
13068 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
13069 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
13072 APInt FF(32, 0x5F800000ULL);
13074 // Check whether the sign bit is set.
13075 SDValue SignSet = DAG.getSetCC(
13076 dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
13077 Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
13079 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
13080 SDValue FudgePtr = DAG.getConstantPool(
13081 ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
13083 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
13084 SDValue Zero = DAG.getIntPtrConstant(0, dl);
13085 SDValue Four = DAG.getIntPtrConstant(4, dl);
13086 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
13088 FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
13090 // Load the value out, extending it from f32 to f80.
13091 // FIXME: Avoid the extend by constructing the right constant pool?
13092 SDValue Fudge = DAG.getExtLoad(
13093 ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), FudgePtr,
13094 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
13095 false, false, false, 4);
13096 // Extend everything to 80 bits to force it to be done on x87.
13097 // TODO: Are there any fast-math-flags to propagate here?
13098 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
13099 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
13100 DAG.getIntPtrConstant(0, dl));
13103 // If the given FP_TO_SINT (IsSigned) or FP_TO_UINT (!IsSigned) operation
13104 // is legal, or has an fp128 or f16 source (which needs to be promoted to f32),
13105 // just return an <SDValue(), SDValue()> pair.
13106 // Otherwise it is assumed to be a conversion from one of f32, f64 or f80
13107 // to i16, i32 or i64, and we lower it to a legal sequence.
13108 // If lowered to the final integer result we return a <result, SDValue()> pair.
13109 // Otherwise we lower it to a sequence ending with a FIST, return a
13110 // <FIST, StackSlot> pair, and the caller is responsible for loading
13111 // the final integer result from StackSlot.
13112 std::pair<SDValue,SDValue>
13113 X86TargetLowering::FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
13114 bool IsSigned, bool IsReplace) const {
13117 EVT DstTy = Op.getValueType();
13118 EVT TheVT = Op.getOperand(0).getValueType();
13119 auto PtrVT = getPointerTy(DAG.getDataLayout());
13121 if (TheVT != MVT::f32 && TheVT != MVT::f64 && TheVT != MVT::f80) {
13122 // f16 must be promoted before using the lowering in this routine.
13123 // fp128 does not use this lowering.
13124 return std::make_pair(SDValue(), SDValue());
13127 // If using FIST to compute an unsigned i64, we'll need some fixup
13128 // to handle values above the maximum signed i64. A FIST is always
13129 // used for the 32-bit subtarget, but also for f80 on a 64-bit target.
13130 bool UnsignedFixup = !IsSigned &&
13131 DstTy == MVT::i64 &&
13132 (!Subtarget->is64Bit() ||
13133 !isScalarFPTypeInSSEReg(TheVT));
13135 if (!IsSigned && DstTy != MVT::i64 && !Subtarget->hasAVX512()) {
13136 // Replace the fp-to-uint32 operation with an fp-to-sint64 FIST.
13137 // The low 32 bits of the fist result will have the correct uint32 result.
13138 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
13142 assert(DstTy.getSimpleVT() <= MVT::i64 &&
13143 DstTy.getSimpleVT() >= MVT::i16 &&
13144 "Unknown FP_TO_INT to lower!");
13146 // These are really Legal.
13147 if (DstTy == MVT::i32 &&
13148 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
13149 return std::make_pair(SDValue(), SDValue());
13150 if (Subtarget->is64Bit() &&
13151 DstTy == MVT::i64 &&
13152 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
13153 return std::make_pair(SDValue(), SDValue());
13155 // We lower FP->int64 into FISTP64 followed by a load from a temporary
13157 MachineFunction &MF = DAG.getMachineFunction();
13158 unsigned MemSize = DstTy.getSizeInBits()/8;
13159 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
13160 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
13163 switch (DstTy.getSimpleVT().SimpleTy) {
13164 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
13165 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
13166 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
13167 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
13170 SDValue Chain = DAG.getEntryNode();
13171 SDValue Value = Op.getOperand(0);
13172 SDValue Adjust; // 0x0 or 0x80000000, for result sign bit adjustment.
13174 if (UnsignedFixup) {
13176 // Conversion to unsigned i64 is implemented with a select,
13177 // depending on whether the source value fits in the range
13178 // of a signed i64. Let Thresh be the FP equivalent of
13179 // 0x8000000000000000ULL.
13181 // Adjust i32 = (Value < Thresh) ? 0 : 0x80000000;
13182 // FistSrc = (Value < Thresh) ? Value : (Value - Thresh);
13183 // Fist-to-mem64 FistSrc
13184 // Add 0 or 0x800...0ULL to the 64-bit result, which is equivalent
13185 // to XOR'ing the high 32 bits with Adjust.
13187 // Being a power of 2, Thresh is exactly representable in all FP formats.
13188 // For X87 we'd like to use the smallest FP type for this constant, but
13189 // for DAG type consistency we have to match the FP operand type.
13191 APFloat Thresh(APFloat::IEEEsingle, APInt(32, 0x5f000000));
13192 LLVM_ATTRIBUTE_UNUSED APFloat::opStatus Status = APFloat::opOK;
13193 bool LosesInfo = false;
13194 if (TheVT == MVT::f64)
13195 // The rounding mode is irrelevant as the conversion should be exact.
13196 Status = Thresh.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
13198 else if (TheVT == MVT::f80)
13199 Status = Thresh.convert(APFloat::x87DoubleExtended,
13200 APFloat::rmNearestTiesToEven, &LosesInfo);
13202 assert(Status == APFloat::opOK && !LosesInfo &&
13203 "FP conversion should have been exact");
13205 SDValue ThreshVal = DAG.getConstantFP(Thresh, DL, TheVT);
13207 SDValue Cmp = DAG.getSetCC(DL,
13208 getSetCCResultType(DAG.getDataLayout(),
13209 *DAG.getContext(), TheVT),
13210 Value, ThreshVal, ISD::SETLT);
13211 Adjust = DAG.getSelect(DL, MVT::i32, Cmp,
13212 DAG.getConstant(0, DL, MVT::i32),
13213 DAG.getConstant(0x80000000, DL, MVT::i32));
13214 SDValue Sub = DAG.getNode(ISD::FSUB, DL, TheVT, Value, ThreshVal);
13215 Cmp = DAG.getSetCC(DL, getSetCCResultType(DAG.getDataLayout(),
13216 *DAG.getContext(), TheVT),
13217 Value, ThreshVal, ISD::SETLT);
13218 Value = DAG.getSelect(DL, TheVT, Cmp, Value, Sub);
13221 // FIXME This causes a redundant load/store if the SSE-class value is already
13222 // in memory, such as if it is on the callstack.
13223 if (isScalarFPTypeInSSEReg(TheVT)) {
13224 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
13225 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
13226 MachinePointerInfo::getFixedStack(MF, SSFI), false,
13228 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
13230 Chain, StackSlot, DAG.getValueType(TheVT)
13233 MachineMemOperand *MMO =
13234 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
13235 MachineMemOperand::MOLoad, MemSize, MemSize);
13236 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
13237 Chain = Value.getValue(1);
13238 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
13239 StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
13242 MachineMemOperand *MMO =
13243 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
13244 MachineMemOperand::MOStore, MemSize, MemSize);
13246 if (UnsignedFixup) {
13248 // Insert the FIST, load its result as two i32's,
13249 // and XOR the high i32 with Adjust.
13251 SDValue FistOps[] = { Chain, Value, StackSlot };
13252 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
13253 FistOps, DstTy, MMO);
13255 SDValue Low32 = DAG.getLoad(MVT::i32, DL, FIST, StackSlot,
13256 MachinePointerInfo(),
13257 false, false, false, 0);
13258 SDValue HighAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackSlot,
13259 DAG.getConstant(4, DL, PtrVT));
13261 SDValue High32 = DAG.getLoad(MVT::i32, DL, FIST, HighAddr,
13262 MachinePointerInfo(),
13263 false, false, false, 0);
13264 High32 = DAG.getNode(ISD::XOR, DL, MVT::i32, High32, Adjust);
13266 if (Subtarget->is64Bit()) {
13267 // Join High32 and Low32 into a 64-bit result.
13268 // (High32 << 32) | Low32
13269 Low32 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Low32);
13270 High32 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, High32);
13271 High32 = DAG.getNode(ISD::SHL, DL, MVT::i64, High32,
13272 DAG.getConstant(32, DL, MVT::i8));
13273 SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i64, High32, Low32);
13274 return std::make_pair(Result, SDValue());
13277 SDValue ResultOps[] = { Low32, High32 };
13279 SDValue pair = IsReplace
13280 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResultOps)
13281 : DAG.getMergeValues(ResultOps, DL);
13282 return std::make_pair(pair, SDValue());
13284 // Build the FP_TO_INT*_IN_MEM
13285 SDValue Ops[] = { Chain, Value, StackSlot };
13286 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
13288 return std::make_pair(FIST, StackSlot);
13292 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
13293 const X86Subtarget *Subtarget) {
13294 MVT VT = Op->getSimpleValueType(0);
13295 SDValue In = Op->getOperand(0);
13296 MVT InVT = In.getSimpleValueType();
13299 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13300 return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
13302 // Optimize vectors in AVX mode:
13305 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
13306 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
13307 // Concat upper and lower parts.
13310 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
13311 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
13312 // Concat upper and lower parts.
13315 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
13316 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
13317 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
13320 if (Subtarget->hasInt256())
13321 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
13323 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
13324 SDValue Undef = DAG.getUNDEF(InVT);
13325 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
13326 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
13327 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
13329 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
13330 VT.getVectorNumElements()/2);
13332 OpLo = DAG.getBitcast(HVT, OpLo);
13333 OpHi = DAG.getBitcast(HVT, OpHi);
13335 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13338 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
13339 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
13340 MVT VT = Op->getSimpleValueType(0);
13341 SDValue In = Op->getOperand(0);
13342 MVT InVT = In.getSimpleValueType();
13344 unsigned int NumElts = VT.getVectorNumElements();
13345 if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
13348 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
13349 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
13351 assert(InVT.getVectorElementType() == MVT::i1);
13352 MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
13354 DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
13356 DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
13358 SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
13359 if (VT.is512BitVector())
13361 return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
13364 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13365 SelectionDAG &DAG) {
13366 if (Subtarget->hasFp256())
13367 if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
13373 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13374 SelectionDAG &DAG) {
13376 MVT VT = Op.getSimpleValueType();
13377 SDValue In = Op.getOperand(0);
13378 MVT SVT = In.getSimpleValueType();
13380 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
13381 return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
13383 if (Subtarget->hasFp256())
13384 if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
13387 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
13388 VT.getVectorNumElements() != SVT.getVectorNumElements());
13392 static SDValue LowerTruncateVecI1(SDValue Op, SelectionDAG &DAG,
13393 const X86Subtarget *Subtarget) {
13396 MVT VT = Op.getSimpleValueType();
13397 SDValue In = Op.getOperand(0);
13398 MVT InVT = In.getSimpleValueType();
13400 assert(VT.getVectorElementType() == MVT::i1 && "Unexected vector type.");
13402 // Shift LSB to MSB and use VPMOVB2M - SKX.
13403 unsigned ShiftInx = InVT.getScalarSizeInBits() - 1;
13404 if ((InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
13405 Subtarget->hasBWI()) || // legal, will go to VPMOVB2M, VPMOVW2M
13406 ((InVT.is256BitVector() || InVT.is128BitVector()) &&
13407 InVT.getScalarSizeInBits() <= 16 && Subtarget->hasBWI() &&
13408 Subtarget->hasVLX())) { // legal, will go to VPMOVB2M, VPMOVW2M
13409 // Shift packed bytes not supported natively, bitcast to dword
13410 MVT ExtVT = MVT::getVectorVT(MVT::i16, InVT.getSizeInBits()/16);
13411 SDValue ShiftNode = DAG.getNode(ISD::SHL, DL, ExtVT,
13412 DAG.getBitcast(ExtVT, In),
13413 DAG.getConstant(ShiftInx, DL, ExtVT));
13414 ShiftNode = DAG.getBitcast(InVT, ShiftNode);
13415 return DAG.getNode(X86ISD::CVT2MASK, DL, VT, ShiftNode);
13417 if ((InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
13418 Subtarget->hasDQI()) || // legal, will go to VPMOVD2M, VPMOVQ2M
13419 ((InVT.is256BitVector() || InVT.is128BitVector()) &&
13420 InVT.getScalarSizeInBits() >= 32 && Subtarget->hasDQI() &&
13421 Subtarget->hasVLX())) { // legal, will go to VPMOVD2M, VPMOVQ2M
13423 SDValue ShiftNode = DAG.getNode(ISD::SHL, DL, InVT, In,
13424 DAG.getConstant(ShiftInx, DL, InVT));
13425 return DAG.getNode(X86ISD::CVT2MASK, DL, VT, ShiftNode);
13428 // Shift LSB to MSB, extend if necessary and use TESTM.
13429 unsigned NumElts = InVT.getVectorNumElements();
13430 if (InVT.getSizeInBits() < 512 &&
13431 (InVT.getScalarType() == MVT::i8 || InVT.getScalarType() == MVT::i16 ||
13432 !Subtarget->hasVLX())) {
13433 assert((NumElts == 8 || NumElts == 16) && "Unexected vector type.");
13435 // TESTD/Q should be used (if BW supported we use CVT2MASK above),
13436 // so vector should be extended to packed dword/qword.
13437 MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(512/NumElts), NumElts);
13438 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
13440 ShiftInx = InVT.getScalarSizeInBits() - 1;
13443 SDValue ShiftNode = DAG.getNode(ISD::SHL, DL, InVT, In,
13444 DAG.getConstant(ShiftInx, DL, InVT));
13445 return DAG.getNode(X86ISD::TESTM, DL, VT, ShiftNode, ShiftNode);
13448 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
13450 MVT VT = Op.getSimpleValueType();
13451 SDValue In = Op.getOperand(0);
13452 MVT InVT = In.getSimpleValueType();
13454 if (VT == MVT::i1) {
13455 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
13456 "Invalid scalar TRUNCATE operation");
13457 if (InVT.getSizeInBits() >= 32)
13459 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
13460 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
13462 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
13463 "Invalid TRUNCATE operation");
13465 if (VT.getVectorElementType() == MVT::i1)
13466 return LowerTruncateVecI1(Op, DAG, Subtarget);
13468 // vpmovqb/w/d, vpmovdb/w, vpmovwb
13469 if (Subtarget->hasAVX512()) {
13470 // word to byte only under BWI
13471 if (InVT == MVT::v16i16 && !Subtarget->hasBWI()) // v16i16 -> v16i8
13472 return DAG.getNode(X86ISD::VTRUNC, DL, VT,
13473 DAG.getNode(X86ISD::VSEXT, DL, MVT::v16i32, In));
13474 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
13476 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
13477 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
13478 if (Subtarget->hasInt256()) {
13479 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13480 In = DAG.getBitcast(MVT::v8i32, In);
13481 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
13483 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
13484 DAG.getIntPtrConstant(0, DL));
13487 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13488 DAG.getIntPtrConstant(0, DL));
13489 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13490 DAG.getIntPtrConstant(2, DL));
13491 OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13492 OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13493 static const int ShufMask[] = {0, 2, 4, 6};
13494 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
13497 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
13498 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
13499 if (Subtarget->hasInt256()) {
13500 In = DAG.getBitcast(MVT::v32i8, In);
13502 SmallVector<SDValue,32> pshufbMask;
13503 for (unsigned i = 0; i < 2; ++i) {
13504 pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
13505 pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
13506 pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
13507 pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
13508 pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
13509 pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
13510 pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
13511 pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
13512 for (unsigned j = 0; j < 8; ++j)
13513 pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
13515 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
13516 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
13517 In = DAG.getBitcast(MVT::v4i64, In);
13519 static const int ShufMask[] = {0, 2, -1, -1};
13520 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
13522 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13523 DAG.getIntPtrConstant(0, DL));
13524 return DAG.getBitcast(VT, In);
13527 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13528 DAG.getIntPtrConstant(0, DL));
13530 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13531 DAG.getIntPtrConstant(4, DL));
13533 OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
13534 OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
13536 // The PSHUFB mask:
13537 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
13538 -1, -1, -1, -1, -1, -1, -1, -1};
13540 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
13541 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
13542 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
13544 OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13545 OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13547 // The MOVLHPS Mask:
13548 static const int ShufMask2[] = {0, 1, 4, 5};
13549 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
13550 return DAG.getBitcast(MVT::v8i16, res);
13553 // Handle truncation of V256 to V128 using shuffles.
13554 if (!VT.is128BitVector() || !InVT.is256BitVector())
13557 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
13559 unsigned NumElems = VT.getVectorNumElements();
13560 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
13562 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
13563 // Prepare truncation shuffle mask
13564 for (unsigned i = 0; i != NumElems; ++i)
13565 MaskVec[i] = i * 2;
13566 SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
13567 DAG.getUNDEF(NVT), &MaskVec[0]);
13568 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
13569 DAG.getIntPtrConstant(0, DL));
13572 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
13573 SelectionDAG &DAG) const {
13574 assert(!Op.getSimpleValueType().isVector());
13576 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13577 /*IsSigned=*/ true, /*IsReplace=*/ false);
13578 SDValue FIST = Vals.first, StackSlot = Vals.second;
13579 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13580 if (!FIST.getNode())
13583 if (StackSlot.getNode())
13584 // Load the result.
13585 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13586 FIST, StackSlot, MachinePointerInfo(),
13587 false, false, false, 0);
13589 // The node is the result.
13593 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
13594 SelectionDAG &DAG) const {
13595 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13596 /*IsSigned=*/ false, /*IsReplace=*/ false);
13597 SDValue FIST = Vals.first, StackSlot = Vals.second;
13598 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13599 if (!FIST.getNode())
13602 if (StackSlot.getNode())
13603 // Load the result.
13604 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13605 FIST, StackSlot, MachinePointerInfo(),
13606 false, false, false, 0);
13608 // The node is the result.
13612 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
13614 MVT VT = Op.getSimpleValueType();
13615 SDValue In = Op.getOperand(0);
13616 MVT SVT = In.getSimpleValueType();
13618 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
13620 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
13621 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
13622 In, DAG.getUNDEF(SVT)));
13625 /// The only differences between FABS and FNEG are the mask and the logic op.
13626 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
13627 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
13628 assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
13629 "Wrong opcode for lowering FABS or FNEG.");
13631 bool IsFABS = (Op.getOpcode() == ISD::FABS);
13633 // If this is a FABS and it has an FNEG user, bail out to fold the combination
13634 // into an FNABS. We'll lower the FABS after that if it is still in use.
13636 for (SDNode *User : Op->uses())
13637 if (User->getOpcode() == ISD::FNEG)
13641 MVT VT = Op.getSimpleValueType();
13643 bool IsF128 = (VT == MVT::f128);
13645 // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
13646 // decide if we should generate a 16-byte constant mask when we only need 4 or
13647 // 8 bytes for the scalar case.
13653 if (VT.isVector()) {
13655 EltVT = VT.getVectorElementType();
13656 NumElts = VT.getVectorNumElements();
13657 } else if (IsF128) {
13658 // SSE instructions are used for optimized f128 logical operations.
13659 LogicVT = MVT::f128;
13663 // There are no scalar bitwise logical SSE/AVX instructions, so we
13664 // generate a 16-byte vector constant and logic op even for the scalar case.
13665 // Using a 16-byte mask allows folding the load of the mask with
13666 // the logic op, so it can save (~4 bytes) on code size.
13667 LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
13669 NumElts = (VT == MVT::f64) ? 2 : 4;
13672 unsigned EltBits = EltVT.getSizeInBits();
13673 LLVMContext *Context = DAG.getContext();
13674 // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
13676 IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
13677 Constant *C = ConstantInt::get(*Context, MaskElt);
13678 C = ConstantVector::getSplat(NumElts, C);
13679 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13680 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
13681 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13683 DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13684 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13685 false, false, false, Alignment);
13687 SDValue Op0 = Op.getOperand(0);
13688 bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
13690 IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
13691 SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
13693 if (VT.isVector() || IsF128)
13694 return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13696 // For the scalar case extend to a 128-bit vector, perform the logic op,
13697 // and extract the scalar result back out.
13698 Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
13699 SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13700 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
13701 DAG.getIntPtrConstant(0, dl));
13704 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
13705 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13706 LLVMContext *Context = DAG.getContext();
13707 SDValue Op0 = Op.getOperand(0);
13708 SDValue Op1 = Op.getOperand(1);
13710 MVT VT = Op.getSimpleValueType();
13711 MVT SrcVT = Op1.getSimpleValueType();
13712 bool IsF128 = (VT == MVT::f128);
13714 // If second operand is smaller, extend it first.
13715 if (SrcVT.bitsLT(VT)) {
13716 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
13719 // And if it is bigger, shrink it first.
13720 if (SrcVT.bitsGT(VT)) {
13721 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
13725 // At this point the operands and the result should have the same
13726 // type, and that won't be f80 since that is not custom lowered.
13727 assert((VT == MVT::f64 || VT == MVT::f32 || IsF128) &&
13728 "Unexpected type in LowerFCOPYSIGN");
13730 const fltSemantics &Sem =
13731 VT == MVT::f64 ? APFloat::IEEEdouble :
13732 (IsF128 ? APFloat::IEEEquad : APFloat::IEEEsingle);
13733 const unsigned SizeInBits = VT.getSizeInBits();
13735 SmallVector<Constant *, 4> CV(
13736 VT == MVT::f64 ? 2 : (IsF128 ? 1 : 4),
13737 ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
13739 // First, clear all bits but the sign bit from the second operand (sign).
13740 CV[0] = ConstantFP::get(*Context,
13741 APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
13742 Constant *C = ConstantVector::get(CV);
13743 auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
13744 SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13746 // Perform all logic operations as 16-byte vectors because there are no
13747 // scalar FP logic instructions in SSE. This allows load folding of the
13748 // constants into the logic instructions.
13749 MVT LogicVT = (VT == MVT::f64) ? MVT::v2f64 : (IsF128 ? MVT::f128 : MVT::v4f32);
13751 DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13752 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13753 false, false, false, 16);
13755 Op1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op1);
13756 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op1, Mask1);
13758 // Next, clear the sign bit from the first operand (magnitude).
13759 // If it's a constant, we can clear it here.
13760 if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
13761 APFloat APF = Op0CN->getValueAPF();
13762 // If the magnitude is a positive zero, the sign bit alone is enough.
13763 if (APF.isPosZero())
13764 return IsF128 ? SignBit :
13765 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, SignBit,
13766 DAG.getIntPtrConstant(0, dl));
13768 CV[0] = ConstantFP::get(*Context, APF);
13770 CV[0] = ConstantFP::get(
13772 APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
13774 C = ConstantVector::get(CV);
13775 CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13777 DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13778 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13779 false, false, false, 16);
13780 // If the magnitude operand wasn't a constant, we need to AND out the sign.
13781 if (!isa<ConstantFPSDNode>(Op0)) {
13783 Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op0);
13784 Val = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op0, Val);
13786 // OR the magnitude value with the sign bit.
13787 Val = DAG.getNode(X86ISD::FOR, dl, LogicVT, Val, SignBit);
13788 return IsF128 ? Val :
13789 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, Val,
13790 DAG.getIntPtrConstant(0, dl));
13793 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
13794 SDValue N0 = Op.getOperand(0);
13796 MVT VT = Op.getSimpleValueType();
13798 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
13799 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
13800 DAG.getConstant(1, dl, VT));
13801 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
13804 // Check whether an OR'd tree is PTEST-able.
13805 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
13806 SelectionDAG &DAG) {
13807 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
13809 if (!Subtarget->hasSSE41())
13812 if (!Op->hasOneUse())
13815 SDNode *N = Op.getNode();
13818 SmallVector<SDValue, 8> Opnds;
13819 DenseMap<SDValue, unsigned> VecInMap;
13820 SmallVector<SDValue, 8> VecIns;
13821 EVT VT = MVT::Other;
13823 // Recognize a special case where a vector is casted into wide integer to
13825 Opnds.push_back(N->getOperand(0));
13826 Opnds.push_back(N->getOperand(1));
13828 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
13829 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
13830 // BFS traverse all OR'd operands.
13831 if (I->getOpcode() == ISD::OR) {
13832 Opnds.push_back(I->getOperand(0));
13833 Opnds.push_back(I->getOperand(1));
13834 // Re-evaluate the number of nodes to be traversed.
13835 e += 2; // 2 more nodes (LHS and RHS) are pushed.
13839 // Quit if a non-EXTRACT_VECTOR_ELT
13840 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13843 // Quit if without a constant index.
13844 SDValue Idx = I->getOperand(1);
13845 if (!isa<ConstantSDNode>(Idx))
13848 SDValue ExtractedFromVec = I->getOperand(0);
13849 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
13850 if (M == VecInMap.end()) {
13851 VT = ExtractedFromVec.getValueType();
13852 // Quit if not 128/256-bit vector.
13853 if (!VT.is128BitVector() && !VT.is256BitVector())
13855 // Quit if not the same type.
13856 if (VecInMap.begin() != VecInMap.end() &&
13857 VT != VecInMap.begin()->first.getValueType())
13859 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
13860 VecIns.push_back(ExtractedFromVec);
13862 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
13865 assert((VT.is128BitVector() || VT.is256BitVector()) &&
13866 "Not extracted from 128-/256-bit vector.");
13868 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
13870 for (DenseMap<SDValue, unsigned>::const_iterator
13871 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
13872 // Quit if not all elements are used.
13873 if (I->second != FullMask)
13877 MVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
13879 // Cast all vectors into TestVT for PTEST.
13880 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
13881 VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
13883 // If more than one full vectors are evaluated, OR them first before PTEST.
13884 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
13885 // Each iteration will OR 2 nodes and append the result until there is only
13886 // 1 node left, i.e. the final OR'd value of all vectors.
13887 SDValue LHS = VecIns[Slot];
13888 SDValue RHS = VecIns[Slot + 1];
13889 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
13892 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
13893 VecIns.back(), VecIns.back());
13896 /// \brief return true if \c Op has a use that doesn't just read flags.
13897 static bool hasNonFlagsUse(SDValue Op) {
13898 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
13900 SDNode *User = *UI;
13901 unsigned UOpNo = UI.getOperandNo();
13902 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
13903 // Look pass truncate.
13904 UOpNo = User->use_begin().getOperandNo();
13905 User = *User->use_begin();
13908 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
13909 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
13915 /// Emit nodes that will be selected as "test Op0,Op0", or something
13917 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
13918 SelectionDAG &DAG) const {
13919 if (Op.getValueType() == MVT::i1) {
13920 SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
13921 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
13922 DAG.getConstant(0, dl, MVT::i8));
13924 // CF and OF aren't always set the way we want. Determine which
13925 // of these we need.
13926 bool NeedCF = false;
13927 bool NeedOF = false;
13930 case X86::COND_A: case X86::COND_AE:
13931 case X86::COND_B: case X86::COND_BE:
13934 case X86::COND_G: case X86::COND_GE:
13935 case X86::COND_L: case X86::COND_LE:
13936 case X86::COND_O: case X86::COND_NO: {
13937 // Check if we really need to set the
13938 // Overflow flag. If NoSignedWrap is present
13939 // that is not actually needed.
13940 switch (Op->getOpcode()) {
13945 const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
13946 if (BinNode->Flags.hasNoSignedWrap())
13956 // See if we can use the EFLAGS value from the operand instead of
13957 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
13958 // we prove that the arithmetic won't overflow, we can't use OF or CF.
13959 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
13960 // Emit a CMP with 0, which is the TEST pattern.
13961 //if (Op.getValueType() == MVT::i1)
13962 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
13963 // DAG.getConstant(0, MVT::i1));
13964 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13965 DAG.getConstant(0, dl, Op.getValueType()));
13967 unsigned Opcode = 0;
13968 unsigned NumOperands = 0;
13970 // Truncate operations may prevent the merge of the SETCC instruction
13971 // and the arithmetic instruction before it. Attempt to truncate the operands
13972 // of the arithmetic instruction and use a reduced bit-width instruction.
13973 bool NeedTruncation = false;
13974 SDValue ArithOp = Op;
13975 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
13976 SDValue Arith = Op->getOperand(0);
13977 // Both the trunc and the arithmetic op need to have one user each.
13978 if (Arith->hasOneUse())
13979 switch (Arith.getOpcode()) {
13986 NeedTruncation = true;
13992 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
13993 // which may be the result of a CAST. We use the variable 'Op', which is the
13994 // non-casted variable when we check for possible users.
13995 switch (ArithOp.getOpcode()) {
13997 // Due to an isel shortcoming, be conservative if this add is likely to be
13998 // selected as part of a load-modify-store instruction. When the root node
13999 // in a match is a store, isel doesn't know how to remap non-chain non-flag
14000 // uses of other nodes in the match, such as the ADD in this case. This
14001 // leads to the ADD being left around and reselected, with the result being
14002 // two adds in the output. Alas, even if none our users are stores, that
14003 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
14004 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
14005 // climbing the DAG back to the root, and it doesn't seem to be worth the
14007 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14008 UE = Op.getNode()->use_end(); UI != UE; ++UI)
14009 if (UI->getOpcode() != ISD::CopyToReg &&
14010 UI->getOpcode() != ISD::SETCC &&
14011 UI->getOpcode() != ISD::STORE)
14014 if (ConstantSDNode *C =
14015 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
14016 // An add of one will be selected as an INC.
14017 if (C->isOne() && !Subtarget->slowIncDec()) {
14018 Opcode = X86ISD::INC;
14023 // An add of negative one (subtract of one) will be selected as a DEC.
14024 if (C->isAllOnesValue() && !Subtarget->slowIncDec()) {
14025 Opcode = X86ISD::DEC;
14031 // Otherwise use a regular EFLAGS-setting add.
14032 Opcode = X86ISD::ADD;
14037 // If we have a constant logical shift that's only used in a comparison
14038 // against zero turn it into an equivalent AND. This allows turning it into
14039 // a TEST instruction later.
14040 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
14041 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
14042 EVT VT = Op.getValueType();
14043 unsigned BitWidth = VT.getSizeInBits();
14044 unsigned ShAmt = Op->getConstantOperandVal(1);
14045 if (ShAmt >= BitWidth) // Avoid undefined shifts.
14047 APInt Mask = ArithOp.getOpcode() == ISD::SRL
14048 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
14049 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
14050 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
14052 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
14053 DAG.getConstant(Mask, dl, VT));
14054 DAG.ReplaceAllUsesWith(Op, New);
14060 // If the primary and result isn't used, don't bother using X86ISD::AND,
14061 // because a TEST instruction will be better.
14062 if (!hasNonFlagsUse(Op))
14068 // Due to the ISEL shortcoming noted above, be conservative if this op is
14069 // likely to be selected as part of a load-modify-store instruction.
14070 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14071 UE = Op.getNode()->use_end(); UI != UE; ++UI)
14072 if (UI->getOpcode() == ISD::STORE)
14075 // Otherwise use a regular EFLAGS-setting instruction.
14076 switch (ArithOp.getOpcode()) {
14077 default: llvm_unreachable("unexpected operator!");
14078 case ISD::SUB: Opcode = X86ISD::SUB; break;
14079 case ISD::XOR: Opcode = X86ISD::XOR; break;
14080 case ISD::AND: Opcode = X86ISD::AND; break;
14082 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
14083 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
14084 if (EFLAGS.getNode())
14087 Opcode = X86ISD::OR;
14101 return SDValue(Op.getNode(), 1);
14107 // If we found that truncation is beneficial, perform the truncation and
14109 if (NeedTruncation) {
14110 EVT VT = Op.getValueType();
14111 SDValue WideVal = Op->getOperand(0);
14112 EVT WideVT = WideVal.getValueType();
14113 unsigned ConvertedOp = 0;
14114 // Use a target machine opcode to prevent further DAGCombine
14115 // optimizations that may separate the arithmetic operations
14116 // from the setcc node.
14117 switch (WideVal.getOpcode()) {
14119 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
14120 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
14121 case ISD::AND: ConvertedOp = X86ISD::AND; break;
14122 case ISD::OR: ConvertedOp = X86ISD::OR; break;
14123 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
14127 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14128 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
14129 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
14130 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
14131 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
14137 // Emit a CMP with 0, which is the TEST pattern.
14138 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
14139 DAG.getConstant(0, dl, Op.getValueType()));
14141 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14142 SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
14144 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
14145 DAG.ReplaceAllUsesWith(Op, New);
14146 return SDValue(New.getNode(), 1);
14149 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
14151 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
14152 SDLoc dl, SelectionDAG &DAG) const {
14153 if (isNullConstant(Op1))
14154 return EmitTest(Op0, X86CC, dl, DAG);
14156 assert(!(isa<ConstantSDNode>(Op1) && Op0.getValueType() == MVT::i1) &&
14157 "Unexpected comparison operation for MVT::i1 operands");
14159 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
14160 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
14161 // Do the comparison at i32 if it's smaller, besides the Atom case.
14162 // This avoids subregister aliasing issues. Keep the smaller reference
14163 // if we're optimizing for size, however, as that'll allow better folding
14164 // of memory operations.
14165 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
14166 !DAG.getMachineFunction().getFunction()->optForMinSize() &&
14167 !Subtarget->isAtom()) {
14168 unsigned ExtendOp =
14169 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
14170 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
14171 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
14173 // Use SUB instead of CMP to enable CSE between SUB and CMP.
14174 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
14175 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
14177 return SDValue(Sub.getNode(), 1);
14179 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
14182 /// Convert a comparison if required by the subtarget.
14183 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
14184 SelectionDAG &DAG) const {
14185 // If the subtarget does not support the FUCOMI instruction, floating-point
14186 // comparisons have to be converted.
14187 if (Subtarget->hasCMov() ||
14188 Cmp.getOpcode() != X86ISD::CMP ||
14189 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
14190 !Cmp.getOperand(1).getValueType().isFloatingPoint())
14193 // The instruction selector will select an FUCOM instruction instead of
14194 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
14195 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
14196 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
14198 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
14199 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
14200 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
14201 DAG.getConstant(8, dl, MVT::i8));
14202 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
14204 // Some 64-bit targets lack SAHF support, but they do support FCOMI.
14205 assert(Subtarget->hasLAHFSAHF() && "Target doesn't support SAHF or FCOMI?");
14206 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
14209 /// The minimum architected relative accuracy is 2^-12. We need one
14210 /// Newton-Raphson step to have a good float result (24 bits of precision).
14211 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
14212 DAGCombinerInfo &DCI,
14213 unsigned &RefinementSteps,
14214 bool &UseOneConstNR) const {
14215 EVT VT = Op.getValueType();
14216 const char *RecipOp;
14218 // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
14219 // TODO: Add support for AVX512 (v16f32).
14220 // It is likely not profitable to do this for f64 because a double-precision
14221 // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
14222 // instructions: convert to single, rsqrtss, convert back to double, refine
14223 // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
14224 // along with FMA, this could be a throughput win.
14225 if (VT == MVT::f32 && Subtarget->hasSSE1())
14227 else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
14228 (VT == MVT::v8f32 && Subtarget->hasAVX()))
14229 RecipOp = "vec-sqrtf";
14233 TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
14234 if (!Recips.isEnabled(RecipOp))
14237 RefinementSteps = Recips.getRefinementSteps(RecipOp);
14238 UseOneConstNR = false;
14239 return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
14242 /// The minimum architected relative accuracy is 2^-12. We need one
14243 /// Newton-Raphson step to have a good float result (24 bits of precision).
14244 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
14245 DAGCombinerInfo &DCI,
14246 unsigned &RefinementSteps) const {
14247 EVT VT = Op.getValueType();
14248 const char *RecipOp;
14250 // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
14251 // TODO: Add support for AVX512 (v16f32).
14252 // It is likely not profitable to do this for f64 because a double-precision
14253 // reciprocal estimate with refinement on x86 prior to FMA requires
14254 // 15 instructions: convert to single, rcpss, convert back to double, refine
14255 // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
14256 // along with FMA, this could be a throughput win.
14257 if (VT == MVT::f32 && Subtarget->hasSSE1())
14259 else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
14260 (VT == MVT::v8f32 && Subtarget->hasAVX()))
14261 RecipOp = "vec-divf";
14265 TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
14266 if (!Recips.isEnabled(RecipOp))
14269 RefinementSteps = Recips.getRefinementSteps(RecipOp);
14270 return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
14273 /// If we have at least two divisions that use the same divisor, convert to
14274 /// multplication by a reciprocal. This may need to be adjusted for a given
14275 /// CPU if a division's cost is not at least twice the cost of a multiplication.
14276 /// This is because we still need one division to calculate the reciprocal and
14277 /// then we need two multiplies by that reciprocal as replacements for the
14278 /// original divisions.
14279 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
14283 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
14284 /// if it's possible.
14285 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
14286 SDLoc dl, SelectionDAG &DAG) const {
14287 SDValue Op0 = And.getOperand(0);
14288 SDValue Op1 = And.getOperand(1);
14289 if (Op0.getOpcode() == ISD::TRUNCATE)
14290 Op0 = Op0.getOperand(0);
14291 if (Op1.getOpcode() == ISD::TRUNCATE)
14292 Op1 = Op1.getOperand(0);
14295 if (Op1.getOpcode() == ISD::SHL)
14296 std::swap(Op0, Op1);
14297 if (Op0.getOpcode() == ISD::SHL) {
14298 if (isOneConstant(Op0.getOperand(0))) {
14299 // If we looked past a truncate, check that it's only truncating away
14301 unsigned BitWidth = Op0.getValueSizeInBits();
14302 unsigned AndBitWidth = And.getValueSizeInBits();
14303 if (BitWidth > AndBitWidth) {
14305 DAG.computeKnownBits(Op0, Zeros, Ones);
14306 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
14310 RHS = Op0.getOperand(1);
14312 } else if (Op1.getOpcode() == ISD::Constant) {
14313 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
14314 uint64_t AndRHSVal = AndRHS->getZExtValue();
14315 SDValue AndLHS = Op0;
14317 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
14318 LHS = AndLHS.getOperand(0);
14319 RHS = AndLHS.getOperand(1);
14322 // Use BT if the immediate can't be encoded in a TEST instruction.
14323 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
14325 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
14329 if (LHS.getNode()) {
14330 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
14331 // instruction. Since the shift amount is in-range-or-undefined, we know
14332 // that doing a bittest on the i32 value is ok. We extend to i32 because
14333 // the encoding for the i16 version is larger than the i32 version.
14334 // Also promote i16 to i32 for performance / code size reason.
14335 if (LHS.getValueType() == MVT::i8 ||
14336 LHS.getValueType() == MVT::i16)
14337 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
14339 // If the operand types disagree, extend the shift amount to match. Since
14340 // BT ignores high bits (like shifts) we can use anyextend.
14341 if (LHS.getValueType() != RHS.getValueType())
14342 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
14344 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
14345 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
14346 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14347 DAG.getConstant(Cond, dl, MVT::i8), BT);
14353 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
14355 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
14360 // SSE Condition code mapping:
14369 switch (SetCCOpcode) {
14370 default: llvm_unreachable("Unexpected SETCC condition");
14372 case ISD::SETEQ: SSECC = 0; break;
14374 case ISD::SETGT: Swap = true; // Fallthrough
14376 case ISD::SETOLT: SSECC = 1; break;
14378 case ISD::SETGE: Swap = true; // Fallthrough
14380 case ISD::SETOLE: SSECC = 2; break;
14381 case ISD::SETUO: SSECC = 3; break;
14383 case ISD::SETNE: SSECC = 4; break;
14384 case ISD::SETULE: Swap = true; // Fallthrough
14385 case ISD::SETUGE: SSECC = 5; break;
14386 case ISD::SETULT: Swap = true; // Fallthrough
14387 case ISD::SETUGT: SSECC = 6; break;
14388 case ISD::SETO: SSECC = 7; break;
14390 case ISD::SETONE: SSECC = 8; break;
14393 std::swap(Op0, Op1);
14398 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
14399 // ones, and then concatenate the result back.
14400 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
14401 MVT VT = Op.getSimpleValueType();
14403 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
14404 "Unsupported value type for operation");
14406 unsigned NumElems = VT.getVectorNumElements();
14408 SDValue CC = Op.getOperand(2);
14410 // Extract the LHS vectors
14411 SDValue LHS = Op.getOperand(0);
14412 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14413 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14415 // Extract the RHS vectors
14416 SDValue RHS = Op.getOperand(1);
14417 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
14418 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
14420 // Issue the operation on the smaller types and concatenate the result back
14421 MVT EltVT = VT.getVectorElementType();
14422 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14423 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
14424 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
14425 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
14428 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
14429 SDValue Op0 = Op.getOperand(0);
14430 SDValue Op1 = Op.getOperand(1);
14431 SDValue CC = Op.getOperand(2);
14432 MVT VT = Op.getSimpleValueType();
14435 assert(Op0.getSimpleValueType().getVectorElementType() == MVT::i1 &&
14436 "Unexpected type for boolean compare operation");
14437 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14438 SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
14439 DAG.getConstant(-1, dl, VT));
14440 SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
14441 DAG.getConstant(-1, dl, VT));
14442 switch (SetCCOpcode) {
14443 default: llvm_unreachable("Unexpected SETCC condition");
14445 // (x == y) -> ~(x ^ y)
14446 return DAG.getNode(ISD::XOR, dl, VT,
14447 DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
14448 DAG.getConstant(-1, dl, VT));
14450 // (x != y) -> (x ^ y)
14451 return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
14454 // (x > y) -> (x & ~y)
14455 return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
14458 // (x < y) -> (~x & y)
14459 return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
14462 // (x <= y) -> (~x | y)
14463 return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
14466 // (x >=y) -> (x | ~y)
14467 return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
14471 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
14472 const X86Subtarget *Subtarget) {
14473 SDValue Op0 = Op.getOperand(0);
14474 SDValue Op1 = Op.getOperand(1);
14475 SDValue CC = Op.getOperand(2);
14476 MVT VT = Op.getSimpleValueType();
14479 assert(Op0.getSimpleValueType().getVectorElementType().getSizeInBits() >= 8 &&
14480 Op.getSimpleValueType().getVectorElementType() == MVT::i1 &&
14481 "Cannot set masked compare for this operation");
14483 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14485 bool Unsigned = false;
14488 switch (SetCCOpcode) {
14489 default: llvm_unreachable("Unexpected SETCC condition");
14490 case ISD::SETNE: SSECC = 4; break;
14491 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
14492 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
14493 case ISD::SETLT: Swap = true; //fall-through
14494 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
14495 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
14496 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
14497 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
14498 case ISD::SETULE: Unsigned = true; //fall-through
14499 case ISD::SETLE: SSECC = 2; break;
14503 std::swap(Op0, Op1);
14505 return DAG.getNode(Opc, dl, VT, Op0, Op1);
14506 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
14507 return DAG.getNode(Opc, dl, VT, Op0, Op1,
14508 DAG.getConstant(SSECC, dl, MVT::i8));
14511 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
14512 /// operand \p Op1. If non-trivial (for example because it's not constant)
14513 /// return an empty value.
14514 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
14516 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
14520 MVT VT = Op1.getSimpleValueType();
14521 MVT EVT = VT.getVectorElementType();
14522 unsigned n = VT.getVectorNumElements();
14523 SmallVector<SDValue, 8> ULTOp1;
14525 for (unsigned i = 0; i < n; ++i) {
14526 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
14527 if (!Elt || Elt->isOpaque() || Elt->getSimpleValueType(0) != EVT)
14530 // Avoid underflow.
14531 APInt Val = Elt->getAPIntValue();
14535 ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
14538 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
14541 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
14542 SelectionDAG &DAG) {
14543 SDValue Op0 = Op.getOperand(0);
14544 SDValue Op1 = Op.getOperand(1);
14545 SDValue CC = Op.getOperand(2);
14546 MVT VT = Op.getSimpleValueType();
14547 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14548 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
14553 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
14554 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
14557 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
14558 unsigned Opc = X86ISD::CMPP;
14559 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
14560 assert(VT.getVectorNumElements() <= 16);
14561 Opc = X86ISD::CMPM;
14563 // In the two special cases we can't handle, emit two comparisons.
14566 unsigned CombineOpc;
14567 if (SetCCOpcode == ISD::SETUEQ) {
14568 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
14570 assert(SetCCOpcode == ISD::SETONE);
14571 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
14574 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14575 DAG.getConstant(CC0, dl, MVT::i8));
14576 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14577 DAG.getConstant(CC1, dl, MVT::i8));
14578 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
14580 // Handle all other FP comparisons here.
14581 return DAG.getNode(Opc, dl, VT, Op0, Op1,
14582 DAG.getConstant(SSECC, dl, MVT::i8));
14585 MVT VTOp0 = Op0.getSimpleValueType();
14586 assert(VTOp0 == Op1.getSimpleValueType() &&
14587 "Expected operands with same type!");
14588 assert(VT.getVectorNumElements() == VTOp0.getVectorNumElements() &&
14589 "Invalid number of packed elements for source and destination!");
14591 if (VT.is128BitVector() && VTOp0.is256BitVector()) {
14592 // On non-AVX512 targets, a vector of MVT::i1 is promoted by the type
14593 // legalizer to a wider vector type. In the case of 'vsetcc' nodes, the
14594 // legalizer firstly checks if the first operand in input to the setcc has
14595 // a legal type. If so, then it promotes the return type to that same type.
14596 // Otherwise, the return type is promoted to the 'next legal type' which,
14597 // for a vector of MVT::i1 is always a 128-bit integer vector type.
14599 // We reach this code only if the following two conditions are met:
14600 // 1. Both return type and operand type have been promoted to wider types
14601 // by the type legalizer.
14602 // 2. The original operand type has been promoted to a 256-bit vector.
14604 // Note that condition 2. only applies for AVX targets.
14605 SDValue NewOp = DAG.getSetCC(dl, VTOp0, Op0, Op1, SetCCOpcode);
14606 return DAG.getZExtOrTrunc(NewOp, dl, VT);
14609 // The non-AVX512 code below works under the assumption that source and
14610 // destination types are the same.
14611 assert((Subtarget->hasAVX512() || (VT == VTOp0)) &&
14612 "Value types for source and destination must be the same!");
14614 // Break 256-bit integer vector compare into smaller ones.
14615 if (VT.is256BitVector() && !Subtarget->hasInt256())
14616 return Lower256IntVSETCC(Op, DAG);
14618 MVT OpVT = Op1.getSimpleValueType();
14619 if (OpVT.getVectorElementType() == MVT::i1)
14620 return LowerBoolVSETCC_AVX512(Op, DAG);
14622 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
14623 if (Subtarget->hasAVX512()) {
14624 if (Op1.getSimpleValueType().is512BitVector() ||
14625 (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
14626 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
14627 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
14629 // In AVX-512 architecture setcc returns mask with i1 elements,
14630 // But there is no compare instruction for i8 and i16 elements in KNL.
14631 // We are not talking about 512-bit operands in this case, these
14632 // types are illegal.
14634 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
14635 OpVT.getVectorElementType().getSizeInBits() >= 8))
14636 return DAG.getNode(ISD::TRUNCATE, dl, VT,
14637 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
14640 // Lower using XOP integer comparisons.
14641 if ((VT == MVT::v16i8 || VT == MVT::v8i16 ||
14642 VT == MVT::v4i32 || VT == MVT::v2i64) && Subtarget->hasXOP()) {
14643 // Translate compare code to XOP PCOM compare mode.
14644 unsigned CmpMode = 0;
14645 switch (SetCCOpcode) {
14646 default: llvm_unreachable("Unexpected SETCC condition");
14648 case ISD::SETLT: CmpMode = 0x00; break;
14650 case ISD::SETLE: CmpMode = 0x01; break;
14652 case ISD::SETGT: CmpMode = 0x02; break;
14654 case ISD::SETGE: CmpMode = 0x03; break;
14655 case ISD::SETEQ: CmpMode = 0x04; break;
14656 case ISD::SETNE: CmpMode = 0x05; break;
14659 // Are we comparing unsigned or signed integers?
14660 unsigned Opc = ISD::isUnsignedIntSetCC(SetCCOpcode)
14661 ? X86ISD::VPCOMU : X86ISD::VPCOM;
14663 return DAG.getNode(Opc, dl, VT, Op0, Op1,
14664 DAG.getConstant(CmpMode, dl, MVT::i8));
14667 // We are handling one of the integer comparisons here. Since SSE only has
14668 // GT and EQ comparisons for integer, swapping operands and multiple
14669 // operations may be required for some comparisons.
14671 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
14672 bool Subus = false;
14674 switch (SetCCOpcode) {
14675 default: llvm_unreachable("Unexpected SETCC condition");
14676 case ISD::SETNE: Invert = true;
14677 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
14678 case ISD::SETLT: Swap = true;
14679 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
14680 case ISD::SETGE: Swap = true;
14681 case ISD::SETLE: Opc = X86ISD::PCMPGT;
14682 Invert = true; break;
14683 case ISD::SETULT: Swap = true;
14684 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
14685 FlipSigns = true; break;
14686 case ISD::SETUGE: Swap = true;
14687 case ISD::SETULE: Opc = X86ISD::PCMPGT;
14688 FlipSigns = true; Invert = true; break;
14691 // Special case: Use min/max operations for SETULE/SETUGE
14692 MVT VET = VT.getVectorElementType();
14694 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
14695 || (Subtarget->hasSSE2() && (VET == MVT::i8));
14698 switch (SetCCOpcode) {
14700 case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
14701 case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
14704 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
14707 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
14708 if (!MinMax && hasSubus) {
14709 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
14711 // t = psubus Op0, Op1
14712 // pcmpeq t, <0..0>
14713 switch (SetCCOpcode) {
14715 case ISD::SETULT: {
14716 // If the comparison is against a constant we can turn this into a
14717 // setule. With psubus, setule does not require a swap. This is
14718 // beneficial because the constant in the register is no longer
14719 // destructed as the destination so it can be hoisted out of a loop.
14720 // Only do this pre-AVX since vpcmp* is no longer destructive.
14721 if (Subtarget->hasAVX())
14723 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
14724 if (ULEOp1.getNode()) {
14726 Subus = true; Invert = false; Swap = false;
14730 // Psubus is better than flip-sign because it requires no inversion.
14731 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
14732 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
14736 Opc = X86ISD::SUBUS;
14742 std::swap(Op0, Op1);
14744 // Check that the operation in question is available (most are plain SSE2,
14745 // but PCMPGTQ and PCMPEQQ have different requirements).
14746 if (VT == MVT::v2i64) {
14747 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
14748 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
14750 // First cast everything to the right type.
14751 Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14752 Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14754 // Since SSE has no unsigned integer comparisons, we need to flip the sign
14755 // bits of the inputs before performing those operations. The lower
14756 // compare is always unsigned.
14759 SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
14761 SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
14762 SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
14763 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
14764 Sign, Zero, Sign, Zero);
14766 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
14767 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
14769 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
14770 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
14771 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
14773 // Create masks for only the low parts/high parts of the 64 bit integers.
14774 static const int MaskHi[] = { 1, 1, 3, 3 };
14775 static const int MaskLo[] = { 0, 0, 2, 2 };
14776 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
14777 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
14778 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
14780 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
14781 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
14784 Result = DAG.getNOT(dl, Result, MVT::v4i32);
14786 return DAG.getBitcast(VT, Result);
14789 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
14790 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
14791 // pcmpeqd + pshufd + pand.
14792 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
14794 // First cast everything to the right type.
14795 Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14796 Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14799 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
14801 // Make sure the lower and upper halves are both all-ones.
14802 static const int Mask[] = { 1, 0, 3, 2 };
14803 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
14804 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
14807 Result = DAG.getNOT(dl, Result, MVT::v4i32);
14809 return DAG.getBitcast(VT, Result);
14813 // Since SSE has no unsigned integer comparisons, we need to flip the sign
14814 // bits of the inputs before performing those operations.
14816 MVT EltVT = VT.getVectorElementType();
14817 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
14819 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
14820 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
14823 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
14825 // If the logical-not of the result is required, perform that now.
14827 Result = DAG.getNOT(dl, Result, VT);
14830 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
14833 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
14834 getZeroVector(VT, Subtarget, DAG, dl));
14839 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
14841 MVT VT = Op.getSimpleValueType();
14843 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
14845 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
14846 && "SetCC type must be 8-bit or 1-bit integer");
14847 SDValue Op0 = Op.getOperand(0);
14848 SDValue Op1 = Op.getOperand(1);
14850 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
14852 // Optimize to BT if possible.
14853 // Lower (X & (1 << N)) == 0 to BT(X, N).
14854 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
14855 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
14856 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
14857 isNullConstant(Op1) &&
14858 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14859 if (SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG)) {
14861 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
14866 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
14868 if ((isOneConstant(Op1) || isNullConstant(Op1)) &&
14869 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14871 // If the input is a setcc, then reuse the input setcc or use a new one with
14872 // the inverted condition.
14873 if (Op0.getOpcode() == X86ISD::SETCC) {
14874 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
14875 bool Invert = (CC == ISD::SETNE) ^ isNullConstant(Op1);
14879 CCode = X86::GetOppositeBranchCondition(CCode);
14880 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14881 DAG.getConstant(CCode, dl, MVT::i8),
14882 Op0.getOperand(1));
14884 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14888 if ((Op0.getValueType() == MVT::i1) && isOneConstant(Op1) &&
14889 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14891 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
14892 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
14895 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
14896 unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
14897 if (X86CC == X86::COND_INVALID)
14900 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
14901 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
14902 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14903 DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
14905 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14909 SDValue X86TargetLowering::LowerSETCCE(SDValue Op, SelectionDAG &DAG) const {
14910 SDValue LHS = Op.getOperand(0);
14911 SDValue RHS = Op.getOperand(1);
14912 SDValue Carry = Op.getOperand(2);
14913 SDValue Cond = Op.getOperand(3);
14916 assert(LHS.getSimpleValueType().isInteger() && "SETCCE is integer only.");
14917 X86::CondCode CC = TranslateIntegerX86CC(cast<CondCodeSDNode>(Cond)->get());
14919 assert(Carry.getOpcode() != ISD::CARRY_FALSE);
14920 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14921 SDValue Cmp = DAG.getNode(X86ISD::SBB, DL, VTs, LHS, RHS, Carry);
14922 return DAG.getNode(X86ISD::SETCC, DL, Op.getValueType(),
14923 DAG.getConstant(CC, DL, MVT::i8), Cmp.getValue(1));
14926 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
14927 static bool isX86LogicalCmp(SDValue Op) {
14928 unsigned Opc = Op.getNode()->getOpcode();
14929 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
14930 Opc == X86ISD::SAHF)
14932 if (Op.getResNo() == 1 &&
14933 (Opc == X86ISD::ADD ||
14934 Opc == X86ISD::SUB ||
14935 Opc == X86ISD::ADC ||
14936 Opc == X86ISD::SBB ||
14937 Opc == X86ISD::SMUL ||
14938 Opc == X86ISD::UMUL ||
14939 Opc == X86ISD::INC ||
14940 Opc == X86ISD::DEC ||
14941 Opc == X86ISD::OR ||
14942 Opc == X86ISD::XOR ||
14943 Opc == X86ISD::AND))
14946 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
14952 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
14953 if (V.getOpcode() != ISD::TRUNCATE)
14956 SDValue VOp0 = V.getOperand(0);
14957 unsigned InBits = VOp0.getValueSizeInBits();
14958 unsigned Bits = V.getValueSizeInBits();
14959 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
14962 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
14963 bool addTest = true;
14964 SDValue Cond = Op.getOperand(0);
14965 SDValue Op1 = Op.getOperand(1);
14966 SDValue Op2 = Op.getOperand(2);
14968 MVT VT = Op1.getSimpleValueType();
14971 // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
14972 // are available or VBLENDV if AVX is available.
14973 // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
14974 if (Cond.getOpcode() == ISD::SETCC &&
14975 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
14976 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
14977 VT == Cond.getOperand(0).getSimpleValueType() && Cond->hasOneUse()) {
14978 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
14979 int SSECC = translateX86FSETCC(
14980 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
14983 if (Subtarget->hasAVX512()) {
14984 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
14985 DAG.getConstant(SSECC, DL, MVT::i8));
14986 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
14989 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
14990 DAG.getConstant(SSECC, DL, MVT::i8));
14992 // If we have AVX, we can use a variable vector select (VBLENDV) instead
14993 // of 3 logic instructions for size savings and potentially speed.
14994 // Unfortunately, there is no scalar form of VBLENDV.
14996 // If either operand is a constant, don't try this. We can expect to
14997 // optimize away at least one of the logic instructions later in that
14998 // case, so that sequence would be faster than a variable blend.
15000 // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
15001 // uses XMM0 as the selection register. That may need just as many
15002 // instructions as the AND/ANDN/OR sequence due to register moves, so
15005 if (Subtarget->hasAVX() &&
15006 !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
15008 // Convert to vectors, do a VSELECT, and convert back to scalar.
15009 // All of the conversions should be optimized away.
15011 MVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
15012 SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
15013 SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
15014 SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
15016 MVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
15017 VCmp = DAG.getBitcast(VCmpVT, VCmp);
15019 SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
15021 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
15022 VSel, DAG.getIntPtrConstant(0, DL));
15024 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
15025 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
15026 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
15030 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
15032 if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
15033 Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
15034 else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
15035 Op1Scalar = Op1.getOperand(0);
15037 if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
15038 Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
15039 else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
15040 Op2Scalar = Op2.getOperand(0);
15041 if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
15042 SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
15043 Op1Scalar.getValueType(),
15044 Cond, Op1Scalar, Op2Scalar);
15045 if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
15046 return DAG.getBitcast(VT, newSelect);
15047 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
15048 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
15049 DAG.getIntPtrConstant(0, DL));
15053 if (VT == MVT::v4i1 || VT == MVT::v2i1) {
15054 SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
15055 Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
15056 DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
15057 Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
15058 DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
15059 SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
15061 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
15064 if (Cond.getOpcode() == ISD::SETCC) {
15065 SDValue NewCond = LowerSETCC(Cond, DAG);
15066 if (NewCond.getNode())
15070 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
15071 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
15072 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
15073 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
15074 if (Cond.getOpcode() == X86ISD::SETCC &&
15075 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
15076 isNullConstant(Cond.getOperand(1).getOperand(1))) {
15077 SDValue Cmp = Cond.getOperand(1);
15079 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
15081 if ((isAllOnesConstant(Op1) || isAllOnesConstant(Op2)) &&
15082 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
15083 SDValue Y = isAllOnesConstant(Op2) ? Op1 : Op2;
15085 SDValue CmpOp0 = Cmp.getOperand(0);
15086 // Apply further optimizations for special cases
15087 // (select (x != 0), -1, 0) -> neg & sbb
15088 // (select (x == 0), 0, -1) -> neg & sbb
15089 if (isNullConstant(Y) &&
15090 (isAllOnesConstant(Op1) == (CondCode == X86::COND_NE))) {
15091 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
15092 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
15093 DAG.getConstant(0, DL,
15094 CmpOp0.getValueType()),
15096 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15097 DAG.getConstant(X86::COND_B, DL, MVT::i8),
15098 SDValue(Neg.getNode(), 1));
15102 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
15103 CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
15104 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15106 SDValue Res = // Res = 0 or -1.
15107 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15108 DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
15110 if (isAllOnesConstant(Op1) != (CondCode == X86::COND_E))
15111 Res = DAG.getNOT(DL, Res, Res.getValueType());
15113 if (!isNullConstant(Op2))
15114 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
15119 // Look past (and (setcc_carry (cmp ...)), 1).
15120 if (Cond.getOpcode() == ISD::AND &&
15121 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY &&
15122 isOneConstant(Cond.getOperand(1)))
15123 Cond = Cond.getOperand(0);
15125 // If condition flag is set by a X86ISD::CMP, then use it as the condition
15126 // setting operand in place of the X86ISD::SETCC.
15127 unsigned CondOpcode = Cond.getOpcode();
15128 if (CondOpcode == X86ISD::SETCC ||
15129 CondOpcode == X86ISD::SETCC_CARRY) {
15130 CC = Cond.getOperand(0);
15132 SDValue Cmp = Cond.getOperand(1);
15133 unsigned Opc = Cmp.getOpcode();
15134 MVT VT = Op.getSimpleValueType();
15136 bool IllegalFPCMov = false;
15137 if (VT.isFloatingPoint() && !VT.isVector() &&
15138 !isScalarFPTypeInSSEReg(VT)) // FPStack?
15139 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
15141 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
15142 Opc == X86ISD::BT) { // FIXME
15146 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15147 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15148 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15149 Cond.getOperand(0).getValueType() != MVT::i8)) {
15150 SDValue LHS = Cond.getOperand(0);
15151 SDValue RHS = Cond.getOperand(1);
15152 unsigned X86Opcode;
15155 switch (CondOpcode) {
15156 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15157 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15158 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15159 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15160 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15161 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15162 default: llvm_unreachable("unexpected overflowing operator");
15164 if (CondOpcode == ISD::UMULO)
15165 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15168 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15170 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
15172 if (CondOpcode == ISD::UMULO)
15173 Cond = X86Op.getValue(2);
15175 Cond = X86Op.getValue(1);
15177 CC = DAG.getConstant(X86Cond, DL, MVT::i8);
15182 // Look past the truncate if the high bits are known zero.
15183 if (isTruncWithZeroHighBitsInput(Cond, DAG))
15184 Cond = Cond.getOperand(0);
15186 // We know the result of AND is compared against zero. Try to match
15188 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15189 if (SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG)) {
15190 CC = NewSetCC.getOperand(0);
15191 Cond = NewSetCC.getOperand(1);
15198 CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
15199 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
15202 // a < b ? -1 : 0 -> RES = ~setcc_carry
15203 // a < b ? 0 : -1 -> RES = setcc_carry
15204 // a >= b ? -1 : 0 -> RES = setcc_carry
15205 // a >= b ? 0 : -1 -> RES = ~setcc_carry
15206 if (Cond.getOpcode() == X86ISD::SUB) {
15207 Cond = ConvertCmpIfNecessary(Cond, DAG);
15208 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
15210 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
15211 (isAllOnesConstant(Op1) || isAllOnesConstant(Op2)) &&
15212 (isNullConstant(Op1) || isNullConstant(Op2))) {
15213 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
15214 DAG.getConstant(X86::COND_B, DL, MVT::i8),
15216 if (isAllOnesConstant(Op1) != (CondCode == X86::COND_B))
15217 return DAG.getNOT(DL, Res, Res.getValueType());
15222 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
15223 // widen the cmov and push the truncate through. This avoids introducing a new
15224 // branch during isel and doesn't add any extensions.
15225 if (Op.getValueType() == MVT::i8 &&
15226 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
15227 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
15228 if (T1.getValueType() == T2.getValueType() &&
15229 // Blacklist CopyFromReg to avoid partial register stalls.
15230 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
15231 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
15232 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
15233 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
15237 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
15238 // condition is true.
15239 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
15240 SDValue Ops[] = { Op2, Op1, CC, Cond };
15241 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
15244 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
15245 const X86Subtarget *Subtarget,
15246 SelectionDAG &DAG) {
15247 MVT VT = Op->getSimpleValueType(0);
15248 SDValue In = Op->getOperand(0);
15249 MVT InVT = In.getSimpleValueType();
15250 MVT VTElt = VT.getVectorElementType();
15251 MVT InVTElt = InVT.getVectorElementType();
15255 if ((InVTElt == MVT::i1) &&
15256 (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
15257 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
15259 ((Subtarget->hasBWI() && VT.is512BitVector() &&
15260 VTElt.getSizeInBits() <= 16)) ||
15262 ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
15263 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
15265 ((Subtarget->hasDQI() && VT.is512BitVector() &&
15266 VTElt.getSizeInBits() >= 32))))
15267 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15269 unsigned int NumElts = VT.getVectorNumElements();
15271 if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
15274 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
15275 if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
15276 return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
15277 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15280 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
15281 MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
15283 DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
15286 DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
15288 SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
15289 if (VT.is512BitVector())
15291 return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
15294 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
15295 const X86Subtarget *Subtarget,
15296 SelectionDAG &DAG) {
15297 SDValue In = Op->getOperand(0);
15298 MVT VT = Op->getSimpleValueType(0);
15299 MVT InVT = In.getSimpleValueType();
15300 assert(VT.getSizeInBits() == InVT.getSizeInBits());
15302 MVT InSVT = InVT.getVectorElementType();
15303 assert(VT.getVectorElementType().getSizeInBits() > InSVT.getSizeInBits());
15305 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
15307 if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
15312 // SSE41 targets can use the pmovsx* instructions directly.
15313 if (Subtarget->hasSSE41())
15314 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15316 // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
15320 // As SRAI is only available on i16/i32 types, we expand only up to i32
15321 // and handle i64 separately.
15322 while (CurrVT != VT && CurrVT.getVectorElementType() != MVT::i32) {
15323 Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
15324 MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
15325 CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
15326 Curr = DAG.getBitcast(CurrVT, Curr);
15329 SDValue SignExt = Curr;
15330 if (CurrVT != InVT) {
15331 unsigned SignExtShift =
15332 CurrVT.getVectorElementType().getSizeInBits() - InSVT.getSizeInBits();
15333 SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
15334 DAG.getConstant(SignExtShift, dl, MVT::i8));
15340 if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
15341 SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
15342 DAG.getConstant(31, dl, MVT::i8));
15343 SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
15344 return DAG.getBitcast(VT, Ext);
15350 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
15351 SelectionDAG &DAG) {
15352 MVT VT = Op->getSimpleValueType(0);
15353 SDValue In = Op->getOperand(0);
15354 MVT InVT = In.getSimpleValueType();
15357 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
15358 return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
15360 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
15361 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
15362 (VT != MVT::v16i16 || InVT != MVT::v16i8))
15365 if (Subtarget->hasInt256())
15366 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15368 // Optimize vectors in AVX mode
15369 // Sign extend v8i16 to v8i32 and
15372 // Divide input vector into two parts
15373 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15374 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15375 // concat the vectors to original VT
15377 unsigned NumElems = InVT.getVectorNumElements();
15378 SDValue Undef = DAG.getUNDEF(InVT);
15380 SmallVector<int,8> ShufMask1(NumElems, -1);
15381 for (unsigned i = 0; i != NumElems/2; ++i)
15384 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
15386 SmallVector<int,8> ShufMask2(NumElems, -1);
15387 for (unsigned i = 0; i != NumElems/2; ++i)
15388 ShufMask2[i] = i + NumElems/2;
15390 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
15392 MVT HalfVT = MVT::getVectorVT(VT.getVectorElementType(),
15393 VT.getVectorNumElements()/2);
15395 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
15396 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
15398 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15401 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
15402 // may emit an illegal shuffle but the expansion is still better than scalar
15403 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
15404 // we'll emit a shuffle and a arithmetic shift.
15405 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
15406 // TODO: It is possible to support ZExt by zeroing the undef values during
15407 // the shuffle phase or after the shuffle.
15408 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
15409 SelectionDAG &DAG) {
15410 MVT RegVT = Op.getSimpleValueType();
15411 assert(RegVT.isVector() && "We only custom lower vector sext loads.");
15412 assert(RegVT.isInteger() &&
15413 "We only custom lower integer vector sext loads.");
15415 // Nothing useful we can do without SSE2 shuffles.
15416 assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
15418 LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
15420 EVT MemVT = Ld->getMemoryVT();
15421 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15422 unsigned RegSz = RegVT.getSizeInBits();
15424 ISD::LoadExtType Ext = Ld->getExtensionType();
15426 assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
15427 && "Only anyext and sext are currently implemented.");
15428 assert(MemVT != RegVT && "Cannot extend to the same type");
15429 assert(MemVT.isVector() && "Must load a vector from memory");
15431 unsigned NumElems = RegVT.getVectorNumElements();
15432 unsigned MemSz = MemVT.getSizeInBits();
15433 assert(RegSz > MemSz && "Register size must be greater than the mem size");
15435 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
15436 // The only way in which we have a legal 256-bit vector result but not the
15437 // integer 256-bit operations needed to directly lower a sextload is if we
15438 // have AVX1 but not AVX2. In that case, we can always emit a sextload to
15439 // a 128-bit vector and a normal sign_extend to 256-bits that should get
15440 // correctly legalized. We do this late to allow the canonical form of
15441 // sextload to persist throughout the rest of the DAG combiner -- it wants
15442 // to fold together any extensions it can, and so will fuse a sign_extend
15443 // of an sextload into a sextload targeting a wider value.
15445 if (MemSz == 128) {
15446 // Just switch this to a normal load.
15447 assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
15448 "it must be a legal 128-bit vector "
15450 Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
15451 Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
15452 Ld->isInvariant(), Ld->getAlignment());
15454 assert(MemSz < 128 &&
15455 "Can't extend a type wider than 128 bits to a 256 bit vector!");
15456 // Do an sext load to a 128-bit vector type. We want to use the same
15457 // number of elements, but elements half as wide. This will end up being
15458 // recursively lowered by this routine, but will succeed as we definitely
15459 // have all the necessary features if we're using AVX1.
15461 EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
15462 EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
15464 DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
15465 Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
15466 Ld->isNonTemporal(), Ld->isInvariant(),
15467 Ld->getAlignment());
15470 // Replace chain users with the new chain.
15471 assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
15472 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
15474 // Finally, do a normal sign-extend to the desired register.
15475 return DAG.getSExtOrTrunc(Load, dl, RegVT);
15478 // All sizes must be a power of two.
15479 assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
15480 "Non-power-of-two elements are not custom lowered!");
15482 // Attempt to load the original value using scalar loads.
15483 // Find the largest scalar type that divides the total loaded size.
15484 MVT SclrLoadTy = MVT::i8;
15485 for (MVT Tp : MVT::integer_valuetypes()) {
15486 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15491 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15492 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15494 SclrLoadTy = MVT::f64;
15496 // Calculate the number of scalar loads that we need to perform
15497 // in order to load our vector from memory.
15498 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15500 assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
15501 "Can only lower sext loads with a single scalar load!");
15503 unsigned loadRegZize = RegSz;
15504 if (Ext == ISD::SEXTLOAD && RegSz >= 256)
15507 // Represent our vector as a sequence of elements which are the
15508 // largest scalar that we can load.
15509 EVT LoadUnitVecVT = EVT::getVectorVT(
15510 *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
15512 // Represent the data using the same element type that is stored in
15513 // memory. In practice, we ''widen'' MemVT.
15515 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15516 loadRegZize / MemVT.getScalarSizeInBits());
15518 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15519 "Invalid vector type");
15521 // We can't shuffle using an illegal type.
15522 assert(TLI.isTypeLegal(WideVecVT) &&
15523 "We only lower types that form legal widened vector types");
15525 SmallVector<SDValue, 8> Chains;
15526 SDValue Ptr = Ld->getBasePtr();
15527 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
15528 TLI.getPointerTy(DAG.getDataLayout()));
15529 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15531 for (unsigned i = 0; i < NumLoads; ++i) {
15532 // Perform a single load.
15533 SDValue ScalarLoad =
15534 DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
15535 Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
15536 Ld->getAlignment());
15537 Chains.push_back(ScalarLoad.getValue(1));
15538 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15539 // another round of DAGCombining.
15541 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15543 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15544 ScalarLoad, DAG.getIntPtrConstant(i, dl));
15546 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15549 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
15551 // Bitcast the loaded value to a vector of the original element type, in
15552 // the size of the target vector type.
15553 SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
15554 unsigned SizeRatio = RegSz / MemSz;
15556 if (Ext == ISD::SEXTLOAD) {
15557 // If we have SSE4.1, we can directly emit a VSEXT node.
15558 if (Subtarget->hasSSE41()) {
15559 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
15560 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15564 // Otherwise we'll use SIGN_EXTEND_VECTOR_INREG to sign extend the lowest
15566 assert(TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND_VECTOR_INREG, RegVT) &&
15567 "We can't implement a sext load without SIGN_EXTEND_VECTOR_INREG!");
15569 SDValue Shuff = DAG.getSignExtendVectorInReg(SlicedVec, dl, RegVT);
15570 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15574 // Redistribute the loaded elements into the different locations.
15575 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
15576 for (unsigned i = 0; i != NumElems; ++i)
15577 ShuffleVec[i * SizeRatio] = i;
15579 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15580 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
15582 // Bitcast to the requested type.
15583 Shuff = DAG.getBitcast(RegVT, Shuff);
15584 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15588 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
15589 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
15590 // from the AND / OR.
15591 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
15592 Opc = Op.getOpcode();
15593 if (Opc != ISD::OR && Opc != ISD::AND)
15595 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15596 Op.getOperand(0).hasOneUse() &&
15597 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
15598 Op.getOperand(1).hasOneUse());
15601 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
15602 // 1 and that the SETCC node has a single use.
15603 static bool isXor1OfSetCC(SDValue Op) {
15604 if (Op.getOpcode() != ISD::XOR)
15606 if (isOneConstant(Op.getOperand(1)))
15607 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15608 Op.getOperand(0).hasOneUse();
15612 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
15613 bool addTest = true;
15614 SDValue Chain = Op.getOperand(0);
15615 SDValue Cond = Op.getOperand(1);
15616 SDValue Dest = Op.getOperand(2);
15619 bool Inverted = false;
15621 if (Cond.getOpcode() == ISD::SETCC) {
15622 // Check for setcc([su]{add,sub,mul}o == 0).
15623 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
15624 isNullConstant(Cond.getOperand(1)) &&
15625 Cond.getOperand(0).getResNo() == 1 &&
15626 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
15627 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
15628 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
15629 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
15630 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
15631 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
15633 Cond = Cond.getOperand(0);
15635 SDValue NewCond = LowerSETCC(Cond, DAG);
15636 if (NewCond.getNode())
15641 // FIXME: LowerXALUO doesn't handle these!!
15642 else if (Cond.getOpcode() == X86ISD::ADD ||
15643 Cond.getOpcode() == X86ISD::SUB ||
15644 Cond.getOpcode() == X86ISD::SMUL ||
15645 Cond.getOpcode() == X86ISD::UMUL)
15646 Cond = LowerXALUO(Cond, DAG);
15649 // Look pass (and (setcc_carry (cmp ...)), 1).
15650 if (Cond.getOpcode() == ISD::AND &&
15651 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY &&
15652 isOneConstant(Cond.getOperand(1)))
15653 Cond = Cond.getOperand(0);
15655 // If condition flag is set by a X86ISD::CMP, then use it as the condition
15656 // setting operand in place of the X86ISD::SETCC.
15657 unsigned CondOpcode = Cond.getOpcode();
15658 if (CondOpcode == X86ISD::SETCC ||
15659 CondOpcode == X86ISD::SETCC_CARRY) {
15660 CC = Cond.getOperand(0);
15662 SDValue Cmp = Cond.getOperand(1);
15663 unsigned Opc = Cmp.getOpcode();
15664 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
15665 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
15669 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
15673 // These can only come from an arithmetic instruction with overflow,
15674 // e.g. SADDO, UADDO.
15675 Cond = Cond.getNode()->getOperand(1);
15681 CondOpcode = Cond.getOpcode();
15682 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15683 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15684 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15685 Cond.getOperand(0).getValueType() != MVT::i8)) {
15686 SDValue LHS = Cond.getOperand(0);
15687 SDValue RHS = Cond.getOperand(1);
15688 unsigned X86Opcode;
15691 // Keep this in sync with LowerXALUO, otherwise we might create redundant
15692 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
15694 switch (CondOpcode) {
15695 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15697 if (isOneConstant(RHS)) {
15698 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
15701 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15702 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15704 if (isOneConstant(RHS)) {
15705 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
15708 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15709 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15710 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15711 default: llvm_unreachable("unexpected overflowing operator");
15714 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
15715 if (CondOpcode == ISD::UMULO)
15716 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15719 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15721 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
15723 if (CondOpcode == ISD::UMULO)
15724 Cond = X86Op.getValue(2);
15726 Cond = X86Op.getValue(1);
15728 CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15732 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
15733 SDValue Cmp = Cond.getOperand(0).getOperand(1);
15734 if (CondOpc == ISD::OR) {
15735 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
15736 // two branches instead of an explicit OR instruction with a
15738 if (Cmp == Cond.getOperand(1).getOperand(1) &&
15739 isX86LogicalCmp(Cmp)) {
15740 CC = Cond.getOperand(0).getOperand(0);
15741 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15742 Chain, Dest, CC, Cmp);
15743 CC = Cond.getOperand(1).getOperand(0);
15747 } else { // ISD::AND
15748 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
15749 // two branches instead of an explicit AND instruction with a
15750 // separate test. However, we only do this if this block doesn't
15751 // have a fall-through edge, because this requires an explicit
15752 // jmp when the condition is false.
15753 if (Cmp == Cond.getOperand(1).getOperand(1) &&
15754 isX86LogicalCmp(Cmp) &&
15755 Op.getNode()->hasOneUse()) {
15756 X86::CondCode CCode =
15757 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15758 CCode = X86::GetOppositeBranchCondition(CCode);
15759 CC = DAG.getConstant(CCode, dl, MVT::i8);
15760 SDNode *User = *Op.getNode()->use_begin();
15761 // Look for an unconditional branch following this conditional branch.
15762 // We need this because we need to reverse the successors in order
15763 // to implement FCMP_OEQ.
15764 if (User->getOpcode() == ISD::BR) {
15765 SDValue FalseBB = User->getOperand(1);
15767 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15768 assert(NewBR == User);
15772 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15773 Chain, Dest, CC, Cmp);
15774 X86::CondCode CCode =
15775 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
15776 CCode = X86::GetOppositeBranchCondition(CCode);
15777 CC = DAG.getConstant(CCode, dl, MVT::i8);
15783 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
15784 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
15785 // It should be transformed during dag combiner except when the condition
15786 // is set by a arithmetics with overflow node.
15787 X86::CondCode CCode =
15788 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15789 CCode = X86::GetOppositeBranchCondition(CCode);
15790 CC = DAG.getConstant(CCode, dl, MVT::i8);
15791 Cond = Cond.getOperand(0).getOperand(1);
15793 } else if (Cond.getOpcode() == ISD::SETCC &&
15794 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
15795 // For FCMP_OEQ, we can emit
15796 // two branches instead of an explicit AND instruction with a
15797 // separate test. However, we only do this if this block doesn't
15798 // have a fall-through edge, because this requires an explicit
15799 // jmp when the condition is false.
15800 if (Op.getNode()->hasOneUse()) {
15801 SDNode *User = *Op.getNode()->use_begin();
15802 // Look for an unconditional branch following this conditional branch.
15803 // We need this because we need to reverse the successors in order
15804 // to implement FCMP_OEQ.
15805 if (User->getOpcode() == ISD::BR) {
15806 SDValue FalseBB = User->getOperand(1);
15808 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15809 assert(NewBR == User);
15813 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15814 Cond.getOperand(0), Cond.getOperand(1));
15815 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15816 CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15817 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15818 Chain, Dest, CC, Cmp);
15819 CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
15824 } else if (Cond.getOpcode() == ISD::SETCC &&
15825 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
15826 // For FCMP_UNE, we can emit
15827 // two branches instead of an explicit AND instruction with a
15828 // separate test. However, we only do this if this block doesn't
15829 // have a fall-through edge, because this requires an explicit
15830 // jmp when the condition is false.
15831 if (Op.getNode()->hasOneUse()) {
15832 SDNode *User = *Op.getNode()->use_begin();
15833 // Look for an unconditional branch following this conditional branch.
15834 // We need this because we need to reverse the successors in order
15835 // to implement FCMP_UNE.
15836 if (User->getOpcode() == ISD::BR) {
15837 SDValue FalseBB = User->getOperand(1);
15839 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15840 assert(NewBR == User);
15843 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15844 Cond.getOperand(0), Cond.getOperand(1));
15845 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15846 CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15847 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15848 Chain, Dest, CC, Cmp);
15849 CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
15859 // Look pass the truncate if the high bits are known zero.
15860 if (isTruncWithZeroHighBitsInput(Cond, DAG))
15861 Cond = Cond.getOperand(0);
15863 // We know the result of AND is compared against zero. Try to match
15865 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15866 if (SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG)) {
15867 CC = NewSetCC.getOperand(0);
15868 Cond = NewSetCC.getOperand(1);
15875 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
15876 CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15877 Cond = EmitTest(Cond, X86Cond, dl, DAG);
15879 Cond = ConvertCmpIfNecessary(Cond, DAG);
15880 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15881 Chain, Dest, CC, Cond);
15884 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
15885 // Calls to _alloca are needed to probe the stack when allocating more than 4k
15886 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
15887 // that the guard pages used by the OS virtual memory manager are allocated in
15888 // correct sequence.
15890 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
15891 SelectionDAG &DAG) const {
15892 MachineFunction &MF = DAG.getMachineFunction();
15893 bool SplitStack = MF.shouldSplitStack();
15894 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
15899 SDNode *Node = Op.getNode();
15900 SDValue Chain = Op.getOperand(0);
15901 SDValue Size = Op.getOperand(1);
15902 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
15903 EVT VT = Node->getValueType(0);
15905 // Chain the dynamic stack allocation so that it doesn't modify the stack
15906 // pointer when other instructions are using the stack.
15907 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true), dl);
15909 bool Is64Bit = Subtarget->is64Bit();
15910 MVT SPTy = getPointerTy(DAG.getDataLayout());
15914 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15915 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
15916 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
15917 " not tell us which reg is the stack pointer!");
15918 EVT VT = Node->getValueType(0);
15919 SDValue Tmp3 = Node->getOperand(2);
15921 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
15922 Chain = SP.getValue(1);
15923 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
15924 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15925 unsigned StackAlign = TFI.getStackAlignment();
15926 Result = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
15927 if (Align > StackAlign)
15928 Result = DAG.getNode(ISD::AND, dl, VT, Result,
15929 DAG.getConstant(-(uint64_t)Align, dl, VT));
15930 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Result); // Output chain
15931 } else if (SplitStack) {
15932 MachineRegisterInfo &MRI = MF.getRegInfo();
15935 // The 64 bit implementation of segmented stacks needs to clobber both r10
15936 // r11. This makes it impossible to use it along with nested parameters.
15937 const Function *F = MF.getFunction();
15939 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
15941 if (I->hasNestAttr())
15942 report_fatal_error("Cannot use segmented stacks with functions that "
15943 "have nested arguments.");
15946 const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
15947 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
15948 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
15949 Result = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
15950 DAG.getRegister(Vreg, SPTy));
15953 const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
15955 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
15956 Flag = Chain.getValue(1);
15957 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
15959 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
15961 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15962 unsigned SPReg = RegInfo->getStackRegister();
15963 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
15964 Chain = SP.getValue(1);
15967 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
15968 DAG.getConstant(-(uint64_t)Align, dl, VT));
15969 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
15975 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
15976 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
15978 SDValue Ops[2] = {Result, Chain};
15979 return DAG.getMergeValues(Ops, dl);
15982 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
15983 MachineFunction &MF = DAG.getMachineFunction();
15984 auto PtrVT = getPointerTy(MF.getDataLayout());
15985 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15987 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15990 if (!Subtarget->is64Bit() ||
15991 Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv())) {
15992 // vastart just stores the address of the VarArgsFrameIndex slot into the
15993 // memory location argument.
15994 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15995 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
15996 MachinePointerInfo(SV), false, false, 0);
16000 // gp_offset (0 - 6 * 8)
16001 // fp_offset (48 - 48 + 8 * 16)
16002 // overflow_arg_area (point to parameters coming in memory).
16004 SmallVector<SDValue, 8> MemOps;
16005 SDValue FIN = Op.getOperand(1);
16007 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
16008 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
16010 FIN, MachinePointerInfo(SV), false, false, 0);
16011 MemOps.push_back(Store);
16014 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
16015 Store = DAG.getStore(Op.getOperand(0), DL,
16016 DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
16018 FIN, MachinePointerInfo(SV, 4), false, false, 0);
16019 MemOps.push_back(Store);
16021 // Store ptr to overflow_arg_area
16022 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
16023 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
16024 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
16025 MachinePointerInfo(SV, 8),
16027 MemOps.push_back(Store);
16029 // Store ptr to reg_save_area.
16030 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(
16031 Subtarget->isTarget64BitLP64() ? 8 : 4, DL));
16032 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
16033 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN, MachinePointerInfo(
16034 SV, Subtarget->isTarget64BitLP64() ? 16 : 12), false, false, 0);
16035 MemOps.push_back(Store);
16036 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
16039 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
16040 assert(Subtarget->is64Bit() &&
16041 "LowerVAARG only handles 64-bit va_arg!");
16042 assert(Op.getNode()->getNumOperands() == 4);
16044 MachineFunction &MF = DAG.getMachineFunction();
16045 if (Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv()))
16046 // The Win64 ABI uses char* instead of a structure.
16047 return DAG.expandVAArg(Op.getNode());
16049 SDValue Chain = Op.getOperand(0);
16050 SDValue SrcPtr = Op.getOperand(1);
16051 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
16052 unsigned Align = Op.getConstantOperandVal(3);
16055 EVT ArgVT = Op.getNode()->getValueType(0);
16056 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16057 uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
16060 // Decide which area this value should be read from.
16061 // TODO: Implement the AMD64 ABI in its entirety. This simple
16062 // selection mechanism works only for the basic types.
16063 if (ArgVT == MVT::f80) {
16064 llvm_unreachable("va_arg for f80 not yet implemented");
16065 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
16066 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
16067 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
16068 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
16070 llvm_unreachable("Unhandled argument type in LowerVAARG");
16073 if (ArgMode == 2) {
16074 // Sanity Check: Make sure using fp_offset makes sense.
16075 assert(!Subtarget->useSoftFloat() &&
16076 !(MF.getFunction()->hasFnAttribute(Attribute::NoImplicitFloat)) &&
16077 Subtarget->hasSSE1());
16080 // Insert VAARG_64 node into the DAG
16081 // VAARG_64 returns two values: Variable Argument Address, Chain
16082 SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
16083 DAG.getConstant(ArgMode, dl, MVT::i8),
16084 DAG.getConstant(Align, dl, MVT::i32)};
16085 SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
16086 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
16087 VTs, InstOps, MVT::i64,
16088 MachinePointerInfo(SV),
16090 /*Volatile=*/false,
16092 /*WriteMem=*/true);
16093 Chain = VAARG.getValue(1);
16095 // Load the next argument and return it
16096 return DAG.getLoad(ArgVT, dl,
16099 MachinePointerInfo(),
16100 false, false, false, 0);
16103 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
16104 SelectionDAG &DAG) {
16105 // X86-64 va_list is a struct { i32, i32, i8*, i8* }, except on Windows,
16106 // where a va_list is still an i8*.
16107 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
16108 if (Subtarget->isCallingConvWin64(
16109 DAG.getMachineFunction().getFunction()->getCallingConv()))
16110 // Probably a Win64 va_copy.
16111 return DAG.expandVACopy(Op.getNode());
16113 SDValue Chain = Op.getOperand(0);
16114 SDValue DstPtr = Op.getOperand(1);
16115 SDValue SrcPtr = Op.getOperand(2);
16116 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
16117 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16120 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
16121 DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
16123 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
16126 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
16127 // amount is a constant. Takes immediate version of shift as input.
16128 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
16129 SDValue SrcOp, uint64_t ShiftAmt,
16130 SelectionDAG &DAG) {
16131 MVT ElementType = VT.getVectorElementType();
16133 // Fold this packed shift into its first operand if ShiftAmt is 0.
16137 // Check for ShiftAmt >= element width
16138 if (ShiftAmt >= ElementType.getSizeInBits()) {
16139 if (Opc == X86ISD::VSRAI)
16140 ShiftAmt = ElementType.getSizeInBits() - 1;
16142 return DAG.getConstant(0, dl, VT);
16145 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
16146 && "Unknown target vector shift-by-constant node");
16148 // Fold this packed vector shift into a build vector if SrcOp is a
16149 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
16150 if (VT == SrcOp.getSimpleValueType() &&
16151 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
16152 SmallVector<SDValue, 8> Elts;
16153 unsigned NumElts = SrcOp->getNumOperands();
16154 ConstantSDNode *ND;
16157 default: llvm_unreachable(nullptr);
16158 case X86ISD::VSHLI:
16159 for (unsigned i=0; i!=NumElts; ++i) {
16160 SDValue CurrentOp = SrcOp->getOperand(i);
16161 if (CurrentOp->getOpcode() == ISD::UNDEF) {
16162 Elts.push_back(CurrentOp);
16165 ND = cast<ConstantSDNode>(CurrentOp);
16166 const APInt &C = ND->getAPIntValue();
16167 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
16170 case X86ISD::VSRLI:
16171 for (unsigned i=0; i!=NumElts; ++i) {
16172 SDValue CurrentOp = SrcOp->getOperand(i);
16173 if (CurrentOp->getOpcode() == ISD::UNDEF) {
16174 Elts.push_back(CurrentOp);
16177 ND = cast<ConstantSDNode>(CurrentOp);
16178 const APInt &C = ND->getAPIntValue();
16179 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
16182 case X86ISD::VSRAI:
16183 for (unsigned i=0; i!=NumElts; ++i) {
16184 SDValue CurrentOp = SrcOp->getOperand(i);
16185 if (CurrentOp->getOpcode() == ISD::UNDEF) {
16186 Elts.push_back(CurrentOp);
16189 ND = cast<ConstantSDNode>(CurrentOp);
16190 const APInt &C = ND->getAPIntValue();
16191 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
16196 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16199 return DAG.getNode(Opc, dl, VT, SrcOp,
16200 DAG.getConstant(ShiftAmt, dl, MVT::i8));
16203 // getTargetVShiftNode - Handle vector element shifts where the shift amount
16204 // may or may not be a constant. Takes immediate version of shift as input.
16205 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
16206 SDValue SrcOp, SDValue ShAmt,
16207 SelectionDAG &DAG) {
16208 MVT SVT = ShAmt.getSimpleValueType();
16209 assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
16211 // Catch shift-by-constant.
16212 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
16213 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
16214 CShAmt->getZExtValue(), DAG);
16216 // Change opcode to non-immediate version
16218 default: llvm_unreachable("Unknown target vector shift node");
16219 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
16220 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
16221 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
16224 const X86Subtarget &Subtarget =
16225 static_cast<const X86Subtarget &>(DAG.getSubtarget());
16226 if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
16227 ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
16228 // Let the shuffle legalizer expand this shift amount node.
16229 SDValue Op0 = ShAmt.getOperand(0);
16230 Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
16231 ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
16233 // Need to build a vector containing shift amount.
16234 // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
16235 SmallVector<SDValue, 4> ShOps;
16236 ShOps.push_back(ShAmt);
16237 if (SVT == MVT::i32) {
16238 ShOps.push_back(DAG.getConstant(0, dl, SVT));
16239 ShOps.push_back(DAG.getUNDEF(SVT));
16241 ShOps.push_back(DAG.getUNDEF(SVT));
16243 MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
16244 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
16247 // The return type has to be a 128-bit type with the same element
16248 // type as the input type.
16249 MVT EltVT = VT.getVectorElementType();
16250 MVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
16252 ShAmt = DAG.getBitcast(ShVT, ShAmt);
16253 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
16256 /// \brief Return Mask with the necessary casting or extending
16257 /// for \p Mask according to \p MaskVT when lowering masking intrinsics
16258 static SDValue getMaskNode(SDValue Mask, MVT MaskVT,
16259 const X86Subtarget *Subtarget,
16260 SelectionDAG &DAG, SDLoc dl) {
16262 if (MaskVT.bitsGT(Mask.getSimpleValueType())) {
16263 // Mask should be extended
16264 Mask = DAG.getNode(ISD::ANY_EXTEND, dl,
16265 MVT::getIntegerVT(MaskVT.getSizeInBits()), Mask);
16268 if (Mask.getSimpleValueType() == MVT::i64 && Subtarget->is32Bit()) {
16269 if (MaskVT == MVT::v64i1) {
16270 assert(Subtarget->hasBWI() && "Expected AVX512BW target!");
16271 // In case 32bit mode, bitcast i64 is illegal, extend/split it.
16273 Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Mask,
16274 DAG.getConstant(0, dl, MVT::i32));
16275 Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Mask,
16276 DAG.getConstant(1, dl, MVT::i32));
16278 Lo = DAG.getBitcast(MVT::v32i1, Lo);
16279 Hi = DAG.getBitcast(MVT::v32i1, Hi);
16281 return DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, Lo, Hi);
16283 // MaskVT require < 64bit. Truncate mask (should succeed in any case),
16285 MVT TruncVT = MVT::getIntegerVT(MaskVT.getSizeInBits());
16286 return DAG.getBitcast(MaskVT,
16287 DAG.getNode(ISD::TRUNCATE, dl, TruncVT, Mask));
16291 MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16292 Mask.getSimpleValueType().getSizeInBits());
16293 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16294 // are extracted by EXTRACT_SUBVECTOR.
16295 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16296 DAG.getBitcast(BitcastVT, Mask),
16297 DAG.getIntPtrConstant(0, dl));
16301 /// \brief Return (and \p Op, \p Mask) for compare instructions or
16302 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
16303 /// necessary casting or extending for \p Mask when lowering masking intrinsics
16304 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
16305 SDValue PreservedSrc,
16306 const X86Subtarget *Subtarget,
16307 SelectionDAG &DAG) {
16308 MVT VT = Op.getSimpleValueType();
16309 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16310 unsigned OpcodeSelect = ISD::VSELECT;
16313 if (isAllOnesConstant(Mask))
16316 SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
16318 switch (Op.getOpcode()) {
16320 case X86ISD::PCMPEQM:
16321 case X86ISD::PCMPGTM:
16323 case X86ISD::CMPMU:
16324 return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
16325 case X86ISD::VFPCLASS:
16326 case X86ISD::VFPCLASSS:
16327 return DAG.getNode(ISD::OR, dl, VT, Op, VMask);
16328 case X86ISD::VTRUNC:
16329 case X86ISD::VTRUNCS:
16330 case X86ISD::VTRUNCUS:
16331 // We can't use ISD::VSELECT here because it is not always "Legal"
16332 // for the destination type. For example vpmovqb require only AVX512
16333 // and vselect that can operate on byte element type require BWI
16334 OpcodeSelect = X86ISD::SELECT;
16337 if (PreservedSrc.getOpcode() == ISD::UNDEF)
16338 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
16339 return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
16342 /// \brief Creates an SDNode for a predicated scalar operation.
16343 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
16344 /// The mask is coming as MVT::i8 and it should be truncated
16345 /// to MVT::i1 while lowering masking intrinsics.
16346 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
16347 /// "X86select" instead of "vselect". We just can't create the "vselect" node
16348 /// for a scalar instruction.
16349 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
16350 SDValue PreservedSrc,
16351 const X86Subtarget *Subtarget,
16352 SelectionDAG &DAG) {
16353 if (isAllOnesConstant(Mask))
16356 MVT VT = Op.getSimpleValueType();
16358 // The mask should be of type MVT::i1
16359 SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
16361 if (Op.getOpcode() == X86ISD::FSETCC)
16362 return DAG.getNode(ISD::AND, dl, VT, Op, IMask);
16363 if (Op.getOpcode() == X86ISD::VFPCLASS ||
16364 Op.getOpcode() == X86ISD::VFPCLASSS)
16365 return DAG.getNode(ISD::OR, dl, VT, Op, IMask);
16367 if (PreservedSrc.getOpcode() == ISD::UNDEF)
16368 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
16369 return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
16372 static int getSEHRegistrationNodeSize(const Function *Fn) {
16373 if (!Fn->hasPersonalityFn())
16374 report_fatal_error(
16375 "querying registration node size for function without personality");
16376 // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
16377 // WinEHStatePass for the full struct definition.
16378 switch (classifyEHPersonality(Fn->getPersonalityFn())) {
16379 case EHPersonality::MSVC_X86SEH: return 24;
16380 case EHPersonality::MSVC_CXX: return 16;
16383 report_fatal_error(
16384 "can only recover FP for 32-bit MSVC EH personality functions");
16387 /// When the MSVC runtime transfers control to us, either to an outlined
16388 /// function or when returning to a parent frame after catching an exception, we
16389 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
16390 /// Here's the math:
16391 /// RegNodeBase = EntryEBP - RegNodeSize
16392 /// ParentFP = RegNodeBase - ParentFrameOffset
16393 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
16394 /// subtracting the offset (negative on x86) takes us back to the parent FP.
16395 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
16396 SDValue EntryEBP) {
16397 MachineFunction &MF = DAG.getMachineFunction();
16400 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16401 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
16403 // It's possible that the parent function no longer has a personality function
16404 // if the exceptional code was optimized away, in which case we just return
16405 // the incoming EBP.
16406 if (!Fn->hasPersonalityFn())
16409 // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
16410 // registration, or the .set_setframe offset.
16411 MCSymbol *OffsetSym =
16412 MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
16413 GlobalValue::getRealLinkageName(Fn->getName()));
16414 SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
16415 SDValue ParentFrameOffset =
16416 DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
16418 // Return EntryEBP + ParentFrameOffset for x64. This adjusts from RSP after
16419 // prologue to RBP in the parent function.
16420 const X86Subtarget &Subtarget =
16421 static_cast<const X86Subtarget &>(DAG.getSubtarget());
16422 if (Subtarget.is64Bit())
16423 return DAG.getNode(ISD::ADD, dl, PtrVT, EntryEBP, ParentFrameOffset);
16425 int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16426 // RegNodeBase = EntryEBP - RegNodeSize
16427 // ParentFP = RegNodeBase - ParentFrameOffset
16428 SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
16429 DAG.getConstant(RegNodeSize, dl, PtrVT));
16430 return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, ParentFrameOffset);
16433 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16434 SelectionDAG &DAG) {
16436 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16437 MVT VT = Op.getSimpleValueType();
16438 const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
16440 switch(IntrData->Type) {
16441 case INTR_TYPE_1OP:
16442 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
16443 case INTR_TYPE_2OP:
16444 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16446 case INTR_TYPE_2OP_IMM8:
16447 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16448 DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(2)));
16449 case INTR_TYPE_3OP:
16450 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16451 Op.getOperand(2), Op.getOperand(3));
16452 case INTR_TYPE_4OP:
16453 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16454 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
16455 case INTR_TYPE_1OP_MASK_RM: {
16456 SDValue Src = Op.getOperand(1);
16457 SDValue PassThru = Op.getOperand(2);
16458 SDValue Mask = Op.getOperand(3);
16459 SDValue RoundingMode;
16460 // We allways add rounding mode to the Node.
16461 // If the rounding mode is not specified, we add the
16462 // "current direction" mode.
16463 if (Op.getNumOperands() == 4)
16465 DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16467 RoundingMode = Op.getOperand(4);
16468 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16469 if (IntrWithRoundingModeOpcode != 0)
16470 if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
16471 X86::STATIC_ROUNDING::CUR_DIRECTION)
16472 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16473 dl, Op.getValueType(), Src, RoundingMode),
16474 Mask, PassThru, Subtarget, DAG);
16475 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
16477 Mask, PassThru, Subtarget, DAG);
16479 case INTR_TYPE_1OP_MASK: {
16480 SDValue Src = Op.getOperand(1);
16481 SDValue PassThru = Op.getOperand(2);
16482 SDValue Mask = Op.getOperand(3);
16483 // We add rounding mode to the Node when
16484 // - RM Opcode is specified and
16485 // - RM is not "current direction".
16486 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16487 if (IntrWithRoundingModeOpcode != 0) {
16488 SDValue Rnd = Op.getOperand(4);
16489 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16490 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16491 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16492 dl, Op.getValueType(),
16494 Mask, PassThru, Subtarget, DAG);
16497 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
16498 Mask, PassThru, Subtarget, DAG);
16500 case INTR_TYPE_SCALAR_MASK: {
16501 SDValue Src1 = Op.getOperand(1);
16502 SDValue Src2 = Op.getOperand(2);
16503 SDValue passThru = Op.getOperand(3);
16504 SDValue Mask = Op.getOperand(4);
16505 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2),
16506 Mask, passThru, Subtarget, DAG);
16508 case INTR_TYPE_SCALAR_MASK_RM: {
16509 SDValue Src1 = Op.getOperand(1);
16510 SDValue Src2 = Op.getOperand(2);
16511 SDValue Src0 = Op.getOperand(3);
16512 SDValue Mask = Op.getOperand(4);
16513 // There are 2 kinds of intrinsics in this group:
16514 // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
16515 // (2) With rounding mode and sae - 7 operands.
16516 if (Op.getNumOperands() == 6) {
16517 SDValue Sae = Op.getOperand(5);
16518 unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
16519 return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
16521 Mask, Src0, Subtarget, DAG);
16523 assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
16524 SDValue RoundingMode = Op.getOperand(5);
16525 SDValue Sae = Op.getOperand(6);
16526 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
16527 RoundingMode, Sae),
16528 Mask, Src0, Subtarget, DAG);
16530 case INTR_TYPE_2OP_MASK:
16531 case INTR_TYPE_2OP_IMM8_MASK: {
16532 SDValue Src1 = Op.getOperand(1);
16533 SDValue Src2 = Op.getOperand(2);
16534 SDValue PassThru = Op.getOperand(3);
16535 SDValue Mask = Op.getOperand(4);
16537 if (IntrData->Type == INTR_TYPE_2OP_IMM8_MASK)
16538 Src2 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src2);
16540 // We specify 2 possible opcodes for intrinsics with rounding modes.
16541 // First, we check if the intrinsic may have non-default rounding mode,
16542 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16543 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16544 if (IntrWithRoundingModeOpcode != 0) {
16545 SDValue Rnd = Op.getOperand(5);
16546 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16547 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16548 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16549 dl, Op.getValueType(),
16551 Mask, PassThru, Subtarget, DAG);
16554 // TODO: Intrinsics should have fast-math-flags to propagate.
16555 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,Src1,Src2),
16556 Mask, PassThru, Subtarget, DAG);
16558 case INTR_TYPE_2OP_MASK_RM: {
16559 SDValue Src1 = Op.getOperand(1);
16560 SDValue Src2 = Op.getOperand(2);
16561 SDValue PassThru = Op.getOperand(3);
16562 SDValue Mask = Op.getOperand(4);
16563 // We specify 2 possible modes for intrinsics, with/without rounding
16565 // First, we check if the intrinsic have rounding mode (6 operands),
16566 // if not, we set rounding mode to "current".
16568 if (Op.getNumOperands() == 6)
16569 Rnd = Op.getOperand(5);
16571 Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16572 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16574 Mask, PassThru, Subtarget, DAG);
16576 case INTR_TYPE_3OP_SCALAR_MASK_RM: {
16577 SDValue Src1 = Op.getOperand(1);
16578 SDValue Src2 = Op.getOperand(2);
16579 SDValue Src3 = Op.getOperand(3);
16580 SDValue PassThru = Op.getOperand(4);
16581 SDValue Mask = Op.getOperand(5);
16582 SDValue Sae = Op.getOperand(6);
16584 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1,
16586 Mask, PassThru, Subtarget, DAG);
16588 case INTR_TYPE_3OP_MASK_RM: {
16589 SDValue Src1 = Op.getOperand(1);
16590 SDValue Src2 = Op.getOperand(2);
16591 SDValue Imm = Op.getOperand(3);
16592 SDValue PassThru = Op.getOperand(4);
16593 SDValue Mask = Op.getOperand(5);
16594 // We specify 2 possible modes for intrinsics, with/without rounding
16596 // First, we check if the intrinsic have rounding mode (7 operands),
16597 // if not, we set rounding mode to "current".
16599 if (Op.getNumOperands() == 7)
16600 Rnd = Op.getOperand(6);
16602 Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16603 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16604 Src1, Src2, Imm, Rnd),
16605 Mask, PassThru, Subtarget, DAG);
16607 case INTR_TYPE_3OP_IMM8_MASK:
16608 case INTR_TYPE_3OP_MASK:
16609 case INSERT_SUBVEC: {
16610 SDValue Src1 = Op.getOperand(1);
16611 SDValue Src2 = Op.getOperand(2);
16612 SDValue Src3 = Op.getOperand(3);
16613 SDValue PassThru = Op.getOperand(4);
16614 SDValue Mask = Op.getOperand(5);
16616 if (IntrData->Type == INTR_TYPE_3OP_IMM8_MASK)
16617 Src3 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src3);
16618 else if (IntrData->Type == INSERT_SUBVEC) {
16619 // imm should be adapted to ISD::INSERT_SUBVECTOR behavior
16620 assert(isa<ConstantSDNode>(Src3) && "Expected a ConstantSDNode here!");
16621 unsigned Imm = cast<ConstantSDNode>(Src3)->getZExtValue();
16622 Imm *= Src2.getSimpleValueType().getVectorNumElements();
16623 Src3 = DAG.getTargetConstant(Imm, dl, MVT::i32);
16626 // We specify 2 possible opcodes for intrinsics with rounding modes.
16627 // First, we check if the intrinsic may have non-default rounding mode,
16628 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16629 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16630 if (IntrWithRoundingModeOpcode != 0) {
16631 SDValue Rnd = Op.getOperand(6);
16632 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16633 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16634 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16635 dl, Op.getValueType(),
16636 Src1, Src2, Src3, Rnd),
16637 Mask, PassThru, Subtarget, DAG);
16640 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16642 Mask, PassThru, Subtarget, DAG);
16644 case VPERM_3OP_MASKZ:
16645 case VPERM_3OP_MASK:{
16646 // Src2 is the PassThru
16647 SDValue Src1 = Op.getOperand(1);
16648 SDValue Src2 = Op.getOperand(2);
16649 SDValue Src3 = Op.getOperand(3);
16650 SDValue Mask = Op.getOperand(4);
16651 MVT VT = Op.getSimpleValueType();
16652 SDValue PassThru = SDValue();
16654 // set PassThru element
16655 if (IntrData->Type == VPERM_3OP_MASKZ)
16656 PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16658 PassThru = DAG.getBitcast(VT, Src2);
16660 // Swap Src1 and Src2 in the node creation
16661 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
16662 dl, Op.getValueType(),
16664 Mask, PassThru, Subtarget, DAG);
16668 case FMA_OP_MASK: {
16669 SDValue Src1 = Op.getOperand(1);
16670 SDValue Src2 = Op.getOperand(2);
16671 SDValue Src3 = Op.getOperand(3);
16672 SDValue Mask = Op.getOperand(4);
16673 MVT VT = Op.getSimpleValueType();
16674 SDValue PassThru = SDValue();
16676 // set PassThru element
16677 if (IntrData->Type == FMA_OP_MASKZ)
16678 PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16679 else if (IntrData->Type == FMA_OP_MASK3)
16684 // We specify 2 possible opcodes for intrinsics with rounding modes.
16685 // First, we check if the intrinsic may have non-default rounding mode,
16686 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16687 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16688 if (IntrWithRoundingModeOpcode != 0) {
16689 SDValue Rnd = Op.getOperand(5);
16690 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16691 X86::STATIC_ROUNDING::CUR_DIRECTION)
16692 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16693 dl, Op.getValueType(),
16694 Src1, Src2, Src3, Rnd),
16695 Mask, PassThru, Subtarget, DAG);
16697 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
16698 dl, Op.getValueType(),
16700 Mask, PassThru, Subtarget, DAG);
16702 case TERLOG_OP_MASK:
16703 case TERLOG_OP_MASKZ: {
16704 SDValue Src1 = Op.getOperand(1);
16705 SDValue Src2 = Op.getOperand(2);
16706 SDValue Src3 = Op.getOperand(3);
16707 SDValue Src4 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(4));
16708 SDValue Mask = Op.getOperand(5);
16709 MVT VT = Op.getSimpleValueType();
16710 SDValue PassThru = Src1;
16711 // Set PassThru element.
16712 if (IntrData->Type == TERLOG_OP_MASKZ)
16713 PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16715 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16716 Src1, Src2, Src3, Src4),
16717 Mask, PassThru, Subtarget, DAG);
16720 // FPclass intrinsics with mask
16721 SDValue Src1 = Op.getOperand(1);
16722 MVT VT = Src1.getSimpleValueType();
16723 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16724 SDValue Imm = Op.getOperand(2);
16725 SDValue Mask = Op.getOperand(3);
16726 MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16727 Mask.getSimpleValueType().getSizeInBits());
16728 SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MaskVT, Src1, Imm);
16729 SDValue FPclassMask = getVectorMaskingNode(FPclass, Mask,
16730 DAG.getTargetConstant(0, dl, MaskVT),
16732 SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16733 DAG.getUNDEF(BitcastVT), FPclassMask,
16734 DAG.getIntPtrConstant(0, dl));
16735 return DAG.getBitcast(Op.getValueType(), Res);
16738 SDValue Src1 = Op.getOperand(1);
16739 SDValue Imm = Op.getOperand(2);
16740 SDValue Mask = Op.getOperand(3);
16741 SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MVT::i1, Src1, Imm);
16742 SDValue FPclassMask = getScalarMaskingNode(FPclass, Mask,
16743 DAG.getTargetConstant(0, dl, MVT::i1), Subtarget, DAG);
16744 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i8, FPclassMask);
16747 case CMP_MASK_CC: {
16748 // Comparison intrinsics with masks.
16749 // Example of transformation:
16750 // (i8 (int_x86_avx512_mask_pcmpeq_q_128
16751 // (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
16753 // (v8i1 (insert_subvector undef,
16754 // (v2i1 (and (PCMPEQM %a, %b),
16755 // (extract_subvector
16756 // (v8i1 (bitcast %mask)), 0))), 0))))
16757 MVT VT = Op.getOperand(1).getSimpleValueType();
16758 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16759 SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
16760 MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16761 Mask.getSimpleValueType().getSizeInBits());
16763 if (IntrData->Type == CMP_MASK_CC) {
16764 SDValue CC = Op.getOperand(3);
16765 CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
16766 // We specify 2 possible opcodes for intrinsics with rounding modes.
16767 // First, we check if the intrinsic may have non-default rounding mode,
16768 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16769 if (IntrData->Opc1 != 0) {
16770 SDValue Rnd = Op.getOperand(5);
16771 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16772 X86::STATIC_ROUNDING::CUR_DIRECTION)
16773 Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
16774 Op.getOperand(2), CC, Rnd);
16776 //default rounding mode
16778 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16779 Op.getOperand(2), CC);
16782 assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
16783 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16786 SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
16787 DAG.getTargetConstant(0, dl,
16790 SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16791 DAG.getUNDEF(BitcastVT), CmpMask,
16792 DAG.getIntPtrConstant(0, dl));
16793 return DAG.getBitcast(Op.getValueType(), Res);
16795 case CMP_MASK_SCALAR_CC: {
16796 SDValue Src1 = Op.getOperand(1);
16797 SDValue Src2 = Op.getOperand(2);
16798 SDValue CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(3));
16799 SDValue Mask = Op.getOperand(4);
16802 if (IntrData->Opc1 != 0) {
16803 SDValue Rnd = Op.getOperand(5);
16804 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16805 X86::STATIC_ROUNDING::CUR_DIRECTION)
16806 Cmp = DAG.getNode(IntrData->Opc1, dl, MVT::i1, Src1, Src2, CC, Rnd);
16808 //default rounding mode
16810 Cmp = DAG.getNode(IntrData->Opc0, dl, MVT::i1, Src1, Src2, CC);
16812 SDValue CmpMask = getScalarMaskingNode(Cmp, Mask,
16813 DAG.getTargetConstant(0, dl,
16817 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i8,
16818 DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i8, CmpMask),
16819 DAG.getValueType(MVT::i1));
16821 case COMI: { // Comparison intrinsics
16822 ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
16823 SDValue LHS = Op.getOperand(1);
16824 SDValue RHS = Op.getOperand(2);
16825 unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
16826 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
16827 SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
16828 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16829 DAG.getConstant(X86CC, dl, MVT::i8), Cond);
16830 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16832 case COMI_RM: { // Comparison intrinsics with Sae
16833 SDValue LHS = Op.getOperand(1);
16834 SDValue RHS = Op.getOperand(2);
16835 SDValue CC = Op.getOperand(3);
16836 SDValue Sae = Op.getOperand(4);
16837 auto ComiType = TranslateX86ConstCondToX86CC(CC);
16838 // choose between ordered and unordered (comi/ucomi)
16839 unsigned comiOp = std::get<0>(ComiType) ? IntrData->Opc0 : IntrData->Opc1;
16841 if (cast<ConstantSDNode>(Sae)->getZExtValue() !=
16842 X86::STATIC_ROUNDING::CUR_DIRECTION)
16843 Cond = DAG.getNode(comiOp, dl, MVT::i32, LHS, RHS, Sae);
16845 Cond = DAG.getNode(comiOp, dl, MVT::i32, LHS, RHS);
16846 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16847 DAG.getConstant(std::get<1>(ComiType), dl, MVT::i8), Cond);
16848 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16851 return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
16852 Op.getOperand(1), Op.getOperand(2), DAG);
16854 return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
16855 Op.getSimpleValueType(),
16857 Op.getOperand(2), DAG),
16858 Op.getOperand(4), Op.getOperand(3), Subtarget,
16860 case COMPRESS_EXPAND_IN_REG: {
16861 SDValue Mask = Op.getOperand(3);
16862 SDValue DataToCompress = Op.getOperand(1);
16863 SDValue PassThru = Op.getOperand(2);
16864 if (isAllOnesConstant(Mask)) // return data as is
16865 return Op.getOperand(1);
16867 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16869 Mask, PassThru, Subtarget, DAG);
16872 SDValue Mask = Op.getOperand(1);
16873 MVT MaskVT = MVT::getVectorVT(MVT::i1,
16874 Mask.getSimpleValueType().getSizeInBits());
16875 Mask = DAG.getBitcast(MaskVT, Mask);
16876 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Mask);
16879 SDValue Mask = Op.getOperand(3);
16880 MVT VT = Op.getSimpleValueType();
16881 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16882 SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
16883 return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
16887 MVT VT = Op.getSimpleValueType();
16888 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getSizeInBits()/2);
16890 SDValue Src1 = getMaskNode(Op.getOperand(1), MaskVT, Subtarget, DAG, dl);
16891 SDValue Src2 = getMaskNode(Op.getOperand(2), MaskVT, Subtarget, DAG, dl);
16892 // Arguments should be swapped.
16893 SDValue Res = DAG.getNode(IntrData->Opc0, dl,
16894 MVT::getVectorVT(MVT::i1, VT.getSizeInBits()),
16896 return DAG.getBitcast(VT, Res);
16898 case CONVERT_TO_MASK: {
16899 MVT SrcVT = Op.getOperand(1).getSimpleValueType();
16900 MVT MaskVT = MVT::getVectorVT(MVT::i1, SrcVT.getVectorNumElements());
16901 MVT BitcastVT = MVT::getVectorVT(MVT::i1, VT.getSizeInBits());
16903 SDValue CvtMask = DAG.getNode(IntrData->Opc0, dl, MaskVT,
16905 SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16906 DAG.getUNDEF(BitcastVT), CvtMask,
16907 DAG.getIntPtrConstant(0, dl));
16908 return DAG.getBitcast(Op.getValueType(), Res);
16910 case CONVERT_MASK_TO_VEC: {
16911 SDValue Mask = Op.getOperand(1);
16912 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16913 SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
16914 return DAG.getNode(IntrData->Opc0, dl, VT, VMask);
16916 case BRCST_SUBVEC_TO_VEC: {
16917 SDValue Src = Op.getOperand(1);
16918 SDValue Passthru = Op.getOperand(2);
16919 SDValue Mask = Op.getOperand(3);
16920 EVT resVT = Passthru.getValueType();
16921 SDValue subVec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, resVT,
16922 DAG.getUNDEF(resVT), Src,
16923 DAG.getIntPtrConstant(0, dl));
16925 if (Src.getSimpleValueType().is256BitVector() && resVT.is512BitVector())
16926 immVal = DAG.getConstant(0x44, dl, MVT::i8);
16928 immVal = DAG.getConstant(0, dl, MVT::i8);
16929 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16930 subVec, subVec, immVal),
16931 Mask, Passthru, Subtarget, DAG);
16939 default: return SDValue(); // Don't custom lower most intrinsics.
16941 case Intrinsic::x86_avx2_permd:
16942 case Intrinsic::x86_avx2_permps:
16943 // Operands intentionally swapped. Mask is last operand to intrinsic,
16944 // but second operand for node/instruction.
16945 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
16946 Op.getOperand(2), Op.getOperand(1));
16948 // ptest and testp intrinsics. The intrinsic these come from are designed to
16949 // return an integer value, not just an instruction so lower it to the ptest
16950 // or testp pattern and a setcc for the result.
16951 case Intrinsic::x86_sse41_ptestz:
16952 case Intrinsic::x86_sse41_ptestc:
16953 case Intrinsic::x86_sse41_ptestnzc:
16954 case Intrinsic::x86_avx_ptestz_256:
16955 case Intrinsic::x86_avx_ptestc_256:
16956 case Intrinsic::x86_avx_ptestnzc_256:
16957 case Intrinsic::x86_avx_vtestz_ps:
16958 case Intrinsic::x86_avx_vtestc_ps:
16959 case Intrinsic::x86_avx_vtestnzc_ps:
16960 case Intrinsic::x86_avx_vtestz_pd:
16961 case Intrinsic::x86_avx_vtestc_pd:
16962 case Intrinsic::x86_avx_vtestnzc_pd:
16963 case Intrinsic::x86_avx_vtestz_ps_256:
16964 case Intrinsic::x86_avx_vtestc_ps_256:
16965 case Intrinsic::x86_avx_vtestnzc_ps_256:
16966 case Intrinsic::x86_avx_vtestz_pd_256:
16967 case Intrinsic::x86_avx_vtestc_pd_256:
16968 case Intrinsic::x86_avx_vtestnzc_pd_256: {
16969 bool IsTestPacked = false;
16972 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
16973 case Intrinsic::x86_avx_vtestz_ps:
16974 case Intrinsic::x86_avx_vtestz_pd:
16975 case Intrinsic::x86_avx_vtestz_ps_256:
16976 case Intrinsic::x86_avx_vtestz_pd_256:
16977 IsTestPacked = true; // Fallthrough
16978 case Intrinsic::x86_sse41_ptestz:
16979 case Intrinsic::x86_avx_ptestz_256:
16981 X86CC = X86::COND_E;
16983 case Intrinsic::x86_avx_vtestc_ps:
16984 case Intrinsic::x86_avx_vtestc_pd:
16985 case Intrinsic::x86_avx_vtestc_ps_256:
16986 case Intrinsic::x86_avx_vtestc_pd_256:
16987 IsTestPacked = true; // Fallthrough
16988 case Intrinsic::x86_sse41_ptestc:
16989 case Intrinsic::x86_avx_ptestc_256:
16991 X86CC = X86::COND_B;
16993 case Intrinsic::x86_avx_vtestnzc_ps:
16994 case Intrinsic::x86_avx_vtestnzc_pd:
16995 case Intrinsic::x86_avx_vtestnzc_ps_256:
16996 case Intrinsic::x86_avx_vtestnzc_pd_256:
16997 IsTestPacked = true; // Fallthrough
16998 case Intrinsic::x86_sse41_ptestnzc:
16999 case Intrinsic::x86_avx_ptestnzc_256:
17001 X86CC = X86::COND_A;
17005 SDValue LHS = Op.getOperand(1);
17006 SDValue RHS = Op.getOperand(2);
17007 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
17008 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
17009 SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
17010 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
17011 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
17013 case Intrinsic::x86_avx512_kortestz_w:
17014 case Intrinsic::x86_avx512_kortestc_w: {
17015 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
17016 SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
17017 SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
17018 SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
17019 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
17020 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
17021 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
17024 case Intrinsic::x86_sse42_pcmpistria128:
17025 case Intrinsic::x86_sse42_pcmpestria128:
17026 case Intrinsic::x86_sse42_pcmpistric128:
17027 case Intrinsic::x86_sse42_pcmpestric128:
17028 case Intrinsic::x86_sse42_pcmpistrio128:
17029 case Intrinsic::x86_sse42_pcmpestrio128:
17030 case Intrinsic::x86_sse42_pcmpistris128:
17031 case Intrinsic::x86_sse42_pcmpestris128:
17032 case Intrinsic::x86_sse42_pcmpistriz128:
17033 case Intrinsic::x86_sse42_pcmpestriz128: {
17037 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
17038 case Intrinsic::x86_sse42_pcmpistria128:
17039 Opcode = X86ISD::PCMPISTRI;
17040 X86CC = X86::COND_A;
17042 case Intrinsic::x86_sse42_pcmpestria128:
17043 Opcode = X86ISD::PCMPESTRI;
17044 X86CC = X86::COND_A;
17046 case Intrinsic::x86_sse42_pcmpistric128:
17047 Opcode = X86ISD::PCMPISTRI;
17048 X86CC = X86::COND_B;
17050 case Intrinsic::x86_sse42_pcmpestric128:
17051 Opcode = X86ISD::PCMPESTRI;
17052 X86CC = X86::COND_B;
17054 case Intrinsic::x86_sse42_pcmpistrio128:
17055 Opcode = X86ISD::PCMPISTRI;
17056 X86CC = X86::COND_O;
17058 case Intrinsic::x86_sse42_pcmpestrio128:
17059 Opcode = X86ISD::PCMPESTRI;
17060 X86CC = X86::COND_O;
17062 case Intrinsic::x86_sse42_pcmpistris128:
17063 Opcode = X86ISD::PCMPISTRI;
17064 X86CC = X86::COND_S;
17066 case Intrinsic::x86_sse42_pcmpestris128:
17067 Opcode = X86ISD::PCMPESTRI;
17068 X86CC = X86::COND_S;
17070 case Intrinsic::x86_sse42_pcmpistriz128:
17071 Opcode = X86ISD::PCMPISTRI;
17072 X86CC = X86::COND_E;
17074 case Intrinsic::x86_sse42_pcmpestriz128:
17075 Opcode = X86ISD::PCMPESTRI;
17076 X86CC = X86::COND_E;
17079 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
17080 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
17081 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
17082 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17083 DAG.getConstant(X86CC, dl, MVT::i8),
17084 SDValue(PCMP.getNode(), 1));
17085 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
17088 case Intrinsic::x86_sse42_pcmpistri128:
17089 case Intrinsic::x86_sse42_pcmpestri128: {
17091 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
17092 Opcode = X86ISD::PCMPISTRI;
17094 Opcode = X86ISD::PCMPESTRI;
17096 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
17097 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
17098 return DAG.getNode(Opcode, dl, VTs, NewOps);
17101 case Intrinsic::x86_seh_lsda: {
17102 // Compute the symbol for the LSDA. We know it'll get emitted later.
17103 MachineFunction &MF = DAG.getMachineFunction();
17104 SDValue Op1 = Op.getOperand(1);
17105 auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
17106 MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
17107 GlobalValue::getRealLinkageName(Fn->getName()));
17109 // Generate a simple absolute symbol reference. This intrinsic is only
17110 // supported on 32-bit Windows, which isn't PIC.
17111 SDValue Result = DAG.getMCSymbol(LSDASym, VT);
17112 return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
17115 case Intrinsic::x86_seh_recoverfp: {
17116 SDValue FnOp = Op.getOperand(1);
17117 SDValue IncomingFPOp = Op.getOperand(2);
17118 GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
17119 auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
17121 report_fatal_error(
17122 "llvm.x86.seh.recoverfp must take a function as the first argument");
17123 return recoverFramePointer(DAG, Fn, IncomingFPOp);
17126 case Intrinsic::localaddress: {
17127 // Returns one of the stack, base, or frame pointer registers, depending on
17128 // which is used to reference local variables.
17129 MachineFunction &MF = DAG.getMachineFunction();
17130 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17132 if (RegInfo->hasBasePointer(MF))
17133 Reg = RegInfo->getBaseRegister();
17134 else // This function handles the SP or FP case.
17135 Reg = RegInfo->getPtrSizedFrameRegister(MF);
17136 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
17141 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17142 SDValue Src, SDValue Mask, SDValue Base,
17143 SDValue Index, SDValue ScaleOp, SDValue Chain,
17144 const X86Subtarget * Subtarget) {
17146 auto *C = cast<ConstantSDNode>(ScaleOp);
17147 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
17148 MVT MaskVT = MVT::getVectorVT(MVT::i1,
17149 Index.getSimpleValueType().getVectorNumElements());
17151 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
17153 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
17155 MVT BitcastVT = MVT::getVectorVT(MVT::i1,
17156 Mask.getSimpleValueType().getSizeInBits());
17158 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
17159 // are extracted by EXTRACT_SUBVECTOR.
17160 MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17161 DAG.getBitcast(BitcastVT, Mask),
17162 DAG.getIntPtrConstant(0, dl));
17164 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
17165 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
17166 SDValue Segment = DAG.getRegister(0, MVT::i32);
17167 if (Src.getOpcode() == ISD::UNDEF)
17168 Src = getZeroVector(Op.getSimpleValueType(), Subtarget, DAG, dl);
17169 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
17170 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
17171 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
17172 return DAG.getMergeValues(RetOps, dl);
17175 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17176 SDValue Src, SDValue Mask, SDValue Base,
17177 SDValue Index, SDValue ScaleOp, SDValue Chain) {
17179 auto *C = cast<ConstantSDNode>(ScaleOp);
17180 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
17181 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
17182 SDValue Segment = DAG.getRegister(0, MVT::i32);
17183 MVT MaskVT = MVT::getVectorVT(MVT::i1,
17184 Index.getSimpleValueType().getVectorNumElements());
17186 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
17188 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
17190 MVT BitcastVT = MVT::getVectorVT(MVT::i1,
17191 Mask.getSimpleValueType().getSizeInBits());
17193 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
17194 // are extracted by EXTRACT_SUBVECTOR.
17195 MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17196 DAG.getBitcast(BitcastVT, Mask),
17197 DAG.getIntPtrConstant(0, dl));
17199 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
17200 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
17201 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
17202 return SDValue(Res, 1);
17205 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
17206 SDValue Mask, SDValue Base, SDValue Index,
17207 SDValue ScaleOp, SDValue Chain) {
17209 auto *C = cast<ConstantSDNode>(ScaleOp);
17210 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
17211 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
17212 SDValue Segment = DAG.getRegister(0, MVT::i32);
17214 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
17216 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
17218 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
17220 MaskInReg = DAG.getBitcast(MaskVT, Mask);
17221 //SDVTList VTs = DAG.getVTList(MVT::Other);
17222 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
17223 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
17224 return SDValue(Res, 0);
17227 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
17228 // read performance monitor counters (x86_rdpmc).
17229 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
17230 SelectionDAG &DAG, const X86Subtarget *Subtarget,
17231 SmallVectorImpl<SDValue> &Results) {
17232 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
17233 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17236 // The ECX register is used to select the index of the performance counter
17238 SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
17240 SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
17242 // Reads the content of a 64-bit performance counter and returns it in the
17243 // registers EDX:EAX.
17244 if (Subtarget->is64Bit()) {
17245 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
17246 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
17249 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
17250 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
17253 Chain = HI.getValue(1);
17255 if (Subtarget->is64Bit()) {
17256 // The EAX register is loaded with the low-order 32 bits. The EDX register
17257 // is loaded with the supported high-order bits of the counter.
17258 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
17259 DAG.getConstant(32, DL, MVT::i8));
17260 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
17261 Results.push_back(Chain);
17265 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
17266 SDValue Ops[] = { LO, HI };
17267 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
17268 Results.push_back(Pair);
17269 Results.push_back(Chain);
17272 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
17273 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
17274 // also used to custom lower READCYCLECOUNTER nodes.
17275 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
17276 SelectionDAG &DAG, const X86Subtarget *Subtarget,
17277 SmallVectorImpl<SDValue> &Results) {
17278 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17279 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
17282 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
17283 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
17284 // and the EAX register is loaded with the low-order 32 bits.
17285 if (Subtarget->is64Bit()) {
17286 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
17287 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
17290 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
17291 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
17294 SDValue Chain = HI.getValue(1);
17296 if (Opcode == X86ISD::RDTSCP_DAG) {
17297 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
17299 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
17300 // the ECX register. Add 'ecx' explicitly to the chain.
17301 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
17303 // Explicitly store the content of ECX at the location passed in input
17304 // to the 'rdtscp' intrinsic.
17305 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
17306 MachinePointerInfo(), false, false, 0);
17309 if (Subtarget->is64Bit()) {
17310 // The EDX register is loaded with the high-order 32 bits of the MSR, and
17311 // the EAX register is loaded with the low-order 32 bits.
17312 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
17313 DAG.getConstant(32, DL, MVT::i8));
17314 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
17315 Results.push_back(Chain);
17319 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
17320 SDValue Ops[] = { LO, HI };
17321 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
17322 Results.push_back(Pair);
17323 Results.push_back(Chain);
17326 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
17327 SelectionDAG &DAG) {
17328 SmallVector<SDValue, 2> Results;
17330 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
17332 return DAG.getMergeValues(Results, DL);
17335 static SDValue MarkEHRegistrationNode(SDValue Op, SelectionDAG &DAG) {
17336 MachineFunction &MF = DAG.getMachineFunction();
17337 SDValue Chain = Op.getOperand(0);
17338 SDValue RegNode = Op.getOperand(2);
17339 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
17341 report_fatal_error("EH registrations only live in functions using WinEH");
17343 // Cast the operand to an alloca, and remember the frame index.
17344 auto *FINode = dyn_cast<FrameIndexSDNode>(RegNode);
17346 report_fatal_error("llvm.x86.seh.ehregnode expects a static alloca");
17347 EHInfo->EHRegNodeFrameIndex = FINode->getIndex();
17349 // Return the chain operand without making any DAG nodes.
17353 /// \brief Lower intrinsics for TRUNCATE_TO_MEM case
17354 /// return truncate Store/MaskedStore Node
17355 static SDValue LowerINTRINSIC_TRUNCATE_TO_MEM(const SDValue & Op,
17359 SDValue Mask = Op.getOperand(4);
17360 SDValue DataToTruncate = Op.getOperand(3);
17361 SDValue Addr = Op.getOperand(2);
17362 SDValue Chain = Op.getOperand(0);
17364 MVT VT = DataToTruncate.getSimpleValueType();
17365 MVT SVT = MVT::getVectorVT(ElementType, VT.getVectorNumElements());
17367 if (isAllOnesConstant(Mask)) // return just a truncate store
17368 return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr,
17369 MachinePointerInfo(), SVT, false, false,
17370 SVT.getScalarSizeInBits()/8);
17372 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
17373 MVT BitcastVT = MVT::getVectorVT(MVT::i1,
17374 Mask.getSimpleValueType().getSizeInBits());
17375 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
17376 // are extracted by EXTRACT_SUBVECTOR.
17377 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17378 DAG.getBitcast(BitcastVT, Mask),
17379 DAG.getIntPtrConstant(0, dl));
17381 MachineMemOperand *MMO = DAG.getMachineFunction().
17382 getMachineMemOperand(MachinePointerInfo(),
17383 MachineMemOperand::MOStore, SVT.getStoreSize(),
17384 SVT.getScalarSizeInBits()/8);
17386 return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr,
17387 VMask, SVT, MMO, true);
17390 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
17391 SelectionDAG &DAG) {
17392 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
17394 const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
17396 if (IntNo == llvm::Intrinsic::x86_seh_ehregnode)
17397 return MarkEHRegistrationNode(Op, DAG);
17398 if (IntNo == llvm::Intrinsic::x86_flags_read_u32 ||
17399 IntNo == llvm::Intrinsic::x86_flags_read_u64 ||
17400 IntNo == llvm::Intrinsic::x86_flags_write_u32 ||
17401 IntNo == llvm::Intrinsic::x86_flags_write_u64) {
17402 // We need a frame pointer because this will get lowered to a PUSH/POP
17404 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
17405 MFI->setHasOpaqueSPAdjustment(true);
17406 // Don't do anything here, we will expand these intrinsics out later
17407 // during ExpandISelPseudos in EmitInstrWithCustomInserter.
17414 switch(IntrData->Type) {
17415 default: llvm_unreachable("Unknown Intrinsic Type");
17418 // Emit the node with the right value type.
17419 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
17420 SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17422 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
17423 // Otherwise return the value from Rand, which is always 0, casted to i32.
17424 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
17425 DAG.getConstant(1, dl, Op->getValueType(1)),
17426 DAG.getConstant(X86::COND_B, dl, MVT::i32),
17427 SDValue(Result.getNode(), 1) };
17428 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
17429 DAG.getVTList(Op->getValueType(1), MVT::Glue),
17432 // Return { result, isValid, chain }.
17433 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
17434 SDValue(Result.getNode(), 2));
17437 //gather(v1, mask, index, base, scale);
17438 SDValue Chain = Op.getOperand(0);
17439 SDValue Src = Op.getOperand(2);
17440 SDValue Base = Op.getOperand(3);
17441 SDValue Index = Op.getOperand(4);
17442 SDValue Mask = Op.getOperand(5);
17443 SDValue Scale = Op.getOperand(6);
17444 return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
17448 //scatter(base, mask, index, v1, scale);
17449 SDValue Chain = Op.getOperand(0);
17450 SDValue Base = Op.getOperand(2);
17451 SDValue Mask = Op.getOperand(3);
17452 SDValue Index = Op.getOperand(4);
17453 SDValue Src = Op.getOperand(5);
17454 SDValue Scale = Op.getOperand(6);
17455 return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
17459 SDValue Hint = Op.getOperand(6);
17460 unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
17461 assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
17462 unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
17463 SDValue Chain = Op.getOperand(0);
17464 SDValue Mask = Op.getOperand(2);
17465 SDValue Index = Op.getOperand(3);
17466 SDValue Base = Op.getOperand(4);
17467 SDValue Scale = Op.getOperand(5);
17468 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
17470 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
17472 SmallVector<SDValue, 2> Results;
17473 getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
17475 return DAG.getMergeValues(Results, dl);
17477 // Read Performance Monitoring Counters.
17479 SmallVector<SDValue, 2> Results;
17480 getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
17481 return DAG.getMergeValues(Results, dl);
17483 // XTEST intrinsics.
17485 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17486 SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17487 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17488 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
17490 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
17491 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
17492 Ret, SDValue(InTrans.getNode(), 1));
17496 SmallVector<SDValue, 2> Results;
17497 SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17498 SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
17499 SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
17500 DAG.getConstant(-1, dl, MVT::i8));
17501 SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
17502 Op.getOperand(4), GenCF.getValue(1));
17503 SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
17504 Op.getOperand(5), MachinePointerInfo(),
17506 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17507 DAG.getConstant(X86::COND_B, dl, MVT::i8),
17509 Results.push_back(SetCC);
17510 Results.push_back(Store);
17511 return DAG.getMergeValues(Results, dl);
17513 case COMPRESS_TO_MEM: {
17515 SDValue Mask = Op.getOperand(4);
17516 SDValue DataToCompress = Op.getOperand(3);
17517 SDValue Addr = Op.getOperand(2);
17518 SDValue Chain = Op.getOperand(0);
17520 MVT VT = DataToCompress.getSimpleValueType();
17521 if (isAllOnesConstant(Mask)) // return just a store
17522 return DAG.getStore(Chain, dl, DataToCompress, Addr,
17523 MachinePointerInfo(), false, false,
17524 VT.getScalarSizeInBits()/8);
17526 SDValue Compressed =
17527 getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
17528 Mask, DAG.getUNDEF(VT), Subtarget, DAG);
17529 return DAG.getStore(Chain, dl, Compressed, Addr,
17530 MachinePointerInfo(), false, false,
17531 VT.getScalarSizeInBits()/8);
17533 case TRUNCATE_TO_MEM_VI8:
17534 return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i8);
17535 case TRUNCATE_TO_MEM_VI16:
17536 return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i16);
17537 case TRUNCATE_TO_MEM_VI32:
17538 return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i32);
17539 case EXPAND_FROM_MEM: {
17541 SDValue Mask = Op.getOperand(4);
17542 SDValue PassThru = Op.getOperand(3);
17543 SDValue Addr = Op.getOperand(2);
17544 SDValue Chain = Op.getOperand(0);
17545 MVT VT = Op.getSimpleValueType();
17547 if (isAllOnesConstant(Mask)) // return just a load
17548 return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
17549 false, VT.getScalarSizeInBits()/8);
17551 SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
17552 false, false, false,
17553 VT.getScalarSizeInBits()/8);
17555 SDValue Results[] = {
17556 getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
17557 Mask, PassThru, Subtarget, DAG), Chain};
17558 return DAG.getMergeValues(Results, dl);
17563 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
17564 SelectionDAG &DAG) const {
17565 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
17566 MFI->setReturnAddressIsTaken(true);
17568 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
17571 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17573 EVT PtrVT = getPointerTy(DAG.getDataLayout());
17576 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
17577 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17578 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
17579 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17580 DAG.getNode(ISD::ADD, dl, PtrVT,
17581 FrameAddr, Offset),
17582 MachinePointerInfo(), false, false, false, 0);
17585 // Just load the return address.
17586 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
17587 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17588 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
17591 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
17592 MachineFunction &MF = DAG.getMachineFunction();
17593 MachineFrameInfo *MFI = MF.getFrameInfo();
17594 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
17595 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17596 EVT VT = Op.getValueType();
17598 MFI->setFrameAddressIsTaken(true);
17600 if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
17601 // Depth > 0 makes no sense on targets which use Windows unwind codes. It
17602 // is not possible to crawl up the stack without looking at the unwind codes
17604 int FrameAddrIndex = FuncInfo->getFAIndex();
17605 if (!FrameAddrIndex) {
17606 // Set up a frame object for the return address.
17607 unsigned SlotSize = RegInfo->getSlotSize();
17608 FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
17609 SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
17610 FuncInfo->setFAIndex(FrameAddrIndex);
17612 return DAG.getFrameIndex(FrameAddrIndex, VT);
17615 unsigned FrameReg =
17616 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17617 SDLoc dl(Op); // FIXME probably not meaningful
17618 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17619 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
17620 (FrameReg == X86::EBP && VT == MVT::i32)) &&
17621 "Invalid Frame Register!");
17622 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
17624 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
17625 MachinePointerInfo(),
17626 false, false, false, 0);
17630 // FIXME? Maybe this could be a TableGen attribute on some registers and
17631 // this table could be generated automatically from RegInfo.
17632 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
17633 SelectionDAG &DAG) const {
17634 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17635 const MachineFunction &MF = DAG.getMachineFunction();
17637 unsigned Reg = StringSwitch<unsigned>(RegName)
17638 .Case("esp", X86::ESP)
17639 .Case("rsp", X86::RSP)
17640 .Case("ebp", X86::EBP)
17641 .Case("rbp", X86::RBP)
17644 if (Reg == X86::EBP || Reg == X86::RBP) {
17645 if (!TFI.hasFP(MF))
17646 report_fatal_error("register " + StringRef(RegName) +
17647 " is allocatable: function has no frame pointer");
17650 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17651 unsigned FrameReg =
17652 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17653 assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
17654 "Invalid Frame Register!");
17662 report_fatal_error("Invalid register name global variable");
17665 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
17666 SelectionDAG &DAG) const {
17667 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17668 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
17671 unsigned X86TargetLowering::getExceptionPointerRegister(
17672 const Constant *PersonalityFn) const {
17673 if (classifyEHPersonality(PersonalityFn) == EHPersonality::CoreCLR)
17674 return Subtarget->isTarget64BitLP64() ? X86::RDX : X86::EDX;
17676 return Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX;
17679 unsigned X86TargetLowering::getExceptionSelectorRegister(
17680 const Constant *PersonalityFn) const {
17681 // Funclet personalities don't use selectors (the runtime does the selection).
17682 assert(!isFuncletEHPersonality(classifyEHPersonality(PersonalityFn)));
17683 return Subtarget->isTarget64BitLP64() ? X86::RDX : X86::EDX;
17686 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
17687 SDValue Chain = Op.getOperand(0);
17688 SDValue Offset = Op.getOperand(1);
17689 SDValue Handler = Op.getOperand(2);
17692 EVT PtrVT = getPointerTy(DAG.getDataLayout());
17693 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17694 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
17695 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
17696 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
17697 "Invalid Frame Register!");
17698 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
17699 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
17701 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
17702 DAG.getIntPtrConstant(RegInfo->getSlotSize(),
17704 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
17705 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
17707 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
17709 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
17710 DAG.getRegister(StoreAddrReg, PtrVT));
17713 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
17714 SelectionDAG &DAG) const {
17716 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
17717 DAG.getVTList(MVT::i32, MVT::Other),
17718 Op.getOperand(0), Op.getOperand(1));
17721 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
17722 SelectionDAG &DAG) const {
17724 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
17725 Op.getOperand(0), Op.getOperand(1));
17728 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
17729 return Op.getOperand(0);
17732 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
17733 SelectionDAG &DAG) const {
17734 SDValue Root = Op.getOperand(0);
17735 SDValue Trmp = Op.getOperand(1); // trampoline
17736 SDValue FPtr = Op.getOperand(2); // nested function
17737 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
17740 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
17741 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
17743 if (Subtarget->is64Bit()) {
17744 SDValue OutChains[6];
17746 // Large code-model.
17747 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
17748 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
17750 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
17751 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
17753 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
17755 // Load the pointer to the nested function into R11.
17756 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
17757 SDValue Addr = Trmp;
17758 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17759 Addr, MachinePointerInfo(TrmpAddr),
17762 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17763 DAG.getConstant(2, dl, MVT::i64));
17764 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
17765 MachinePointerInfo(TrmpAddr, 2),
17768 // Load the 'nest' parameter value into R10.
17769 // R10 is specified in X86CallingConv.td
17770 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
17771 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17772 DAG.getConstant(10, dl, MVT::i64));
17773 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17774 Addr, MachinePointerInfo(TrmpAddr, 10),
17777 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17778 DAG.getConstant(12, dl, MVT::i64));
17779 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
17780 MachinePointerInfo(TrmpAddr, 12),
17783 // Jump to the nested function.
17784 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
17785 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17786 DAG.getConstant(20, dl, MVT::i64));
17787 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17788 Addr, MachinePointerInfo(TrmpAddr, 20),
17791 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
17792 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17793 DAG.getConstant(22, dl, MVT::i64));
17794 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
17795 Addr, MachinePointerInfo(TrmpAddr, 22),
17798 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17800 const Function *Func =
17801 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
17802 CallingConv::ID CC = Func->getCallingConv();
17807 llvm_unreachable("Unsupported calling convention");
17808 case CallingConv::C:
17809 case CallingConv::X86_StdCall: {
17810 // Pass 'nest' parameter in ECX.
17811 // Must be kept in sync with X86CallingConv.td
17812 NestReg = X86::ECX;
17814 // Check that ECX wasn't needed by an 'inreg' parameter.
17815 FunctionType *FTy = Func->getFunctionType();
17816 const AttributeSet &Attrs = Func->getAttributes();
17818 if (!Attrs.isEmpty() && !Func->isVarArg()) {
17819 unsigned InRegCount = 0;
17822 for (FunctionType::param_iterator I = FTy->param_begin(),
17823 E = FTy->param_end(); I != E; ++I, ++Idx)
17824 if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
17825 auto &DL = DAG.getDataLayout();
17826 // FIXME: should only count parameters that are lowered to integers.
17827 InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
17830 if (InRegCount > 2) {
17831 report_fatal_error("Nest register in use - reduce number of inreg"
17837 case CallingConv::X86_FastCall:
17838 case CallingConv::X86_ThisCall:
17839 case CallingConv::Fast:
17840 // Pass 'nest' parameter in EAX.
17841 // Must be kept in sync with X86CallingConv.td
17842 NestReg = X86::EAX;
17846 SDValue OutChains[4];
17847 SDValue Addr, Disp;
17849 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17850 DAG.getConstant(10, dl, MVT::i32));
17851 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
17853 // This is storing the opcode for MOV32ri.
17854 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
17855 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
17856 OutChains[0] = DAG.getStore(Root, dl,
17857 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
17858 Trmp, MachinePointerInfo(TrmpAddr),
17861 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17862 DAG.getConstant(1, dl, MVT::i32));
17863 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
17864 MachinePointerInfo(TrmpAddr, 1),
17867 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
17868 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17869 DAG.getConstant(5, dl, MVT::i32));
17870 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
17871 Addr, MachinePointerInfo(TrmpAddr, 5),
17874 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17875 DAG.getConstant(6, dl, MVT::i32));
17876 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
17877 MachinePointerInfo(TrmpAddr, 6),
17880 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17884 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
17885 SelectionDAG &DAG) const {
17887 The rounding mode is in bits 11:10 of FPSR, and has the following
17889 00 Round to nearest
17894 FLT_ROUNDS, on the other hand, expects the following:
17901 To perform the conversion, we do:
17902 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
17905 MachineFunction &MF = DAG.getMachineFunction();
17906 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17907 unsigned StackAlignment = TFI.getStackAlignment();
17908 MVT VT = Op.getSimpleValueType();
17911 // Save FP Control Word to stack slot
17912 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
17913 SDValue StackSlot =
17914 DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
17916 MachineMemOperand *MMO =
17917 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
17918 MachineMemOperand::MOStore, 2, 2);
17920 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
17921 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
17922 DAG.getVTList(MVT::Other),
17923 Ops, MVT::i16, MMO);
17925 // Load FP Control Word from stack slot
17926 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
17927 MachinePointerInfo(), false, false, false, 0);
17929 // Transform as necessary
17931 DAG.getNode(ISD::SRL, DL, MVT::i16,
17932 DAG.getNode(ISD::AND, DL, MVT::i16,
17933 CWD, DAG.getConstant(0x800, DL, MVT::i16)),
17934 DAG.getConstant(11, DL, MVT::i8));
17936 DAG.getNode(ISD::SRL, DL, MVT::i16,
17937 DAG.getNode(ISD::AND, DL, MVT::i16,
17938 CWD, DAG.getConstant(0x400, DL, MVT::i16)),
17939 DAG.getConstant(9, DL, MVT::i8));
17942 DAG.getNode(ISD::AND, DL, MVT::i16,
17943 DAG.getNode(ISD::ADD, DL, MVT::i16,
17944 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
17945 DAG.getConstant(1, DL, MVT::i16)),
17946 DAG.getConstant(3, DL, MVT::i16));
17948 return DAG.getNode((VT.getSizeInBits() < 16 ?
17949 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
17952 /// \brief Lower a vector CTLZ using native supported vector CTLZ instruction.
17954 // 1. i32/i64 128/256-bit vector (native support require VLX) are expended
17955 // to 512-bit vector.
17956 // 2. i8/i16 vector implemented using dword LZCNT vector instruction
17957 // ( sub(trunc(lzcnt(zext32(x)))) ). In case zext32(x) is illegal,
17958 // split the vector, perform operation on it's Lo a Hi part and
17959 // concatenate the results.
17960 static SDValue LowerVectorCTLZ_AVX512(SDValue Op, SelectionDAG &DAG) {
17962 MVT VT = Op.getSimpleValueType();
17963 MVT EltVT = VT.getVectorElementType();
17964 unsigned NumElems = VT.getVectorNumElements();
17966 if (EltVT == MVT::i64 || EltVT == MVT::i32) {
17967 // Extend to 512 bit vector.
17968 assert((VT.is256BitVector() || VT.is128BitVector()) &&
17969 "Unsupported value type for operation");
17971 MVT NewVT = MVT::getVectorVT(EltVT, 512 / VT.getScalarSizeInBits());
17972 SDValue Vec512 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, NewVT,
17973 DAG.getUNDEF(NewVT),
17975 DAG.getIntPtrConstant(0, dl));
17976 SDValue CtlzNode = DAG.getNode(ISD::CTLZ, dl, NewVT, Vec512);
17978 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, CtlzNode,
17979 DAG.getIntPtrConstant(0, dl));
17982 assert((EltVT == MVT::i8 || EltVT == MVT::i16) &&
17983 "Unsupported element type");
17985 if (16 < NumElems) {
17986 // Split vector, it's Lo and Hi parts will be handled in next iteration.
17988 std::tie(Lo, Hi) = DAG.SplitVector(Op.getOperand(0), dl);
17989 MVT OutVT = MVT::getVectorVT(EltVT, NumElems/2);
17991 Lo = DAG.getNode(Op.getOpcode(), dl, OutVT, Lo);
17992 Hi = DAG.getNode(Op.getOpcode(), dl, OutVT, Hi);
17994 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
17997 MVT NewVT = MVT::getVectorVT(MVT::i32, NumElems);
17999 assert((NewVT.is256BitVector() || NewVT.is512BitVector()) &&
18000 "Unsupported value type for operation");
18002 // Use native supported vector instruction vplzcntd.
18003 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, NewVT, Op.getOperand(0));
18004 SDValue CtlzNode = DAG.getNode(ISD::CTLZ, dl, NewVT, Op);
18005 SDValue TruncNode = DAG.getNode(ISD::TRUNCATE, dl, VT, CtlzNode);
18006 SDValue Delta = DAG.getConstant(32 - EltVT.getSizeInBits(), dl, VT);
18008 return DAG.getNode(ISD::SUB, dl, VT, TruncNode, Delta);
18011 static SDValue LowerCTLZ(SDValue Op, const X86Subtarget *Subtarget,
18012 SelectionDAG &DAG) {
18013 MVT VT = Op.getSimpleValueType();
18015 unsigned NumBits = VT.getSizeInBits();
18018 if (VT.isVector() && Subtarget->hasAVX512())
18019 return LowerVectorCTLZ_AVX512(Op, DAG);
18021 Op = Op.getOperand(0);
18022 if (VT == MVT::i8) {
18023 // Zero extend to i32 since there is not an i8 bsr.
18025 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
18028 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
18029 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
18030 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
18032 // If src is zero (i.e. bsr sets ZF), returns NumBits.
18035 DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
18036 DAG.getConstant(X86::COND_E, dl, MVT::i8),
18039 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
18041 // Finally xor with NumBits-1.
18042 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
18043 DAG.getConstant(NumBits - 1, dl, OpVT));
18046 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
18050 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, const X86Subtarget *Subtarget,
18051 SelectionDAG &DAG) {
18052 MVT VT = Op.getSimpleValueType();
18054 unsigned NumBits = VT.getSizeInBits();
18057 Op = Op.getOperand(0);
18058 if (VT == MVT::i8) {
18059 // Zero extend to i32 since there is not an i8 bsr.
18061 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
18064 // Issue a bsr (scan bits in reverse).
18065 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
18066 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
18068 // And xor with NumBits-1.
18069 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
18070 DAG.getConstant(NumBits - 1, dl, OpVT));
18073 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
18077 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
18078 MVT VT = Op.getSimpleValueType();
18079 unsigned NumBits = VT.getScalarSizeInBits();
18082 if (VT.isVector()) {
18083 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18085 SDValue N0 = Op.getOperand(0);
18086 SDValue Zero = DAG.getConstant(0, dl, VT);
18088 // lsb(x) = (x & -x)
18089 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, N0,
18090 DAG.getNode(ISD::SUB, dl, VT, Zero, N0));
18092 // cttz_undef(x) = (width - 1) - ctlz(lsb)
18093 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF &&
18094 TLI.isOperationLegal(ISD::CTLZ, VT)) {
18095 SDValue WidthMinusOne = DAG.getConstant(NumBits - 1, dl, VT);
18096 return DAG.getNode(ISD::SUB, dl, VT, WidthMinusOne,
18097 DAG.getNode(ISD::CTLZ, dl, VT, LSB));
18100 // cttz(x) = ctpop(lsb - 1)
18101 SDValue One = DAG.getConstant(1, dl, VT);
18102 return DAG.getNode(ISD::CTPOP, dl, VT,
18103 DAG.getNode(ISD::SUB, dl, VT, LSB, One));
18106 assert(Op.getOpcode() == ISD::CTTZ &&
18107 "Only scalar CTTZ requires custom lowering");
18109 // Issue a bsf (scan bits forward) which also sets EFLAGS.
18110 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18111 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op.getOperand(0));
18113 // If src is zero (i.e. bsf sets ZF), returns NumBits.
18116 DAG.getConstant(NumBits, dl, VT),
18117 DAG.getConstant(X86::COND_E, dl, MVT::i8),
18120 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
18123 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
18124 // ones, and then concatenate the result back.
18125 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
18126 MVT VT = Op.getSimpleValueType();
18128 assert(VT.is256BitVector() && VT.isInteger() &&
18129 "Unsupported value type for operation");
18131 unsigned NumElems = VT.getVectorNumElements();
18134 // Extract the LHS vectors
18135 SDValue LHS = Op.getOperand(0);
18136 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
18137 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
18139 // Extract the RHS vectors
18140 SDValue RHS = Op.getOperand(1);
18141 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
18142 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
18144 MVT EltVT = VT.getVectorElementType();
18145 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18147 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
18148 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
18149 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
18152 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
18153 if (Op.getValueType() == MVT::i1)
18154 return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
18155 Op.getOperand(0), Op.getOperand(1));
18156 assert(Op.getSimpleValueType().is256BitVector() &&
18157 Op.getSimpleValueType().isInteger() &&
18158 "Only handle AVX 256-bit vector integer operation");
18159 return Lower256IntArith(Op, DAG);
18162 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
18163 if (Op.getValueType() == MVT::i1)
18164 return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
18165 Op.getOperand(0), Op.getOperand(1));
18166 assert(Op.getSimpleValueType().is256BitVector() &&
18167 Op.getSimpleValueType().isInteger() &&
18168 "Only handle AVX 256-bit vector integer operation");
18169 return Lower256IntArith(Op, DAG);
18172 static SDValue LowerMINMAX(SDValue Op, SelectionDAG &DAG) {
18173 assert(Op.getSimpleValueType().is256BitVector() &&
18174 Op.getSimpleValueType().isInteger() &&
18175 "Only handle AVX 256-bit vector integer operation");
18176 return Lower256IntArith(Op, DAG);
18179 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
18180 SelectionDAG &DAG) {
18182 MVT VT = Op.getSimpleValueType();
18185 return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
18187 // Decompose 256-bit ops into smaller 128-bit ops.
18188 if (VT.is256BitVector() && !Subtarget->hasInt256())
18189 return Lower256IntArith(Op, DAG);
18191 SDValue A = Op.getOperand(0);
18192 SDValue B = Op.getOperand(1);
18194 // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
18195 // pairs, multiply and truncate.
18196 if (VT == MVT::v16i8 || VT == MVT::v32i8) {
18197 if (Subtarget->hasInt256()) {
18198 if (VT == MVT::v32i8) {
18199 MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
18200 SDValue Lo = DAG.getIntPtrConstant(0, dl);
18201 SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
18202 SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
18203 SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
18204 SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
18205 SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
18206 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
18207 DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
18208 DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
18211 MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
18212 return DAG.getNode(
18213 ISD::TRUNCATE, dl, VT,
18214 DAG.getNode(ISD::MUL, dl, ExVT,
18215 DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
18216 DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
18219 assert(VT == MVT::v16i8 &&
18220 "Pre-AVX2 support only supports v16i8 multiplication");
18221 MVT ExVT = MVT::v8i16;
18223 // Extract the lo parts and sign extend to i16
18225 if (Subtarget->hasSSE41()) {
18226 ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
18227 BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
18229 const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
18230 -1, 4, -1, 5, -1, 6, -1, 7};
18231 ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
18232 BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
18233 ALo = DAG.getBitcast(ExVT, ALo);
18234 BLo = DAG.getBitcast(ExVT, BLo);
18235 ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
18236 BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
18239 // Extract the hi parts and sign extend to i16
18241 if (Subtarget->hasSSE41()) {
18242 const int ShufMask[] = {8, 9, 10, 11, 12, 13, 14, 15,
18243 -1, -1, -1, -1, -1, -1, -1, -1};
18244 AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
18245 BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
18246 AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
18247 BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
18249 const int ShufMask[] = {-1, 8, -1, 9, -1, 10, -1, 11,
18250 -1, 12, -1, 13, -1, 14, -1, 15};
18251 AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
18252 BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
18253 AHi = DAG.getBitcast(ExVT, AHi);
18254 BHi = DAG.getBitcast(ExVT, BHi);
18255 AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
18256 BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
18259 // Multiply, mask the lower 8bits of the lo/hi results and pack
18260 SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
18261 SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
18262 RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
18263 RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
18264 return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
18267 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
18268 if (VT == MVT::v4i32) {
18269 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
18270 "Should not custom lower when pmuldq is available!");
18272 // Extract the odd parts.
18273 static const int UnpackMask[] = { 1, -1, 3, -1 };
18274 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
18275 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
18277 // Multiply the even parts.
18278 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
18279 // Now multiply odd parts.
18280 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
18282 Evens = DAG.getBitcast(VT, Evens);
18283 Odds = DAG.getBitcast(VT, Odds);
18285 // Merge the two vectors back together with a shuffle. This expands into 2
18287 static const int ShufMask[] = { 0, 4, 2, 6 };
18288 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
18291 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
18292 "Only know how to lower V2I64/V4I64/V8I64 multiply");
18294 // Ahi = psrlqi(a, 32);
18295 // Bhi = psrlqi(b, 32);
18297 // AloBlo = pmuludq(a, b);
18298 // AloBhi = pmuludq(a, Bhi);
18299 // AhiBlo = pmuludq(Ahi, b);
18301 // AloBhi = psllqi(AloBhi, 32);
18302 // AhiBlo = psllqi(AhiBlo, 32);
18303 // return AloBlo + AloBhi + AhiBlo;
18305 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
18306 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
18308 SDValue AhiBlo = Ahi;
18309 SDValue AloBhi = Bhi;
18310 // Bit cast to 32-bit vectors for MULUDQ
18311 MVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
18312 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
18313 A = DAG.getBitcast(MulVT, A);
18314 B = DAG.getBitcast(MulVT, B);
18315 Ahi = DAG.getBitcast(MulVT, Ahi);
18316 Bhi = DAG.getBitcast(MulVT, Bhi);
18318 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
18319 // After shifting right const values the result may be all-zero.
18320 if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
18321 AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
18322 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
18324 if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
18325 AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
18326 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
18329 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
18330 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
18333 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
18334 assert(Subtarget->isTargetWin64() && "Unexpected target");
18335 EVT VT = Op.getValueType();
18336 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
18337 "Unexpected return type for lowering");
18341 switch (Op->getOpcode()) {
18342 default: llvm_unreachable("Unexpected request for libcall!");
18343 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
18344 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
18345 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
18346 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
18347 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
18348 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
18352 SDValue InChain = DAG.getEntryNode();
18354 TargetLowering::ArgListTy Args;
18355 TargetLowering::ArgListEntry Entry;
18356 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
18357 EVT ArgVT = Op->getOperand(i).getValueType();
18358 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
18359 "Unexpected argument type for lowering");
18360 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
18361 Entry.Node = StackPtr;
18362 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
18364 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18365 Entry.Ty = PointerType::get(ArgTy,0);
18366 Entry.isSExt = false;
18367 Entry.isZExt = false;
18368 Args.push_back(Entry);
18371 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
18372 getPointerTy(DAG.getDataLayout()));
18374 TargetLowering::CallLoweringInfo CLI(DAG);
18375 CLI.setDebugLoc(dl).setChain(InChain)
18376 .setCallee(getLibcallCallingConv(LC),
18377 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
18378 Callee, std::move(Args), 0)
18379 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
18381 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
18382 return DAG.getBitcast(VT, CallInfo.first);
18385 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
18386 SelectionDAG &DAG) {
18387 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
18388 MVT VT = Op0.getSimpleValueType();
18391 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
18392 (VT == MVT::v8i32 && Subtarget->hasInt256()));
18394 // PMULxD operations multiply each even value (starting at 0) of LHS with
18395 // the related value of RHS and produce a widen result.
18396 // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
18397 // => <2 x i64> <ae|cg>
18399 // In other word, to have all the results, we need to perform two PMULxD:
18400 // 1. one with the even values.
18401 // 2. one with the odd values.
18402 // To achieve #2, with need to place the odd values at an even position.
18404 // Place the odd value at an even position (basically, shift all values 1
18405 // step to the left):
18406 const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
18407 // <a|b|c|d> => <b|undef|d|undef>
18408 SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
18409 // <e|f|g|h> => <f|undef|h|undef>
18410 SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
18412 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
18414 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
18415 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
18417 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
18418 // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
18419 // => <2 x i64> <ae|cg>
18420 SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
18421 // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
18422 // => <2 x i64> <bf|dh>
18423 SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
18425 // Shuffle it back into the right order.
18426 SDValue Highs, Lows;
18427 if (VT == MVT::v8i32) {
18428 const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
18429 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
18430 const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
18431 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
18433 const int HighMask[] = {1, 5, 3, 7};
18434 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
18435 const int LowMask[] = {0, 4, 2, 6};
18436 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
18439 // If we have a signed multiply but no PMULDQ fix up the high parts of a
18440 // unsigned multiply.
18441 if (IsSigned && !Subtarget->hasSSE41()) {
18442 SDValue ShAmt = DAG.getConstant(
18444 DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
18445 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
18446 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
18447 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
18448 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
18450 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
18451 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
18454 // The first result of MUL_LOHI is actually the low value, followed by the
18456 SDValue Ops[] = {Lows, Highs};
18457 return DAG.getMergeValues(Ops, dl);
18460 // Return true if the required (according to Opcode) shift-imm form is natively
18461 // supported by the Subtarget
18462 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
18464 if (VT.getScalarSizeInBits() < 16)
18467 if (VT.is512BitVector() &&
18468 (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
18471 bool LShift = VT.is128BitVector() ||
18472 (VT.is256BitVector() && Subtarget->hasInt256());
18474 bool AShift = LShift && (Subtarget->hasVLX() ||
18475 (VT != MVT::v2i64 && VT != MVT::v4i64));
18476 return (Opcode == ISD::SRA) ? AShift : LShift;
18479 // The shift amount is a variable, but it is the same for all vector lanes.
18480 // These instructions are defined together with shift-immediate.
18482 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
18484 return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
18487 // Return true if the required (according to Opcode) variable-shift form is
18488 // natively supported by the Subtarget
18489 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
18492 if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
18495 // vXi16 supported only on AVX-512, BWI
18496 if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
18499 if (VT.is512BitVector() || Subtarget->hasVLX())
18502 bool LShift = VT.is128BitVector() || VT.is256BitVector();
18503 bool AShift = LShift && VT != MVT::v2i64 && VT != MVT::v4i64;
18504 return (Opcode == ISD::SRA) ? AShift : LShift;
18507 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
18508 const X86Subtarget *Subtarget) {
18509 MVT VT = Op.getSimpleValueType();
18511 SDValue R = Op.getOperand(0);
18512 SDValue Amt = Op.getOperand(1);
18514 unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
18515 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
18517 auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
18518 assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
18519 MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
18520 SDValue Ex = DAG.getBitcast(ExVT, R);
18522 if (ShiftAmt >= 32) {
18523 // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
18525 getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
18526 SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
18527 ShiftAmt - 32, DAG);
18528 if (VT == MVT::v2i64)
18529 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
18530 if (VT == MVT::v4i64)
18531 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
18532 {9, 1, 11, 3, 13, 5, 15, 7});
18534 // SRA upper i32, SHL whole i64 and select lower i32.
18535 SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
18538 getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
18539 Lower = DAG.getBitcast(ExVT, Lower);
18540 if (VT == MVT::v2i64)
18541 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
18542 if (VT == MVT::v4i64)
18543 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
18544 {8, 1, 10, 3, 12, 5, 14, 7});
18546 return DAG.getBitcast(VT, Ex);
18549 // Optimize shl/srl/sra with constant shift amount.
18550 if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
18551 if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
18552 uint64_t ShiftAmt = ShiftConst->getZExtValue();
18554 if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
18555 return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
18557 // i64 SRA needs to be performed as partial shifts.
18558 if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
18559 Op.getOpcode() == ISD::SRA && !Subtarget->hasXOP())
18560 return ArithmeticShiftRight64(ShiftAmt);
18562 if (VT == MVT::v16i8 ||
18563 (Subtarget->hasInt256() && VT == MVT::v32i8) ||
18564 VT == MVT::v64i8) {
18565 unsigned NumElts = VT.getVectorNumElements();
18566 MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
18568 // Simple i8 add case
18569 if (Op.getOpcode() == ISD::SHL && ShiftAmt == 1)
18570 return DAG.getNode(ISD::ADD, dl, VT, R, R);
18572 // ashr(R, 7) === cmp_slt(R, 0)
18573 if (Op.getOpcode() == ISD::SRA && ShiftAmt == 7) {
18574 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18575 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
18578 // XOP can shift v16i8 directly instead of as shift v8i16 + mask.
18579 if (VT == MVT::v16i8 && Subtarget->hasXOP())
18582 if (Op.getOpcode() == ISD::SHL) {
18583 // Make a large shift.
18584 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
18586 SHL = DAG.getBitcast(VT, SHL);
18587 // Zero out the rightmost bits.
18588 return DAG.getNode(ISD::AND, dl, VT, SHL,
18589 DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, VT));
18591 if (Op.getOpcode() == ISD::SRL) {
18592 // Make a large shift.
18593 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
18595 SRL = DAG.getBitcast(VT, SRL);
18596 // Zero out the leftmost bits.
18597 return DAG.getNode(ISD::AND, dl, VT, SRL,
18598 DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, VT));
18600 if (Op.getOpcode() == ISD::SRA) {
18601 // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
18602 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18604 SDValue Mask = DAG.getConstant(128 >> ShiftAmt, dl, VT);
18605 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
18606 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
18609 llvm_unreachable("Unknown shift opcode.");
18614 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18615 if (!Subtarget->is64Bit() && !Subtarget->hasXOP() &&
18616 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64))) {
18618 // Peek through any splat that was introduced for i64 shift vectorization.
18619 int SplatIndex = -1;
18620 if (ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt.getNode()))
18621 if (SVN->isSplat()) {
18622 SplatIndex = SVN->getSplatIndex();
18623 Amt = Amt.getOperand(0);
18624 assert(SplatIndex < (int)VT.getVectorNumElements() &&
18625 "Splat shuffle referencing second operand");
18628 if (Amt.getOpcode() != ISD::BITCAST ||
18629 Amt.getOperand(0).getOpcode() != ISD::BUILD_VECTOR)
18632 Amt = Amt.getOperand(0);
18633 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18634 VT.getVectorNumElements();
18635 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
18636 uint64_t ShiftAmt = 0;
18637 unsigned BaseOp = (SplatIndex < 0 ? 0 : SplatIndex * Ratio);
18638 for (unsigned i = 0; i != Ratio; ++i) {
18639 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + BaseOp));
18643 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
18646 // Check remaining shift amounts (if not a splat).
18647 if (SplatIndex < 0) {
18648 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18649 uint64_t ShAmt = 0;
18650 for (unsigned j = 0; j != Ratio; ++j) {
18651 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
18655 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
18657 if (ShAmt != ShiftAmt)
18662 if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
18663 return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
18665 if (Op.getOpcode() == ISD::SRA)
18666 return ArithmeticShiftRight64(ShiftAmt);
18672 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
18673 const X86Subtarget* Subtarget) {
18674 MVT VT = Op.getSimpleValueType();
18676 SDValue R = Op.getOperand(0);
18677 SDValue Amt = Op.getOperand(1);
18679 unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
18680 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
18682 unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
18683 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
18685 if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
18687 MVT EltVT = VT.getVectorElementType();
18689 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
18690 // Check if this build_vector node is doing a splat.
18691 // If so, then set BaseShAmt equal to the splat value.
18692 BaseShAmt = BV->getSplatValue();
18693 if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
18694 BaseShAmt = SDValue();
18696 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
18697 Amt = Amt.getOperand(0);
18699 ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
18700 if (SVN && SVN->isSplat()) {
18701 unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
18702 SDValue InVec = Amt.getOperand(0);
18703 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
18704 assert((SplatIdx < InVec.getSimpleValueType().getVectorNumElements()) &&
18705 "Unexpected shuffle index found!");
18706 BaseShAmt = InVec.getOperand(SplatIdx);
18707 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
18708 if (ConstantSDNode *C =
18709 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
18710 if (C->getZExtValue() == SplatIdx)
18711 BaseShAmt = InVec.getOperand(1);
18716 // Avoid introducing an extract element from a shuffle.
18717 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
18718 DAG.getIntPtrConstant(SplatIdx, dl));
18722 if (BaseShAmt.getNode()) {
18723 assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
18724 if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
18725 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
18726 else if (EltVT.bitsLT(MVT::i32))
18727 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
18729 return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
18733 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18734 if (!Subtarget->is64Bit() && VT == MVT::v2i64 &&
18735 Amt.getOpcode() == ISD::BITCAST &&
18736 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
18737 Amt = Amt.getOperand(0);
18738 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18739 VT.getVectorNumElements();
18740 std::vector<SDValue> Vals(Ratio);
18741 for (unsigned i = 0; i != Ratio; ++i)
18742 Vals[i] = Amt.getOperand(i);
18743 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18744 for (unsigned j = 0; j != Ratio; ++j)
18745 if (Vals[j] != Amt.getOperand(i + j))
18749 if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
18750 return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
18755 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
18756 SelectionDAG &DAG) {
18757 MVT VT = Op.getSimpleValueType();
18759 SDValue R = Op.getOperand(0);
18760 SDValue Amt = Op.getOperand(1);
18762 assert(VT.isVector() && "Custom lowering only for vector shifts!");
18763 assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
18765 if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
18768 if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
18771 if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
18774 // XOP has 128-bit variable logical/arithmetic shifts.
18775 // +ve/-ve Amt = shift left/right.
18776 if (Subtarget->hasXOP() &&
18777 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
18778 VT == MVT::v8i16 || VT == MVT::v16i8)) {
18779 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SRA) {
18780 SDValue Zero = getZeroVector(VT, Subtarget, DAG, dl);
18781 Amt = DAG.getNode(ISD::SUB, dl, VT, Zero, Amt);
18783 if (Op.getOpcode() == ISD::SHL || Op.getOpcode() == ISD::SRL)
18784 return DAG.getNode(X86ISD::VPSHL, dl, VT, R, Amt);
18785 if (Op.getOpcode() == ISD::SRA)
18786 return DAG.getNode(X86ISD::VPSHA, dl, VT, R, Amt);
18789 // 2i64 vector logical shifts can efficiently avoid scalarization - do the
18790 // shifts per-lane and then shuffle the partial results back together.
18791 if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
18792 // Splat the shift amounts so the scalar shifts above will catch it.
18793 SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
18794 SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
18795 SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
18796 SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
18797 return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
18800 // i64 vector arithmetic shift can be emulated with the transform:
18801 // M = lshr(SIGN_BIT, Amt)
18802 // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
18803 if ((VT == MVT::v2i64 || (VT == MVT::v4i64 && Subtarget->hasInt256())) &&
18804 Op.getOpcode() == ISD::SRA) {
18805 SDValue S = DAG.getConstant(APInt::getSignBit(64), dl, VT);
18806 SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
18807 R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18808 R = DAG.getNode(ISD::XOR, dl, VT, R, M);
18809 R = DAG.getNode(ISD::SUB, dl, VT, R, M);
18813 // If possible, lower this packed shift into a vector multiply instead of
18814 // expanding it into a sequence of scalar shifts.
18815 // Do this only if the vector shift count is a constant build_vector.
18816 if (Op.getOpcode() == ISD::SHL &&
18817 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
18818 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
18819 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18820 SmallVector<SDValue, 8> Elts;
18821 MVT SVT = VT.getVectorElementType();
18822 unsigned SVTBits = SVT.getSizeInBits();
18823 APInt One(SVTBits, 1);
18824 unsigned NumElems = VT.getVectorNumElements();
18826 for (unsigned i=0; i !=NumElems; ++i) {
18827 SDValue Op = Amt->getOperand(i);
18828 if (Op->getOpcode() == ISD::UNDEF) {
18829 Elts.push_back(Op);
18833 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
18834 APInt C(SVTBits, ND->getAPIntValue().getZExtValue());
18835 uint64_t ShAmt = C.getZExtValue();
18836 if (ShAmt >= SVTBits) {
18837 Elts.push_back(DAG.getUNDEF(SVT));
18840 Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
18842 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
18843 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
18846 // Lower SHL with variable shift amount.
18847 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
18848 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
18850 Op = DAG.getNode(ISD::ADD, dl, VT, Op,
18851 DAG.getConstant(0x3f800000U, dl, VT));
18852 Op = DAG.getBitcast(MVT::v4f32, Op);
18853 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
18854 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
18857 // If possible, lower this shift as a sequence of two shifts by
18858 // constant plus a MOVSS/MOVSD instead of scalarizing it.
18860 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
18862 // Could be rewritten as:
18863 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
18865 // The advantage is that the two shifts from the example would be
18866 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
18867 // the vector shift into four scalar shifts plus four pairs of vector
18869 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
18870 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18871 unsigned TargetOpcode = X86ISD::MOVSS;
18872 bool CanBeSimplified;
18873 // The splat value for the first packed shift (the 'X' from the example).
18874 SDValue Amt1 = Amt->getOperand(0);
18875 // The splat value for the second packed shift (the 'Y' from the example).
18876 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
18877 Amt->getOperand(2);
18879 // See if it is possible to replace this node with a sequence of
18880 // two shifts followed by a MOVSS/MOVSD
18881 if (VT == MVT::v4i32) {
18882 // Check if it is legal to use a MOVSS.
18883 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
18884 Amt2 == Amt->getOperand(3);
18885 if (!CanBeSimplified) {
18886 // Otherwise, check if we can still simplify this node using a MOVSD.
18887 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
18888 Amt->getOperand(2) == Amt->getOperand(3);
18889 TargetOpcode = X86ISD::MOVSD;
18890 Amt2 = Amt->getOperand(2);
18893 // Do similar checks for the case where the machine value type
18895 CanBeSimplified = Amt1 == Amt->getOperand(1);
18896 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
18897 CanBeSimplified = Amt2 == Amt->getOperand(i);
18899 if (!CanBeSimplified) {
18900 TargetOpcode = X86ISD::MOVSD;
18901 CanBeSimplified = true;
18902 Amt2 = Amt->getOperand(4);
18903 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
18904 CanBeSimplified = Amt1 == Amt->getOperand(i);
18905 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
18906 CanBeSimplified = Amt2 == Amt->getOperand(j);
18910 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
18911 isa<ConstantSDNode>(Amt2)) {
18912 // Replace this node with two shifts followed by a MOVSS/MOVSD.
18913 MVT CastVT = MVT::v4i32;
18915 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
18916 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
18918 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
18919 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
18920 if (TargetOpcode == X86ISD::MOVSD)
18921 CastVT = MVT::v2i64;
18922 SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
18923 SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
18924 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
18926 return DAG.getBitcast(VT, Result);
18930 // v4i32 Non Uniform Shifts.
18931 // If the shift amount is constant we can shift each lane using the SSE2
18932 // immediate shifts, else we need to zero-extend each lane to the lower i64
18933 // and shift using the SSE2 variable shifts.
18934 // The separate results can then be blended together.
18935 if (VT == MVT::v4i32) {
18936 unsigned Opc = Op.getOpcode();
18937 SDValue Amt0, Amt1, Amt2, Amt3;
18938 if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18939 Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
18940 Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
18941 Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
18942 Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
18944 // ISD::SHL is handled above but we include it here for completeness.
18947 llvm_unreachable("Unknown target vector shift node");
18949 Opc = X86ISD::VSHL;
18952 Opc = X86ISD::VSRL;
18955 Opc = X86ISD::VSRA;
18958 // The SSE2 shifts use the lower i64 as the same shift amount for
18959 // all lanes and the upper i64 is ignored. These shuffle masks
18960 // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
18961 SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
18962 Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
18963 Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
18964 Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
18965 Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
18968 SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
18969 SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
18970 SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
18971 SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
18972 SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
18973 SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
18974 return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
18977 if (VT == MVT::v16i8 ||
18978 (VT == MVT::v32i8 && Subtarget->hasInt256() && !Subtarget->hasXOP())) {
18979 MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
18980 unsigned ShiftOpcode = Op->getOpcode();
18982 auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
18983 // On SSE41 targets we make use of the fact that VSELECT lowers
18984 // to PBLENDVB which selects bytes based just on the sign bit.
18985 if (Subtarget->hasSSE41()) {
18986 V0 = DAG.getBitcast(VT, V0);
18987 V1 = DAG.getBitcast(VT, V1);
18988 Sel = DAG.getBitcast(VT, Sel);
18989 return DAG.getBitcast(SelVT,
18990 DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
18992 // On pre-SSE41 targets we test for the sign bit by comparing to
18993 // zero - a negative value will set all bits of the lanes to true
18994 // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
18995 SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
18996 SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
18997 return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
19000 // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
19001 // We can safely do this using i16 shifts as we're only interested in
19002 // the 3 lower bits of each byte.
19003 Amt = DAG.getBitcast(ExtVT, Amt);
19004 Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
19005 Amt = DAG.getBitcast(VT, Amt);
19007 if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
19008 // r = VSELECT(r, shift(r, 4), a);
19010 DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
19011 R = SignBitSelect(VT, Amt, M, R);
19014 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
19016 // r = VSELECT(r, shift(r, 2), a);
19017 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
19018 R = SignBitSelect(VT, Amt, M, R);
19021 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
19023 // return VSELECT(r, shift(r, 1), a);
19024 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
19025 R = SignBitSelect(VT, Amt, M, R);
19029 if (Op->getOpcode() == ISD::SRA) {
19030 // For SRA we need to unpack each byte to the higher byte of a i16 vector
19031 // so we can correctly sign extend. We don't care what happens to the
19033 SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
19034 SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
19035 SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
19036 SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
19037 ALo = DAG.getBitcast(ExtVT, ALo);
19038 AHi = DAG.getBitcast(ExtVT, AHi);
19039 RLo = DAG.getBitcast(ExtVT, RLo);
19040 RHi = DAG.getBitcast(ExtVT, RHi);
19042 // r = VSELECT(r, shift(r, 4), a);
19043 SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
19044 DAG.getConstant(4, dl, ExtVT));
19045 SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
19046 DAG.getConstant(4, dl, ExtVT));
19047 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
19048 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
19051 ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
19052 AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
19054 // r = VSELECT(r, shift(r, 2), a);
19055 MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
19056 DAG.getConstant(2, dl, ExtVT));
19057 MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
19058 DAG.getConstant(2, dl, ExtVT));
19059 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
19060 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
19063 ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
19064 AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
19066 // r = VSELECT(r, shift(r, 1), a);
19067 MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
19068 DAG.getConstant(1, dl, ExtVT));
19069 MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
19070 DAG.getConstant(1, dl, ExtVT));
19071 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
19072 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
19074 // Logical shift the result back to the lower byte, leaving a zero upper
19076 // meaning that we can safely pack with PACKUSWB.
19078 DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
19080 DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
19081 return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
19085 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
19086 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
19087 // solution better.
19088 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
19089 MVT ExtVT = MVT::v8i32;
19091 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
19092 R = DAG.getNode(ExtOpc, dl, ExtVT, R);
19093 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
19094 return DAG.getNode(ISD::TRUNCATE, dl, VT,
19095 DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
19098 if (Subtarget->hasInt256() && !Subtarget->hasXOP() && VT == MVT::v16i16) {
19099 MVT ExtVT = MVT::v8i32;
19100 SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
19101 SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
19102 SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
19103 SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
19104 SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
19105 ALo = DAG.getBitcast(ExtVT, ALo);
19106 AHi = DAG.getBitcast(ExtVT, AHi);
19107 RLo = DAG.getBitcast(ExtVT, RLo);
19108 RHi = DAG.getBitcast(ExtVT, RHi);
19109 SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
19110 SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
19111 Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
19112 Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
19113 return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
19116 if (VT == MVT::v8i16) {
19117 unsigned ShiftOpcode = Op->getOpcode();
19119 auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
19120 // On SSE41 targets we make use of the fact that VSELECT lowers
19121 // to PBLENDVB which selects bytes based just on the sign bit.
19122 if (Subtarget->hasSSE41()) {
19123 MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
19124 V0 = DAG.getBitcast(ExtVT, V0);
19125 V1 = DAG.getBitcast(ExtVT, V1);
19126 Sel = DAG.getBitcast(ExtVT, Sel);
19127 return DAG.getBitcast(
19128 VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
19130 // On pre-SSE41 targets we splat the sign bit - a negative value will
19131 // set all bits of the lanes to true and VSELECT uses that in
19132 // its OR(AND(V0,C),AND(V1,~C)) lowering.
19134 DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
19135 return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
19138 // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
19139 if (Subtarget->hasSSE41()) {
19140 // On SSE41 targets we need to replicate the shift mask in both
19141 // bytes for PBLENDVB.
19144 DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
19145 DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
19147 Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
19150 // r = VSELECT(r, shift(r, 8), a);
19151 SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
19152 R = SignBitSelect(Amt, M, R);
19155 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
19157 // r = VSELECT(r, shift(r, 4), a);
19158 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
19159 R = SignBitSelect(Amt, M, R);
19162 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
19164 // r = VSELECT(r, shift(r, 2), a);
19165 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
19166 R = SignBitSelect(Amt, M, R);
19169 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
19171 // return VSELECT(r, shift(r, 1), a);
19172 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
19173 R = SignBitSelect(Amt, M, R);
19177 // Decompose 256-bit shifts into smaller 128-bit shifts.
19178 if (VT.is256BitVector()) {
19179 unsigned NumElems = VT.getVectorNumElements();
19180 MVT EltVT = VT.getVectorElementType();
19181 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
19183 // Extract the two vectors
19184 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
19185 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
19187 // Recreate the shift amount vectors
19188 SDValue Amt1, Amt2;
19189 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
19190 // Constant shift amount
19191 SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
19192 ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
19193 ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
19195 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
19196 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
19198 // Variable shift amount
19199 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
19200 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
19203 // Issue new vector shifts for the smaller types
19204 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
19205 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
19207 // Concatenate the result back
19208 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
19214 static SDValue LowerRotate(SDValue Op, const X86Subtarget *Subtarget,
19215 SelectionDAG &DAG) {
19216 MVT VT = Op.getSimpleValueType();
19218 SDValue R = Op.getOperand(0);
19219 SDValue Amt = Op.getOperand(1);
19221 assert(VT.isVector() && "Custom lowering only for vector rotates!");
19222 assert(Subtarget->hasXOP() && "XOP support required for vector rotates!");
19223 assert((Op.getOpcode() == ISD::ROTL) && "Only ROTL supported");
19225 // XOP has 128-bit vector variable + immediate rotates.
19226 // +ve/-ve Amt = rotate left/right.
19228 // Split 256-bit integers.
19229 if (VT.is256BitVector())
19230 return Lower256IntArith(Op, DAG);
19232 assert(VT.is128BitVector() && "Only rotate 128-bit vectors!");
19234 // Attempt to rotate by immediate.
19235 if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
19236 if (auto *RotateConst = BVAmt->getConstantSplatNode()) {
19237 uint64_t RotateAmt = RotateConst->getAPIntValue().getZExtValue();
19238 assert(RotateAmt < VT.getScalarSizeInBits() && "Rotation out of range");
19239 return DAG.getNode(X86ISD::VPROTI, DL, VT, R,
19240 DAG.getConstant(RotateAmt, DL, MVT::i8));
19244 // Use general rotate by variable (per-element).
19245 return DAG.getNode(X86ISD::VPROT, DL, VT, R, Amt);
19248 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
19249 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
19250 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
19251 // looks for this combo and may remove the "setcc" instruction if the "setcc"
19252 // has only one use.
19253 SDNode *N = Op.getNode();
19254 SDValue LHS = N->getOperand(0);
19255 SDValue RHS = N->getOperand(1);
19256 unsigned BaseOp = 0;
19259 switch (Op.getOpcode()) {
19260 default: llvm_unreachable("Unknown ovf instruction!");
19262 // A subtract of one will be selected as a INC. Note that INC doesn't
19263 // set CF, so we can't do this for UADDO.
19264 if (isOneConstant(RHS)) {
19265 BaseOp = X86ISD::INC;
19266 Cond = X86::COND_O;
19269 BaseOp = X86ISD::ADD;
19270 Cond = X86::COND_O;
19273 BaseOp = X86ISD::ADD;
19274 Cond = X86::COND_B;
19277 // A subtract of one will be selected as a DEC. Note that DEC doesn't
19278 // set CF, so we can't do this for USUBO.
19279 if (isOneConstant(RHS)) {
19280 BaseOp = X86ISD::DEC;
19281 Cond = X86::COND_O;
19284 BaseOp = X86ISD::SUB;
19285 Cond = X86::COND_O;
19288 BaseOp = X86ISD::SUB;
19289 Cond = X86::COND_B;
19292 BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
19293 Cond = X86::COND_O;
19295 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
19296 if (N->getValueType(0) == MVT::i8) {
19297 BaseOp = X86ISD::UMUL8;
19298 Cond = X86::COND_O;
19301 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
19303 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
19306 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
19307 DAG.getConstant(X86::COND_O, DL, MVT::i32),
19308 SDValue(Sum.getNode(), 2));
19310 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
19314 // Also sets EFLAGS.
19315 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
19316 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
19319 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
19320 DAG.getConstant(Cond, DL, MVT::i32),
19321 SDValue(Sum.getNode(), 1));
19323 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
19326 /// Returns true if the operand type is exactly twice the native width, and
19327 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
19328 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
19329 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
19330 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
19331 unsigned OpWidth = MemType->getPrimitiveSizeInBits();
19334 return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
19335 else if (OpWidth == 128)
19336 return Subtarget->hasCmpxchg16b();
19341 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
19342 return needsCmpXchgNb(SI->getValueOperand()->getType());
19345 // Note: this turns large loads into lock cmpxchg8b/16b.
19346 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
19347 TargetLowering::AtomicExpansionKind
19348 X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
19349 auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
19350 return needsCmpXchgNb(PTy->getElementType()) ? AtomicExpansionKind::CmpXChg
19351 : AtomicExpansionKind::None;
19354 TargetLowering::AtomicExpansionKind
19355 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
19356 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
19357 Type *MemType = AI->getType();
19359 // If the operand is too big, we must see if cmpxchg8/16b is available
19360 // and default to library calls otherwise.
19361 if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
19362 return needsCmpXchgNb(MemType) ? AtomicExpansionKind::CmpXChg
19363 : AtomicExpansionKind::None;
19366 AtomicRMWInst::BinOp Op = AI->getOperation();
19369 llvm_unreachable("Unknown atomic operation");
19370 case AtomicRMWInst::Xchg:
19371 case AtomicRMWInst::Add:
19372 case AtomicRMWInst::Sub:
19373 // It's better to use xadd, xsub or xchg for these in all cases.
19374 return AtomicExpansionKind::None;
19375 case AtomicRMWInst::Or:
19376 case AtomicRMWInst::And:
19377 case AtomicRMWInst::Xor:
19378 // If the atomicrmw's result isn't actually used, we can just add a "lock"
19379 // prefix to a normal instruction for these operations.
19380 return !AI->use_empty() ? AtomicExpansionKind::CmpXChg
19381 : AtomicExpansionKind::None;
19382 case AtomicRMWInst::Nand:
19383 case AtomicRMWInst::Max:
19384 case AtomicRMWInst::Min:
19385 case AtomicRMWInst::UMax:
19386 case AtomicRMWInst::UMin:
19387 // These always require a non-trivial set of data operations on x86. We must
19388 // use a cmpxchg loop.
19389 return AtomicExpansionKind::CmpXChg;
19393 static bool hasMFENCE(const X86Subtarget& Subtarget) {
19394 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
19395 // no-sse2). There isn't any reason to disable it if the target processor
19397 return Subtarget.hasSSE2() || Subtarget.is64Bit();
19401 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
19402 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
19403 Type *MemType = AI->getType();
19404 // Accesses larger than the native width are turned into cmpxchg/libcalls, so
19405 // there is no benefit in turning such RMWs into loads, and it is actually
19406 // harmful as it introduces a mfence.
19407 if (MemType->getPrimitiveSizeInBits() > NativeWidth)
19410 auto Builder = IRBuilder<>(AI);
19411 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
19412 auto SynchScope = AI->getSynchScope();
19413 // We must restrict the ordering to avoid generating loads with Release or
19414 // ReleaseAcquire orderings.
19415 auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
19416 auto Ptr = AI->getPointerOperand();
19418 // Before the load we need a fence. Here is an example lifted from
19419 // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
19422 // x.store(1, relaxed);
19423 // r1 = y.fetch_add(0, release);
19425 // y.fetch_add(42, acquire);
19426 // r2 = x.load(relaxed);
19427 // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
19428 // lowered to just a load without a fence. A mfence flushes the store buffer,
19429 // making the optimization clearly correct.
19430 // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
19431 // otherwise, we might be able to be more aggressive on relaxed idempotent
19432 // rmw. In practice, they do not look useful, so we don't try to be
19433 // especially clever.
19434 if (SynchScope == SingleThread)
19435 // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
19436 // the IR level, so we must wrap it in an intrinsic.
19439 if (!hasMFENCE(*Subtarget))
19440 // FIXME: it might make sense to use a locked operation here but on a
19441 // different cache-line to prevent cache-line bouncing. In practice it
19442 // is probably a small win, and x86 processors without mfence are rare
19443 // enough that we do not bother.
19447 llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
19448 Builder.CreateCall(MFence, {});
19450 // Finally we can emit the atomic load.
19451 LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
19452 AI->getType()->getPrimitiveSizeInBits());
19453 Loaded->setAtomic(Order, SynchScope);
19454 AI->replaceAllUsesWith(Loaded);
19455 AI->eraseFromParent();
19459 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
19460 SelectionDAG &DAG) {
19462 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
19463 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
19464 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
19465 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
19467 // The only fence that needs an instruction is a sequentially-consistent
19468 // cross-thread fence.
19469 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
19470 if (hasMFENCE(*Subtarget))
19471 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
19473 SDValue Chain = Op.getOperand(0);
19474 SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
19476 DAG.getRegister(X86::ESP, MVT::i32), // Base
19477 DAG.getTargetConstant(1, dl, MVT::i8), // Scale
19478 DAG.getRegister(0, MVT::i32), // Index
19479 DAG.getTargetConstant(0, dl, MVT::i32), // Disp
19480 DAG.getRegister(0, MVT::i32), // Segment.
19484 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
19485 return SDValue(Res, 0);
19488 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
19489 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
19492 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
19493 SelectionDAG &DAG) {
19494 MVT T = Op.getSimpleValueType();
19498 switch(T.SimpleTy) {
19499 default: llvm_unreachable("Invalid value type!");
19500 case MVT::i8: Reg = X86::AL; size = 1; break;
19501 case MVT::i16: Reg = X86::AX; size = 2; break;
19502 case MVT::i32: Reg = X86::EAX; size = 4; break;
19504 assert(Subtarget->is64Bit() && "Node not type legal!");
19505 Reg = X86::RAX; size = 8;
19508 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
19509 Op.getOperand(2), SDValue());
19510 SDValue Ops[] = { cpIn.getValue(0),
19513 DAG.getTargetConstant(size, DL, MVT::i8),
19514 cpIn.getValue(1) };
19515 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19516 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
19517 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
19521 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
19522 SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
19523 MVT::i32, cpOut.getValue(2));
19524 SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
19525 DAG.getConstant(X86::COND_E, DL, MVT::i8),
19528 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
19529 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
19530 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
19534 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
19535 SelectionDAG &DAG) {
19536 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
19537 MVT DstVT = Op.getSimpleValueType();
19539 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
19540 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19541 if (DstVT != MVT::f64)
19542 // This conversion needs to be expanded.
19545 SDValue InVec = Op->getOperand(0);
19547 unsigned NumElts = SrcVT.getVectorNumElements();
19548 MVT SVT = SrcVT.getVectorElementType();
19550 // Widen the vector in input in the case of MVT::v2i32.
19551 // Example: from MVT::v2i32 to MVT::v4i32.
19552 SmallVector<SDValue, 16> Elts;
19553 for (unsigned i = 0, e = NumElts; i != e; ++i)
19554 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
19555 DAG.getIntPtrConstant(i, dl)));
19557 // Explicitly mark the extra elements as Undef.
19558 Elts.append(NumElts, DAG.getUNDEF(SVT));
19560 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19561 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
19562 SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
19563 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
19564 DAG.getIntPtrConstant(0, dl));
19567 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
19568 Subtarget->hasMMX() && "Unexpected custom BITCAST");
19569 assert((DstVT == MVT::i64 ||
19570 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
19571 "Unexpected custom BITCAST");
19572 // i64 <=> MMX conversions are Legal.
19573 if (SrcVT==MVT::i64 && DstVT.isVector())
19575 if (DstVT==MVT::i64 && SrcVT.isVector())
19577 // MMX <=> MMX conversions are Legal.
19578 if (SrcVT.isVector() && DstVT.isVector())
19580 // All other conversions need to be expanded.
19584 /// Compute the horizontal sum of bytes in V for the elements of VT.
19586 /// Requires V to be a byte vector and VT to be an integer vector type with
19587 /// wider elements than V's type. The width of the elements of VT determines
19588 /// how many bytes of V are summed horizontally to produce each element of the
19590 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
19591 const X86Subtarget *Subtarget,
19592 SelectionDAG &DAG) {
19594 MVT ByteVecVT = V.getSimpleValueType();
19595 MVT EltVT = VT.getVectorElementType();
19596 int NumElts = VT.getVectorNumElements();
19597 assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
19598 "Expected value to have byte element type.");
19599 assert(EltVT != MVT::i8 &&
19600 "Horizontal byte sum only makes sense for wider elements!");
19601 unsigned VecSize = VT.getSizeInBits();
19602 assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
19604 // PSADBW instruction horizontally add all bytes and leave the result in i64
19605 // chunks, thus directly computes the pop count for v2i64 and v4i64.
19606 if (EltVT == MVT::i64) {
19607 SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
19608 MVT SadVecVT = MVT::getVectorVT(MVT::i64, VecSize / 64);
19609 V = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT, V, Zeros);
19610 return DAG.getBitcast(VT, V);
19613 if (EltVT == MVT::i32) {
19614 // We unpack the low half and high half into i32s interleaved with zeros so
19615 // that we can use PSADBW to horizontally sum them. The most useful part of
19616 // this is that it lines up the results of two PSADBW instructions to be
19617 // two v2i64 vectors which concatenated are the 4 population counts. We can
19618 // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
19619 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
19620 SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
19621 SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
19623 // Do the horizontal sums into two v2i64s.
19624 Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
19625 MVT SadVecVT = MVT::getVectorVT(MVT::i64, VecSize / 64);
19626 Low = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT,
19627 DAG.getBitcast(ByteVecVT, Low), Zeros);
19628 High = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT,
19629 DAG.getBitcast(ByteVecVT, High), Zeros);
19631 // Merge them together.
19632 MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
19633 V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
19634 DAG.getBitcast(ShortVecVT, Low),
19635 DAG.getBitcast(ShortVecVT, High));
19637 return DAG.getBitcast(VT, V);
19640 // The only element type left is i16.
19641 assert(EltVT == MVT::i16 && "Unknown how to handle type");
19643 // To obtain pop count for each i16 element starting from the pop count for
19644 // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
19645 // right by 8. It is important to shift as i16s as i8 vector shift isn't
19646 // directly supported.
19647 SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
19648 SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
19649 SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
19650 V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
19651 DAG.getBitcast(ByteVecVT, V));
19652 return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
19655 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
19656 const X86Subtarget *Subtarget,
19657 SelectionDAG &DAG) {
19658 MVT VT = Op.getSimpleValueType();
19659 MVT EltVT = VT.getVectorElementType();
19660 unsigned VecSize = VT.getSizeInBits();
19662 // Implement a lookup table in register by using an algorithm based on:
19663 // http://wm.ite.pl/articles/sse-popcount.html
19665 // The general idea is that every lower byte nibble in the input vector is an
19666 // index into a in-register pre-computed pop count table. We then split up the
19667 // input vector in two new ones: (1) a vector with only the shifted-right
19668 // higher nibbles for each byte and (2) a vector with the lower nibbles (and
19669 // masked out higher ones) for each byte. PSHUB is used separately with both
19670 // to index the in-register table. Next, both are added and the result is a
19671 // i8 vector where each element contains the pop count for input byte.
19673 // To obtain the pop count for elements != i8, we follow up with the same
19674 // approach and use additional tricks as described below.
19676 const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
19677 /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
19678 /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
19679 /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
19681 int NumByteElts = VecSize / 8;
19682 MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
19683 SDValue In = DAG.getBitcast(ByteVecVT, Op);
19684 SmallVector<SDValue, 16> LUTVec;
19685 for (int i = 0; i < NumByteElts; ++i)
19686 LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
19687 SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
19688 SmallVector<SDValue, 16> Mask0F(NumByteElts,
19689 DAG.getConstant(0x0F, DL, MVT::i8));
19690 SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
19693 SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
19694 SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
19695 SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
19698 SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
19700 // The input vector is used as the shuffle mask that index elements into the
19701 // LUT. After counting low and high nibbles, add the vector to obtain the
19702 // final pop count per i8 element.
19703 SDValue HighPopCnt =
19704 DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
19705 SDValue LowPopCnt =
19706 DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
19707 SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
19709 if (EltVT == MVT::i8)
19712 return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
19715 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
19716 const X86Subtarget *Subtarget,
19717 SelectionDAG &DAG) {
19718 MVT VT = Op.getSimpleValueType();
19719 assert(VT.is128BitVector() &&
19720 "Only 128-bit vector bitmath lowering supported.");
19722 int VecSize = VT.getSizeInBits();
19723 MVT EltVT = VT.getVectorElementType();
19724 int Len = EltVT.getSizeInBits();
19726 // This is the vectorized version of the "best" algorithm from
19727 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
19728 // with a minor tweak to use a series of adds + shifts instead of vector
19729 // multiplications. Implemented for all integer vector types. We only use
19730 // this when we don't have SSSE3 which allows a LUT-based lowering that is
19731 // much faster, even faster than using native popcnt instructions.
19733 auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
19734 MVT VT = V.getSimpleValueType();
19735 SmallVector<SDValue, 32> Shifters(
19736 VT.getVectorNumElements(),
19737 DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
19738 return DAG.getNode(OpCode, DL, VT, V,
19739 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
19741 auto GetMask = [&](SDValue V, APInt Mask) {
19742 MVT VT = V.getSimpleValueType();
19743 SmallVector<SDValue, 32> Masks(
19744 VT.getVectorNumElements(),
19745 DAG.getConstant(Mask, DL, VT.getVectorElementType()));
19746 return DAG.getNode(ISD::AND, DL, VT, V,
19747 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
19750 // We don't want to incur the implicit masks required to SRL vNi8 vectors on
19751 // x86, so set the SRL type to have elements at least i16 wide. This is
19752 // correct because all of our SRLs are followed immediately by a mask anyways
19753 // that handles any bits that sneak into the high bits of the byte elements.
19754 MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
19758 // v = v - ((v >> 1) & 0x55555555...)
19760 DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
19761 SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
19762 V = DAG.getNode(ISD::SUB, DL, VT, V, And);
19764 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
19765 SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
19766 Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
19767 SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
19768 V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
19770 // v = (v + (v >> 4)) & 0x0F0F0F0F...
19771 Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
19772 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
19773 V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
19775 // At this point, V contains the byte-wise population count, and we are
19776 // merely doing a horizontal sum if necessary to get the wider element
19778 if (EltVT == MVT::i8)
19781 return LowerHorizontalByteSum(
19782 DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
19786 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19787 SelectionDAG &DAG) {
19788 MVT VT = Op.getSimpleValueType();
19789 // FIXME: Need to add AVX-512 support here!
19790 assert((VT.is256BitVector() || VT.is128BitVector()) &&
19791 "Unknown CTPOP type to handle");
19792 SDLoc DL(Op.getNode());
19793 SDValue Op0 = Op.getOperand(0);
19795 if (!Subtarget->hasSSSE3()) {
19796 // We can't use the fast LUT approach, so fall back on vectorized bitmath.
19797 assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
19798 return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
19801 if (VT.is256BitVector() && !Subtarget->hasInt256()) {
19802 unsigned NumElems = VT.getVectorNumElements();
19804 // Extract each 128-bit vector, compute pop count and concat the result.
19805 SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
19806 SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
19808 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
19809 LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
19810 LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
19813 return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
19816 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19817 SelectionDAG &DAG) {
19818 assert(Op.getSimpleValueType().isVector() &&
19819 "We only do custom lowering for vector population count.");
19820 return LowerVectorCTPOP(Op, Subtarget, DAG);
19823 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
19824 SDNode *Node = Op.getNode();
19826 EVT T = Node->getValueType(0);
19827 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
19828 DAG.getConstant(0, dl, T), Node->getOperand(2));
19829 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
19830 cast<AtomicSDNode>(Node)->getMemoryVT(),
19831 Node->getOperand(0),
19832 Node->getOperand(1), negOp,
19833 cast<AtomicSDNode>(Node)->getMemOperand(),
19834 cast<AtomicSDNode>(Node)->getOrdering(),
19835 cast<AtomicSDNode>(Node)->getSynchScope());
19838 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
19839 SDNode *Node = Op.getNode();
19841 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
19843 // Convert seq_cst store -> xchg
19844 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
19845 // FIXME: On 32-bit, store -> fist or movq would be more efficient
19846 // (The only way to get a 16-byte store is cmpxchg16b)
19847 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
19848 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
19849 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
19850 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
19851 cast<AtomicSDNode>(Node)->getMemoryVT(),
19852 Node->getOperand(0),
19853 Node->getOperand(1), Node->getOperand(2),
19854 cast<AtomicSDNode>(Node)->getMemOperand(),
19855 cast<AtomicSDNode>(Node)->getOrdering(),
19856 cast<AtomicSDNode>(Node)->getSynchScope());
19857 return Swap.getValue(1);
19859 // Other atomic stores have a simple pattern.
19863 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
19864 MVT VT = Op.getNode()->getSimpleValueType(0);
19866 // Let legalize expand this if it isn't a legal type yet.
19867 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19870 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
19873 bool ExtraOp = false;
19874 switch (Op.getOpcode()) {
19875 default: llvm_unreachable("Invalid code");
19876 case ISD::ADDC: Opc = X86ISD::ADD; break;
19877 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
19878 case ISD::SUBC: Opc = X86ISD::SUB; break;
19879 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
19883 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19885 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19886 Op.getOperand(1), Op.getOperand(2));
19889 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
19890 SelectionDAG &DAG) {
19891 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
19893 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
19894 // which returns the values as { float, float } (in XMM0) or
19895 // { double, double } (which is returned in XMM0, XMM1).
19897 SDValue Arg = Op.getOperand(0);
19898 EVT ArgVT = Arg.getValueType();
19899 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
19901 TargetLowering::ArgListTy Args;
19902 TargetLowering::ArgListEntry Entry;
19906 Entry.isSExt = false;
19907 Entry.isZExt = false;
19908 Args.push_back(Entry);
19910 bool isF64 = ArgVT == MVT::f64;
19911 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
19912 // the small struct {f32, f32} is returned in (eax, edx). For f64,
19913 // the results are returned via SRet in memory.
19914 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
19915 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19917 DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
19919 Type *RetTy = isF64
19920 ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
19921 : (Type*)VectorType::get(ArgTy, 4);
19923 TargetLowering::CallLoweringInfo CLI(DAG);
19924 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
19925 .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
19927 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
19930 // Returned in xmm0 and xmm1.
19931 return CallResult.first;
19933 // Returned in bits 0:31 and 32:64 xmm0.
19934 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19935 CallResult.first, DAG.getIntPtrConstant(0, dl));
19936 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19937 CallResult.first, DAG.getIntPtrConstant(1, dl));
19938 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
19939 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
19942 /// Widen a vector input to a vector of NVT. The
19943 /// input vector must have the same element type as NVT.
19944 static SDValue ExtendToType(SDValue InOp, MVT NVT, SelectionDAG &DAG,
19945 bool FillWithZeroes = false) {
19946 // Check if InOp already has the right width.
19947 MVT InVT = InOp.getSimpleValueType();
19951 if (InOp.isUndef())
19952 return DAG.getUNDEF(NVT);
19954 assert(InVT.getVectorElementType() == NVT.getVectorElementType() &&
19955 "input and widen element type must match");
19957 unsigned InNumElts = InVT.getVectorNumElements();
19958 unsigned WidenNumElts = NVT.getVectorNumElements();
19959 assert(WidenNumElts > InNumElts && WidenNumElts % InNumElts == 0 &&
19960 "Unexpected request for vector widening");
19962 EVT EltVT = NVT.getVectorElementType();
19965 if (InOp.getOpcode() == ISD::CONCAT_VECTORS &&
19966 InOp.getNumOperands() == 2) {
19967 SDValue N1 = InOp.getOperand(1);
19968 if ((ISD::isBuildVectorAllZeros(N1.getNode()) && FillWithZeroes) ||
19970 InOp = InOp.getOperand(0);
19971 InVT = InOp.getSimpleValueType();
19972 InNumElts = InVT.getVectorNumElements();
19975 if (ISD::isBuildVectorOfConstantSDNodes(InOp.getNode()) ||
19976 ISD::isBuildVectorOfConstantFPSDNodes(InOp.getNode())) {
19977 SmallVector<SDValue, 16> Ops;
19978 for (unsigned i = 0; i < InNumElts; ++i)
19979 Ops.push_back(InOp.getOperand(i));
19981 SDValue FillVal = FillWithZeroes ? DAG.getConstant(0, dl, EltVT) :
19982 DAG.getUNDEF(EltVT);
19983 for (unsigned i = 0; i < WidenNumElts - InNumElts; ++i)
19984 Ops.push_back(FillVal);
19985 return DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Ops);
19987 SDValue FillVal = FillWithZeroes ? DAG.getConstant(0, dl, NVT) :
19989 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, NVT, FillVal,
19990 InOp, DAG.getIntPtrConstant(0, dl));
19993 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
19994 SelectionDAG &DAG) {
19995 assert(Subtarget->hasAVX512() &&
19996 "MGATHER/MSCATTER are supported on AVX-512 arch only");
19998 // X86 scatter kills mask register, so its type should be added to
19999 // the list of return values.
20000 // If the "scatter" has 2 return values, it is already handled.
20001 if (Op.getNode()->getNumValues() == 2)
20004 MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
20005 SDValue Src = N->getValue();
20006 MVT VT = Src.getSimpleValueType();
20007 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
20010 SDValue NewScatter;
20011 SDValue Index = N->getIndex();
20012 SDValue Mask = N->getMask();
20013 SDValue Chain = N->getChain();
20014 SDValue BasePtr = N->getBasePtr();
20015 MVT MemVT = N->getMemoryVT().getSimpleVT();
20016 MVT IndexVT = Index.getSimpleValueType();
20017 MVT MaskVT = Mask.getSimpleValueType();
20019 if (MemVT.getScalarSizeInBits() < VT.getScalarSizeInBits()) {
20020 // The v2i32 value was promoted to v2i64.
20021 // Now we "redo" the type legalizer's work and widen the original
20022 // v2i32 value to v4i32. The original v2i32 is retrieved from v2i64
20024 assert((MemVT == MVT::v2i32 && VT == MVT::v2i64) &&
20025 "Unexpected memory type");
20026 int ShuffleMask[] = {0, 2, -1, -1};
20027 Src = DAG.getVectorShuffle(MVT::v4i32, dl, DAG.getBitcast(MVT::v4i32, Src),
20028 DAG.getUNDEF(MVT::v4i32), ShuffleMask);
20029 // Now we have 4 elements instead of 2.
20030 // Expand the index.
20031 MVT NewIndexVT = MVT::getVectorVT(IndexVT.getScalarType(), 4);
20032 Index = ExtendToType(Index, NewIndexVT, DAG);
20034 // Expand the mask with zeroes
20035 // Mask may be <2 x i64> or <2 x i1> at this moment
20036 assert((MaskVT == MVT::v2i1 || MaskVT == MVT::v2i64) &&
20037 "Unexpected mask type");
20038 MVT ExtMaskVT = MVT::getVectorVT(MaskVT.getScalarType(), 4);
20039 Mask = ExtendToType(Mask, ExtMaskVT, DAG, true);
20043 unsigned NumElts = VT.getVectorNumElements();
20044 if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
20045 !Index.getSimpleValueType().is512BitVector()) {
20046 // AVX512F supports only 512-bit vectors. Or data or index should
20047 // be 512 bit wide. If now the both index and data are 256-bit, but
20048 // the vector contains 8 elements, we just sign-extend the index
20049 if (IndexVT == MVT::v8i32)
20050 // Just extend index
20051 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
20053 // The minimal number of elts in scatter is 8
20056 MVT NewIndexVT = MVT::getVectorVT(IndexVT.getScalarType(), NumElts);
20057 // Use original index here, do not modify the index twice
20058 Index = ExtendToType(N->getIndex(), NewIndexVT, DAG);
20059 if (IndexVT.getScalarType() == MVT::i32)
20060 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
20063 // At this point we have promoted mask operand
20064 assert(MaskVT.getScalarSizeInBits() >= 32 && "unexpected mask type");
20065 MVT ExtMaskVT = MVT::getVectorVT(MaskVT.getScalarType(), NumElts);
20066 // Use the original mask here, do not modify the mask twice
20067 Mask = ExtendToType(N->getMask(), ExtMaskVT, DAG, true);
20069 // The value that should be stored
20070 MVT NewVT = MVT::getVectorVT(VT.getScalarType(), NumElts);
20071 Src = ExtendToType(Src, NewVT, DAG);
20074 // If the mask is "wide" at this point - truncate it to i1 vector
20075 MVT BitMaskVT = MVT::getVectorVT(MVT::i1, NumElts);
20076 Mask = DAG.getNode(ISD::TRUNCATE, dl, BitMaskVT, Mask);
20078 // The mask is killed by scatter, add it to the values
20079 SDVTList VTs = DAG.getVTList(BitMaskVT, MVT::Other);
20080 SDValue Ops[] = {Chain, Src, Mask, BasePtr, Index};
20081 NewScatter = DAG.getMaskedScatter(VTs, N->getMemoryVT(), dl, Ops,
20082 N->getMemOperand());
20083 DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
20084 return SDValue(NewScatter.getNode(), 0);
20087 static SDValue LowerMLOAD(SDValue Op, const X86Subtarget *Subtarget,
20088 SelectionDAG &DAG) {
20090 MaskedLoadSDNode *N = cast<MaskedLoadSDNode>(Op.getNode());
20091 MVT VT = Op.getSimpleValueType();
20092 SDValue Mask = N->getMask();
20095 if (Subtarget->hasAVX512() && !Subtarget->hasVLX() &&
20096 !VT.is512BitVector() && Mask.getValueType() == MVT::v8i1) {
20097 // This operation is legal for targets with VLX, but without
20098 // VLX the vector should be widened to 512 bit
20099 unsigned NumEltsInWideVec = 512/VT.getScalarSizeInBits();
20100 MVT WideDataVT = MVT::getVectorVT(VT.getScalarType(), NumEltsInWideVec);
20101 MVT WideMaskVT = MVT::getVectorVT(MVT::i1, NumEltsInWideVec);
20102 SDValue Src0 = N->getSrc0();
20103 Src0 = ExtendToType(Src0, WideDataVT, DAG);
20104 Mask = ExtendToType(Mask, WideMaskVT, DAG, true);
20105 SDValue NewLoad = DAG.getMaskedLoad(WideDataVT, dl, N->getChain(),
20106 N->getBasePtr(), Mask, Src0,
20107 N->getMemoryVT(), N->getMemOperand(),
20108 N->getExtensionType());
20110 SDValue Exract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
20111 NewLoad.getValue(0),
20112 DAG.getIntPtrConstant(0, dl));
20113 SDValue RetOps[] = {Exract, NewLoad.getValue(1)};
20114 return DAG.getMergeValues(RetOps, dl);
20119 static SDValue LowerMSTORE(SDValue Op, const X86Subtarget *Subtarget,
20120 SelectionDAG &DAG) {
20121 MaskedStoreSDNode *N = cast<MaskedStoreSDNode>(Op.getNode());
20122 SDValue DataToStore = N->getValue();
20123 MVT VT = DataToStore.getSimpleValueType();
20124 SDValue Mask = N->getMask();
20127 if (Subtarget->hasAVX512() && !Subtarget->hasVLX() &&
20128 !VT.is512BitVector() && Mask.getValueType() == MVT::v8i1) {
20129 // This operation is legal for targets with VLX, but without
20130 // VLX the vector should be widened to 512 bit
20131 unsigned NumEltsInWideVec = 512/VT.getScalarSizeInBits();
20132 MVT WideDataVT = MVT::getVectorVT(VT.getScalarType(), NumEltsInWideVec);
20133 MVT WideMaskVT = MVT::getVectorVT(MVT::i1, NumEltsInWideVec);
20134 DataToStore = ExtendToType(DataToStore, WideDataVT, DAG);
20135 Mask = ExtendToType(Mask, WideMaskVT, DAG, true);
20136 return DAG.getMaskedStore(N->getChain(), dl, DataToStore, N->getBasePtr(),
20137 Mask, N->getMemoryVT(), N->getMemOperand(),
20138 N->isTruncatingStore());
20143 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
20144 SelectionDAG &DAG) {
20145 assert(Subtarget->hasAVX512() &&
20146 "MGATHER/MSCATTER are supported on AVX-512 arch only");
20148 MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
20150 MVT VT = Op.getSimpleValueType();
20151 SDValue Index = N->getIndex();
20152 SDValue Mask = N->getMask();
20153 SDValue Src0 = N->getValue();
20154 MVT IndexVT = Index.getSimpleValueType();
20155 MVT MaskVT = Mask.getSimpleValueType();
20157 unsigned NumElts = VT.getVectorNumElements();
20158 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
20160 if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
20161 !Index.getSimpleValueType().is512BitVector()) {
20162 // AVX512F supports only 512-bit vectors. Or data or index should
20163 // be 512 bit wide. If now the both index and data are 256-bit, but
20164 // the vector contains 8 elements, we just sign-extend the index
20165 if (NumElts == 8) {
20166 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
20167 SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
20168 N->getOperand(3), Index };
20169 DAG.UpdateNodeOperands(N, Ops);
20173 // Minimal number of elements in Gather
20176 MVT NewIndexVT = MVT::getVectorVT(IndexVT.getScalarType(), NumElts);
20177 Index = ExtendToType(Index, NewIndexVT, DAG);
20178 if (IndexVT.getScalarType() == MVT::i32)
20179 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
20182 MVT MaskBitVT = MVT::getVectorVT(MVT::i1, NumElts);
20183 // At this point we have promoted mask operand
20184 assert(MaskVT.getScalarSizeInBits() >= 32 && "unexpected mask type");
20185 MVT ExtMaskVT = MVT::getVectorVT(MaskVT.getScalarType(), NumElts);
20186 Mask = ExtendToType(Mask, ExtMaskVT, DAG, true);
20187 Mask = DAG.getNode(ISD::TRUNCATE, dl, MaskBitVT, Mask);
20189 // The pass-thru value
20190 MVT NewVT = MVT::getVectorVT(VT.getScalarType(), NumElts);
20191 Src0 = ExtendToType(Src0, NewVT, DAG);
20193 SDValue Ops[] = { N->getChain(), Src0, Mask, N->getBasePtr(), Index };
20194 SDValue NewGather = DAG.getMaskedGather(DAG.getVTList(NewVT, MVT::Other),
20195 N->getMemoryVT(), dl, Ops,
20196 N->getMemOperand());
20197 SDValue Exract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
20198 NewGather.getValue(0),
20199 DAG.getIntPtrConstant(0, dl));
20200 SDValue RetOps[] = {Exract, NewGather.getValue(1)};
20201 return DAG.getMergeValues(RetOps, dl);
20206 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
20207 SelectionDAG &DAG) const {
20208 // TODO: Eventually, the lowering of these nodes should be informed by or
20209 // deferred to the GC strategy for the function in which they appear. For
20210 // now, however, they must be lowered to something. Since they are logically
20211 // no-ops in the case of a null GC strategy (or a GC strategy which does not
20212 // require special handling for these nodes), lower them as literal NOOPs for
20214 SmallVector<SDValue, 2> Ops;
20216 Ops.push_back(Op.getOperand(0));
20217 if (Op->getGluedNode())
20218 Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
20221 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
20222 SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
20227 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
20228 SelectionDAG &DAG) const {
20229 // TODO: Eventually, the lowering of these nodes should be informed by or
20230 // deferred to the GC strategy for the function in which they appear. For
20231 // now, however, they must be lowered to something. Since they are logically
20232 // no-ops in the case of a null GC strategy (or a GC strategy which does not
20233 // require special handling for these nodes), lower them as literal NOOPs for
20235 SmallVector<SDValue, 2> Ops;
20237 Ops.push_back(Op.getOperand(0));
20238 if (Op->getGluedNode())
20239 Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
20242 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
20243 SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
20248 /// LowerOperation - Provide custom lowering hooks for some operations.
20250 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
20251 switch (Op.getOpcode()) {
20252 default: llvm_unreachable("Should not custom lower this!");
20253 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
20254 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
20255 return LowerCMP_SWAP(Op, Subtarget, DAG);
20256 case ISD::CTPOP: return LowerCTPOP(Op, Subtarget, DAG);
20257 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
20258 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
20259 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
20260 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
20261 case ISD::VECTOR_SHUFFLE: return lowerVectorShuffle(Op, Subtarget, DAG);
20262 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
20263 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
20264 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
20265 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
20266 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
20267 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
20268 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
20269 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
20270 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
20271 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
20272 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
20273 case ISD::SHL_PARTS:
20274 case ISD::SRA_PARTS:
20275 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
20276 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
20277 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
20278 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
20279 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
20280 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
20281 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
20282 case ISD::SIGN_EXTEND_VECTOR_INREG:
20283 return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
20284 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
20285 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
20286 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
20287 case ISD::LOAD: return LowerExtendedLoad(Op, Subtarget, DAG);
20289 case ISD::FNEG: return LowerFABSorFNEG(Op, DAG);
20290 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
20291 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
20292 case ISD::SETCC: return LowerSETCC(Op, DAG);
20293 case ISD::SETCCE: return LowerSETCCE(Op, DAG);
20294 case ISD::SELECT: return LowerSELECT(Op, DAG);
20295 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
20296 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
20297 case ISD::VASTART: return LowerVASTART(Op, DAG);
20298 case ISD::VAARG: return LowerVAARG(Op, DAG);
20299 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
20300 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
20301 case ISD::INTRINSIC_VOID:
20302 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
20303 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
20304 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
20305 case ISD::FRAME_TO_ARGS_OFFSET:
20306 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
20307 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
20308 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
20309 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
20310 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
20311 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
20312 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
20313 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
20314 case ISD::CTLZ: return LowerCTLZ(Op, Subtarget, DAG);
20315 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, Subtarget, DAG);
20317 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op, DAG);
20318 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
20319 case ISD::UMUL_LOHI:
20320 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
20321 case ISD::ROTL: return LowerRotate(Op, Subtarget, DAG);
20324 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
20330 case ISD::UMULO: return LowerXALUO(Op, DAG);
20331 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
20332 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
20336 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
20337 case ISD::ADD: return LowerADD(Op, DAG);
20338 case ISD::SUB: return LowerSUB(Op, DAG);
20342 case ISD::UMIN: return LowerMINMAX(Op, DAG);
20343 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
20344 case ISD::MLOAD: return LowerMLOAD(Op, Subtarget, DAG);
20345 case ISD::MSTORE: return LowerMSTORE(Op, Subtarget, DAG);
20346 case ISD::MGATHER: return LowerMGATHER(Op, Subtarget, DAG);
20347 case ISD::MSCATTER: return LowerMSCATTER(Op, Subtarget, DAG);
20348 case ISD::GC_TRANSITION_START:
20349 return LowerGC_TRANSITION_START(Op, DAG);
20350 case ISD::GC_TRANSITION_END: return LowerGC_TRANSITION_END(Op, DAG);
20354 /// ReplaceNodeResults - Replace a node with an illegal result type
20355 /// with a new node built out of custom code.
20356 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
20357 SmallVectorImpl<SDValue>&Results,
20358 SelectionDAG &DAG) const {
20360 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20361 switch (N->getOpcode()) {
20363 llvm_unreachable("Do not know how to custom type legalize this operation!");
20364 case X86ISD::AVG: {
20365 // Legalize types for X86ISD::AVG by expanding vectors.
20366 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
20368 auto InVT = N->getValueType(0);
20369 auto InVTSize = InVT.getSizeInBits();
20370 const unsigned RegSize =
20371 (InVTSize > 128) ? ((InVTSize > 256) ? 512 : 256) : 128;
20372 assert((!Subtarget->hasAVX512() || RegSize < 512) &&
20373 "512-bit vector requires AVX512");
20374 assert((!Subtarget->hasAVX2() || RegSize < 256) &&
20375 "256-bit vector requires AVX2");
20377 auto ElemVT = InVT.getVectorElementType();
20378 auto RegVT = EVT::getVectorVT(*DAG.getContext(), ElemVT,
20379 RegSize / ElemVT.getSizeInBits());
20380 assert(RegSize % InVT.getSizeInBits() == 0);
20381 unsigned NumConcat = RegSize / InVT.getSizeInBits();
20383 SmallVector<SDValue, 16> Ops(NumConcat, DAG.getUNDEF(InVT));
20384 Ops[0] = N->getOperand(0);
20385 SDValue InVec0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, RegVT, Ops);
20386 Ops[0] = N->getOperand(1);
20387 SDValue InVec1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, RegVT, Ops);
20389 SDValue Res = DAG.getNode(X86ISD::AVG, dl, RegVT, InVec0, InVec1);
20390 Results.push_back(DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, InVT, Res,
20391 DAG.getIntPtrConstant(0, dl)));
20394 // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
20395 case X86ISD::FMINC:
20397 case X86ISD::FMAXC:
20398 case X86ISD::FMAX: {
20399 EVT VT = N->getValueType(0);
20400 assert(VT == MVT::v2f32 && "Unexpected type (!= v2f32) on FMIN/FMAX.");
20401 SDValue UNDEF = DAG.getUNDEF(VT);
20402 SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
20403 N->getOperand(0), UNDEF);
20404 SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
20405 N->getOperand(1), UNDEF);
20406 Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
20409 case ISD::SIGN_EXTEND_INREG:
20414 // We don't want to expand or promote these.
20421 case ISD::UDIVREM: {
20422 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
20423 Results.push_back(V);
20426 case ISD::FP_TO_SINT:
20427 case ISD::FP_TO_UINT: {
20428 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
20430 std::pair<SDValue,SDValue> Vals =
20431 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
20432 SDValue FIST = Vals.first, StackSlot = Vals.second;
20433 if (FIST.getNode()) {
20434 EVT VT = N->getValueType(0);
20435 // Return a load from the stack slot.
20436 if (StackSlot.getNode())
20437 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
20438 MachinePointerInfo(),
20439 false, false, false, 0));
20441 Results.push_back(FIST);
20445 case ISD::UINT_TO_FP: {
20446 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
20447 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
20448 N->getValueType(0) != MVT::v2f32)
20450 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
20452 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
20454 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
20455 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
20456 DAG.getBitcast(MVT::v2i64, VBias));
20457 Or = DAG.getBitcast(MVT::v2f64, Or);
20458 // TODO: Are there any fast-math-flags to propagate here?
20459 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
20460 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
20463 case ISD::FP_ROUND: {
20464 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
20466 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
20467 Results.push_back(V);
20470 case ISD::FP_EXTEND: {
20471 // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
20472 // No other ValueType for FP_EXTEND should reach this point.
20473 assert(N->getValueType(0) == MVT::v2f32 &&
20474 "Do not know how to legalize this Node");
20477 case ISD::INTRINSIC_W_CHAIN: {
20478 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
20480 default : llvm_unreachable("Do not know how to custom type "
20481 "legalize this intrinsic operation!");
20482 case Intrinsic::x86_rdtsc:
20483 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
20485 case Intrinsic::x86_rdtscp:
20486 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
20488 case Intrinsic::x86_rdpmc:
20489 return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
20492 case ISD::INTRINSIC_WO_CHAIN: {
20493 if (SDValue V = LowerINTRINSIC_WO_CHAIN(SDValue(N, 0), Subtarget, DAG))
20494 Results.push_back(V);
20497 case ISD::READCYCLECOUNTER: {
20498 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
20501 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
20502 EVT T = N->getValueType(0);
20503 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
20504 bool Regs64bit = T == MVT::i128;
20505 MVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
20506 SDValue cpInL, cpInH;
20507 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
20508 DAG.getConstant(0, dl, HalfT));
20509 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
20510 DAG.getConstant(1, dl, HalfT));
20511 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
20512 Regs64bit ? X86::RAX : X86::EAX,
20514 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
20515 Regs64bit ? X86::RDX : X86::EDX,
20516 cpInH, cpInL.getValue(1));
20517 SDValue swapInL, swapInH;
20518 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
20519 DAG.getConstant(0, dl, HalfT));
20520 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
20521 DAG.getConstant(1, dl, HalfT));
20522 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
20523 Regs64bit ? X86::RBX : X86::EBX,
20524 swapInL, cpInH.getValue(1));
20525 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
20526 Regs64bit ? X86::RCX : X86::ECX,
20527 swapInH, swapInL.getValue(1));
20528 SDValue Ops[] = { swapInH.getValue(0),
20530 swapInH.getValue(1) };
20531 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
20532 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
20533 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
20534 X86ISD::LCMPXCHG8_DAG;
20535 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
20536 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
20537 Regs64bit ? X86::RAX : X86::EAX,
20538 HalfT, Result.getValue(1));
20539 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
20540 Regs64bit ? X86::RDX : X86::EDX,
20541 HalfT, cpOutL.getValue(2));
20542 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
20544 SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
20545 MVT::i32, cpOutH.getValue(2));
20547 DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
20548 DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
20549 Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
20551 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
20552 Results.push_back(Success);
20553 Results.push_back(EFLAGS.getValue(1));
20556 case ISD::ATOMIC_SWAP:
20557 case ISD::ATOMIC_LOAD_ADD:
20558 case ISD::ATOMIC_LOAD_SUB:
20559 case ISD::ATOMIC_LOAD_AND:
20560 case ISD::ATOMIC_LOAD_OR:
20561 case ISD::ATOMIC_LOAD_XOR:
20562 case ISD::ATOMIC_LOAD_NAND:
20563 case ISD::ATOMIC_LOAD_MIN:
20564 case ISD::ATOMIC_LOAD_MAX:
20565 case ISD::ATOMIC_LOAD_UMIN:
20566 case ISD::ATOMIC_LOAD_UMAX:
20567 case ISD::ATOMIC_LOAD: {
20568 // Delegate to generic TypeLegalization. Situations we can really handle
20569 // should have already been dealt with by AtomicExpandPass.cpp.
20572 case ISD::BITCAST: {
20573 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
20574 EVT DstVT = N->getValueType(0);
20575 EVT SrcVT = N->getOperand(0)->getValueType(0);
20577 if (SrcVT != MVT::f64 ||
20578 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
20581 unsigned NumElts = DstVT.getVectorNumElements();
20582 EVT SVT = DstVT.getVectorElementType();
20583 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
20584 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
20585 MVT::v2f64, N->getOperand(0));
20586 SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
20588 if (ExperimentalVectorWideningLegalization) {
20589 // If we are legalizing vectors by widening, we already have the desired
20590 // legal vector type, just return it.
20591 Results.push_back(ToVecInt);
20595 SmallVector<SDValue, 8> Elts;
20596 for (unsigned i = 0, e = NumElts; i != e; ++i)
20597 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
20598 ToVecInt, DAG.getIntPtrConstant(i, dl)));
20600 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
20605 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
20606 switch ((X86ISD::NodeType)Opcode) {
20607 case X86ISD::FIRST_NUMBER: break;
20608 case X86ISD::BSF: return "X86ISD::BSF";
20609 case X86ISD::BSR: return "X86ISD::BSR";
20610 case X86ISD::SHLD: return "X86ISD::SHLD";
20611 case X86ISD::SHRD: return "X86ISD::SHRD";
20612 case X86ISD::FAND: return "X86ISD::FAND";
20613 case X86ISD::FANDN: return "X86ISD::FANDN";
20614 case X86ISD::FOR: return "X86ISD::FOR";
20615 case X86ISD::FXOR: return "X86ISD::FXOR";
20616 case X86ISD::FILD: return "X86ISD::FILD";
20617 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
20618 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
20619 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
20620 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
20621 case X86ISD::FLD: return "X86ISD::FLD";
20622 case X86ISD::FST: return "X86ISD::FST";
20623 case X86ISD::CALL: return "X86ISD::CALL";
20624 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
20625 case X86ISD::RDTSCP_DAG: return "X86ISD::RDTSCP_DAG";
20626 case X86ISD::RDPMC_DAG: return "X86ISD::RDPMC_DAG";
20627 case X86ISD::BT: return "X86ISD::BT";
20628 case X86ISD::CMP: return "X86ISD::CMP";
20629 case X86ISD::COMI: return "X86ISD::COMI";
20630 case X86ISD::UCOMI: return "X86ISD::UCOMI";
20631 case X86ISD::CMPM: return "X86ISD::CMPM";
20632 case X86ISD::CMPMU: return "X86ISD::CMPMU";
20633 case X86ISD::CMPM_RND: return "X86ISD::CMPM_RND";
20634 case X86ISD::SETCC: return "X86ISD::SETCC";
20635 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
20636 case X86ISD::FSETCC: return "X86ISD::FSETCC";
20637 case X86ISD::FGETSIGNx86: return "X86ISD::FGETSIGNx86";
20638 case X86ISD::CMOV: return "X86ISD::CMOV";
20639 case X86ISD::BRCOND: return "X86ISD::BRCOND";
20640 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
20641 case X86ISD::IRET: return "X86ISD::IRET";
20642 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
20643 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
20644 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
20645 case X86ISD::Wrapper: return "X86ISD::Wrapper";
20646 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
20647 case X86ISD::MOVDQ2Q: return "X86ISD::MOVDQ2Q";
20648 case X86ISD::MMX_MOVD2W: return "X86ISD::MMX_MOVD2W";
20649 case X86ISD::MMX_MOVW2D: return "X86ISD::MMX_MOVW2D";
20650 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
20651 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
20652 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
20653 case X86ISD::PINSRB: return "X86ISD::PINSRB";
20654 case X86ISD::PINSRW: return "X86ISD::PINSRW";
20655 case X86ISD::MMX_PINSRW: return "X86ISD::MMX_PINSRW";
20656 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
20657 case X86ISD::ANDNP: return "X86ISD::ANDNP";
20658 case X86ISD::PSIGN: return "X86ISD::PSIGN";
20659 case X86ISD::BLENDI: return "X86ISD::BLENDI";
20660 case X86ISD::SHRUNKBLEND: return "X86ISD::SHRUNKBLEND";
20661 case X86ISD::ADDUS: return "X86ISD::ADDUS";
20662 case X86ISD::SUBUS: return "X86ISD::SUBUS";
20663 case X86ISD::HADD: return "X86ISD::HADD";
20664 case X86ISD::HSUB: return "X86ISD::HSUB";
20665 case X86ISD::FHADD: return "X86ISD::FHADD";
20666 case X86ISD::FHSUB: return "X86ISD::FHSUB";
20667 case X86ISD::ABS: return "X86ISD::ABS";
20668 case X86ISD::CONFLICT: return "X86ISD::CONFLICT";
20669 case X86ISD::FMAX: return "X86ISD::FMAX";
20670 case X86ISD::FMAX_RND: return "X86ISD::FMAX_RND";
20671 case X86ISD::FMIN: return "X86ISD::FMIN";
20672 case X86ISD::FMIN_RND: return "X86ISD::FMIN_RND";
20673 case X86ISD::FMAXC: return "X86ISD::FMAXC";
20674 case X86ISD::FMINC: return "X86ISD::FMINC";
20675 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
20676 case X86ISD::FRCP: return "X86ISD::FRCP";
20677 case X86ISD::EXTRQI: return "X86ISD::EXTRQI";
20678 case X86ISD::INSERTQI: return "X86ISD::INSERTQI";
20679 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
20680 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
20681 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
20682 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
20683 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
20684 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
20685 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
20686 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
20687 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
20688 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
20689 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
20690 case X86ISD::LCMPXCHG16_DAG: return "X86ISD::LCMPXCHG16_DAG";
20691 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
20692 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
20693 case X86ISD::VZEXT: return "X86ISD::VZEXT";
20694 case X86ISD::VSEXT: return "X86ISD::VSEXT";
20695 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
20696 case X86ISD::VTRUNCS: return "X86ISD::VTRUNCS";
20697 case X86ISD::VTRUNCUS: return "X86ISD::VTRUNCUS";
20698 case X86ISD::VINSERT: return "X86ISD::VINSERT";
20699 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
20700 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
20701 case X86ISD::CVTDQ2PD: return "X86ISD::CVTDQ2PD";
20702 case X86ISD::CVTUDQ2PD: return "X86ISD::CVTUDQ2PD";
20703 case X86ISD::CVT2MASK: return "X86ISD::CVT2MASK";
20704 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
20705 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
20706 case X86ISD::VSHL: return "X86ISD::VSHL";
20707 case X86ISD::VSRL: return "X86ISD::VSRL";
20708 case X86ISD::VSRA: return "X86ISD::VSRA";
20709 case X86ISD::VSHLI: return "X86ISD::VSHLI";
20710 case X86ISD::VSRLI: return "X86ISD::VSRLI";
20711 case X86ISD::VSRAI: return "X86ISD::VSRAI";
20712 case X86ISD::CMPP: return "X86ISD::CMPP";
20713 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
20714 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
20715 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
20716 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
20717 case X86ISD::ADD: return "X86ISD::ADD";
20718 case X86ISD::SUB: return "X86ISD::SUB";
20719 case X86ISD::ADC: return "X86ISD::ADC";
20720 case X86ISD::SBB: return "X86ISD::SBB";
20721 case X86ISD::SMUL: return "X86ISD::SMUL";
20722 case X86ISD::UMUL: return "X86ISD::UMUL";
20723 case X86ISD::SMUL8: return "X86ISD::SMUL8";
20724 case X86ISD::UMUL8: return "X86ISD::UMUL8";
20725 case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
20726 case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
20727 case X86ISD::INC: return "X86ISD::INC";
20728 case X86ISD::DEC: return "X86ISD::DEC";
20729 case X86ISD::OR: return "X86ISD::OR";
20730 case X86ISD::XOR: return "X86ISD::XOR";
20731 case X86ISD::AND: return "X86ISD::AND";
20732 case X86ISD::BEXTR: return "X86ISD::BEXTR";
20733 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
20734 case X86ISD::PTEST: return "X86ISD::PTEST";
20735 case X86ISD::TESTP: return "X86ISD::TESTP";
20736 case X86ISD::TESTM: return "X86ISD::TESTM";
20737 case X86ISD::TESTNM: return "X86ISD::TESTNM";
20738 case X86ISD::KORTEST: return "X86ISD::KORTEST";
20739 case X86ISD::KTEST: return "X86ISD::KTEST";
20740 case X86ISD::PACKSS: return "X86ISD::PACKSS";
20741 case X86ISD::PACKUS: return "X86ISD::PACKUS";
20742 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
20743 case X86ISD::VALIGN: return "X86ISD::VALIGN";
20744 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
20745 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
20746 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
20747 case X86ISD::SHUFP: return "X86ISD::SHUFP";
20748 case X86ISD::SHUF128: return "X86ISD::SHUF128";
20749 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
20750 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
20751 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
20752 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
20753 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
20754 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
20755 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
20756 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
20757 case X86ISD::MOVSD: return "X86ISD::MOVSD";
20758 case X86ISD::MOVSS: return "X86ISD::MOVSS";
20759 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
20760 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
20761 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
20762 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
20763 case X86ISD::SUBV_BROADCAST: return "X86ISD::SUBV_BROADCAST";
20764 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
20765 case X86ISD::VPERMILPV: return "X86ISD::VPERMILPV";
20766 case X86ISD::VPERMILPI: return "X86ISD::VPERMILPI";
20767 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
20768 case X86ISD::VPERMV: return "X86ISD::VPERMV";
20769 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
20770 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
20771 case X86ISD::VPERMI: return "X86ISD::VPERMI";
20772 case X86ISD::VPTERNLOG: return "X86ISD::VPTERNLOG";
20773 case X86ISD::VFIXUPIMM: return "X86ISD::VFIXUPIMM";
20774 case X86ISD::VRANGE: return "X86ISD::VRANGE";
20775 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
20776 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
20777 case X86ISD::PSADBW: return "X86ISD::PSADBW";
20778 case X86ISD::DBPSADBW: return "X86ISD::DBPSADBW";
20779 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
20780 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
20781 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
20782 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
20783 case X86ISD::MFENCE: return "X86ISD::MFENCE";
20784 case X86ISD::SFENCE: return "X86ISD::SFENCE";
20785 case X86ISD::LFENCE: return "X86ISD::LFENCE";
20786 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
20787 case X86ISD::SAHF: return "X86ISD::SAHF";
20788 case X86ISD::RDRAND: return "X86ISD::RDRAND";
20789 case X86ISD::RDSEED: return "X86ISD::RDSEED";
20790 case X86ISD::VPMADDUBSW: return "X86ISD::VPMADDUBSW";
20791 case X86ISD::VPMADDWD: return "X86ISD::VPMADDWD";
20792 case X86ISD::VPROT: return "X86ISD::VPROT";
20793 case X86ISD::VPROTI: return "X86ISD::VPROTI";
20794 case X86ISD::VPSHA: return "X86ISD::VPSHA";
20795 case X86ISD::VPSHL: return "X86ISD::VPSHL";
20796 case X86ISD::VPCOM: return "X86ISD::VPCOM";
20797 case X86ISD::VPCOMU: return "X86ISD::VPCOMU";
20798 case X86ISD::FMADD: return "X86ISD::FMADD";
20799 case X86ISD::FMSUB: return "X86ISD::FMSUB";
20800 case X86ISD::FNMADD: return "X86ISD::FNMADD";
20801 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
20802 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
20803 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
20804 case X86ISD::FMADD_RND: return "X86ISD::FMADD_RND";
20805 case X86ISD::FNMADD_RND: return "X86ISD::FNMADD_RND";
20806 case X86ISD::FMSUB_RND: return "X86ISD::FMSUB_RND";
20807 case X86ISD::FNMSUB_RND: return "X86ISD::FNMSUB_RND";
20808 case X86ISD::FMADDSUB_RND: return "X86ISD::FMADDSUB_RND";
20809 case X86ISD::FMSUBADD_RND: return "X86ISD::FMSUBADD_RND";
20810 case X86ISD::VRNDSCALE: return "X86ISD::VRNDSCALE";
20811 case X86ISD::VREDUCE: return "X86ISD::VREDUCE";
20812 case X86ISD::VGETMANT: return "X86ISD::VGETMANT";
20813 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
20814 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
20815 case X86ISD::XTEST: return "X86ISD::XTEST";
20816 case X86ISD::COMPRESS: return "X86ISD::COMPRESS";
20817 case X86ISD::EXPAND: return "X86ISD::EXPAND";
20818 case X86ISD::SELECT: return "X86ISD::SELECT";
20819 case X86ISD::ADDSUB: return "X86ISD::ADDSUB";
20820 case X86ISD::RCP28: return "X86ISD::RCP28";
20821 case X86ISD::EXP2: return "X86ISD::EXP2";
20822 case X86ISD::RSQRT28: return "X86ISD::RSQRT28";
20823 case X86ISD::FADD_RND: return "X86ISD::FADD_RND";
20824 case X86ISD::FSUB_RND: return "X86ISD::FSUB_RND";
20825 case X86ISD::FMUL_RND: return "X86ISD::FMUL_RND";
20826 case X86ISD::FDIV_RND: return "X86ISD::FDIV_RND";
20827 case X86ISD::FSQRT_RND: return "X86ISD::FSQRT_RND";
20828 case X86ISD::FGETEXP_RND: return "X86ISD::FGETEXP_RND";
20829 case X86ISD::SCALEF: return "X86ISD::SCALEF";
20830 case X86ISD::ADDS: return "X86ISD::ADDS";
20831 case X86ISD::SUBS: return "X86ISD::SUBS";
20832 case X86ISD::AVG: return "X86ISD::AVG";
20833 case X86ISD::MULHRS: return "X86ISD::MULHRS";
20834 case X86ISD::SINT_TO_FP_RND: return "X86ISD::SINT_TO_FP_RND";
20835 case X86ISD::UINT_TO_FP_RND: return "X86ISD::UINT_TO_FP_RND";
20836 case X86ISD::FP_TO_SINT_RND: return "X86ISD::FP_TO_SINT_RND";
20837 case X86ISD::FP_TO_UINT_RND: return "X86ISD::FP_TO_UINT_RND";
20838 case X86ISD::VFPCLASS: return "X86ISD::VFPCLASS";
20839 case X86ISD::VFPCLASSS: return "X86ISD::VFPCLASSS";
20844 // isLegalAddressingMode - Return true if the addressing mode represented
20845 // by AM is legal for this target, for a load/store of the specified type.
20846 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
20847 const AddrMode &AM, Type *Ty,
20848 unsigned AS) const {
20849 // X86 supports extremely general addressing modes.
20850 CodeModel::Model M = getTargetMachine().getCodeModel();
20851 Reloc::Model R = getTargetMachine().getRelocationModel();
20853 // X86 allows a sign-extended 32-bit immediate field as a displacement.
20854 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
20859 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
20861 // If a reference to this global requires an extra load, we can't fold it.
20862 if (isGlobalStubReference(GVFlags))
20865 // If BaseGV requires a register for the PIC base, we cannot also have a
20866 // BaseReg specified.
20867 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
20870 // If lower 4G is not available, then we must use rip-relative addressing.
20871 if ((M != CodeModel::Small || R != Reloc::Static) &&
20872 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
20876 switch (AM.Scale) {
20882 // These scales always work.
20887 // These scales are formed with basereg+scalereg. Only accept if there is
20892 default: // Other stuff never works.
20899 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
20900 unsigned Bits = Ty->getScalarSizeInBits();
20902 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
20903 // particularly cheaper than those without.
20907 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
20908 // variable shifts just as cheap as scalar ones.
20909 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
20912 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
20913 // fully general vector.
20917 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
20918 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
20920 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
20921 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
20922 return NumBits1 > NumBits2;
20925 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
20926 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
20929 if (!isTypeLegal(EVT::getEVT(Ty1)))
20932 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
20934 // Assuming the caller doesn't have a zeroext or signext return parameter,
20935 // truncation all the way down to i1 is valid.
20939 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
20940 return isInt<32>(Imm);
20943 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
20944 // Can also use sub to handle negated immediates.
20945 return isInt<32>(Imm);
20948 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
20949 if (!VT1.isInteger() || !VT2.isInteger())
20951 unsigned NumBits1 = VT1.getSizeInBits();
20952 unsigned NumBits2 = VT2.getSizeInBits();
20953 return NumBits1 > NumBits2;
20956 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
20957 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
20958 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
20961 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
20962 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
20963 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
20966 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
20967 EVT VT1 = Val.getValueType();
20968 if (isZExtFree(VT1, VT2))
20971 if (Val.getOpcode() != ISD::LOAD)
20974 if (!VT1.isSimple() || !VT1.isInteger() ||
20975 !VT2.isSimple() || !VT2.isInteger())
20978 switch (VT1.getSimpleVT().SimpleTy) {
20983 // X86 has 8, 16, and 32-bit zero-extending loads.
20990 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
20993 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
20994 if (!Subtarget->hasAnyFMA())
20997 VT = VT.getScalarType();
20999 if (!VT.isSimple())
21002 switch (VT.getSimpleVT().SimpleTy) {
21013 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
21014 // i16 instructions are longer (0x66 prefix) and potentially slower.
21015 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
21018 /// isShuffleMaskLegal - Targets can use this to indicate that they only
21019 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
21020 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
21021 /// are assumed to be legal.
21023 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
21025 if (!VT.isSimple())
21028 // Not for i1 vectors
21029 if (VT.getSimpleVT().getScalarType() == MVT::i1)
21032 // Very little shuffling can be done for 64-bit vectors right now.
21033 if (VT.getSimpleVT().getSizeInBits() == 64)
21036 // We only care that the types being shuffled are legal. The lowering can
21037 // handle any possible shuffle mask that results.
21038 return isTypeLegal(VT.getSimpleVT());
21042 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
21044 // Just delegate to the generic legality, clear masks aren't special.
21045 return isShuffleMaskLegal(Mask, VT);
21048 //===----------------------------------------------------------------------===//
21049 // X86 Scheduler Hooks
21050 //===----------------------------------------------------------------------===//
21052 /// Utility function to emit xbegin specifying the start of an RTM region.
21053 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
21054 const TargetInstrInfo *TII) {
21055 DebugLoc DL = MI->getDebugLoc();
21057 const BasicBlock *BB = MBB->getBasicBlock();
21058 MachineFunction::iterator I = ++MBB->getIterator();
21060 // For the v = xbegin(), we generate
21071 MachineBasicBlock *thisMBB = MBB;
21072 MachineFunction *MF = MBB->getParent();
21073 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
21074 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
21075 MF->insert(I, mainMBB);
21076 MF->insert(I, sinkMBB);
21078 // Transfer the remainder of BB and its successor edges to sinkMBB.
21079 sinkMBB->splice(sinkMBB->begin(), MBB,
21080 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
21081 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
21085 // # fallthrough to mainMBB
21086 // # abortion to sinkMBB
21087 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
21088 thisMBB->addSuccessor(mainMBB);
21089 thisMBB->addSuccessor(sinkMBB);
21093 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
21094 mainMBB->addSuccessor(sinkMBB);
21097 // EAX is live into the sinkMBB
21098 sinkMBB->addLiveIn(X86::EAX);
21099 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
21100 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
21103 MI->eraseFromParent();
21107 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
21108 // or XMM0_V32I8 in AVX all of this code can be replaced with that
21109 // in the .td file.
21110 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
21111 const TargetInstrInfo *TII) {
21113 switch (MI->getOpcode()) {
21114 default: llvm_unreachable("illegal opcode!");
21115 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
21116 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
21117 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
21118 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
21119 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
21120 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
21121 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
21122 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
21125 DebugLoc dl = MI->getDebugLoc();
21126 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
21128 unsigned NumArgs = MI->getNumOperands();
21129 for (unsigned i = 1; i < NumArgs; ++i) {
21130 MachineOperand &Op = MI->getOperand(i);
21131 if (!(Op.isReg() && Op.isImplicit()))
21132 MIB.addOperand(Op);
21134 if (MI->hasOneMemOperand())
21135 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
21137 BuildMI(*BB, MI, dl,
21138 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
21139 .addReg(X86::XMM0);
21141 MI->eraseFromParent();
21145 // FIXME: Custom handling because TableGen doesn't support multiple implicit
21146 // defs in an instruction pattern
21147 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
21148 const TargetInstrInfo *TII) {
21150 switch (MI->getOpcode()) {
21151 default: llvm_unreachable("illegal opcode!");
21152 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
21153 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
21154 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
21155 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
21156 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
21157 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
21158 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
21159 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
21162 DebugLoc dl = MI->getDebugLoc();
21163 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
21165 unsigned NumArgs = MI->getNumOperands(); // remove the results
21166 for (unsigned i = 1; i < NumArgs; ++i) {
21167 MachineOperand &Op = MI->getOperand(i);
21168 if (!(Op.isReg() && Op.isImplicit()))
21169 MIB.addOperand(Op);
21171 if (MI->hasOneMemOperand())
21172 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
21174 BuildMI(*BB, MI, dl,
21175 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
21178 MI->eraseFromParent();
21182 static MachineBasicBlock *EmitWRPKRU(MachineInstr *MI, MachineBasicBlock *BB,
21183 const X86Subtarget *Subtarget) {
21184 DebugLoc dl = MI->getDebugLoc();
21185 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21187 // insert input VAL into EAX
21188 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
21189 .addReg(MI->getOperand(0).getReg());
21190 // insert zero to ECX
21191 BuildMI(*BB, MI, dl, TII->get(X86::XOR32rr), X86::ECX)
21194 // insert zero to EDX
21195 BuildMI(*BB, MI, dl, TII->get(X86::XOR32rr), X86::EDX)
21198 // insert WRPKRU instruction
21199 BuildMI(*BB, MI, dl, TII->get(X86::WRPKRUr));
21201 MI->eraseFromParent(); // The pseudo is gone now.
21205 static MachineBasicBlock *EmitRDPKRU(MachineInstr *MI, MachineBasicBlock *BB,
21206 const X86Subtarget *Subtarget) {
21207 DebugLoc dl = MI->getDebugLoc();
21208 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21210 // insert zero to ECX
21211 BuildMI(*BB, MI, dl, TII->get(X86::XOR32rr), X86::ECX)
21214 // insert RDPKRU instruction
21215 BuildMI(*BB, MI, dl, TII->get(X86::RDPKRUr));
21216 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
21219 MI->eraseFromParent(); // The pseudo is gone now.
21223 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
21224 const X86Subtarget *Subtarget) {
21225 DebugLoc dl = MI->getDebugLoc();
21226 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21227 // Address into RAX/EAX, other two args into ECX, EDX.
21228 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
21229 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
21230 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
21231 for (int i = 0; i < X86::AddrNumOperands; ++i)
21232 MIB.addOperand(MI->getOperand(i));
21234 unsigned ValOps = X86::AddrNumOperands;
21235 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
21236 .addReg(MI->getOperand(ValOps).getReg());
21237 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
21238 .addReg(MI->getOperand(ValOps+1).getReg());
21240 // The instruction doesn't actually take any operands though.
21241 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
21243 MI->eraseFromParent(); // The pseudo is gone now.
21247 MachineBasicBlock *
21248 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
21249 MachineBasicBlock *MBB) const {
21250 // Emit va_arg instruction on X86-64.
21252 // Operands to this pseudo-instruction:
21253 // 0 ) Output : destination address (reg)
21254 // 1-5) Input : va_list address (addr, i64mem)
21255 // 6 ) ArgSize : Size (in bytes) of vararg type
21256 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
21257 // 8 ) Align : Alignment of type
21258 // 9 ) EFLAGS (implicit-def)
21260 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
21261 static_assert(X86::AddrNumOperands == 5,
21262 "VAARG_64 assumes 5 address operands");
21264 unsigned DestReg = MI->getOperand(0).getReg();
21265 MachineOperand &Base = MI->getOperand(1);
21266 MachineOperand &Scale = MI->getOperand(2);
21267 MachineOperand &Index = MI->getOperand(3);
21268 MachineOperand &Disp = MI->getOperand(4);
21269 MachineOperand &Segment = MI->getOperand(5);
21270 unsigned ArgSize = MI->getOperand(6).getImm();
21271 unsigned ArgMode = MI->getOperand(7).getImm();
21272 unsigned Align = MI->getOperand(8).getImm();
21274 // Memory Reference
21275 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
21276 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21277 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21279 // Machine Information
21280 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21281 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
21282 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
21283 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
21284 DebugLoc DL = MI->getDebugLoc();
21286 // struct va_list {
21289 // i64 overflow_area (address)
21290 // i64 reg_save_area (address)
21292 // sizeof(va_list) = 24
21293 // alignment(va_list) = 8
21295 unsigned TotalNumIntRegs = 6;
21296 unsigned TotalNumXMMRegs = 8;
21297 bool UseGPOffset = (ArgMode == 1);
21298 bool UseFPOffset = (ArgMode == 2);
21299 unsigned MaxOffset = TotalNumIntRegs * 8 +
21300 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
21302 /* Align ArgSize to a multiple of 8 */
21303 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
21304 bool NeedsAlign = (Align > 8);
21306 MachineBasicBlock *thisMBB = MBB;
21307 MachineBasicBlock *overflowMBB;
21308 MachineBasicBlock *offsetMBB;
21309 MachineBasicBlock *endMBB;
21311 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
21312 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
21313 unsigned OffsetReg = 0;
21315 if (!UseGPOffset && !UseFPOffset) {
21316 // If we only pull from the overflow region, we don't create a branch.
21317 // We don't need to alter control flow.
21318 OffsetDestReg = 0; // unused
21319 OverflowDestReg = DestReg;
21321 offsetMBB = nullptr;
21322 overflowMBB = thisMBB;
21325 // First emit code to check if gp_offset (or fp_offset) is below the bound.
21326 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
21327 // If not, pull from overflow_area. (branch to overflowMBB)
21332 // offsetMBB overflowMBB
21337 // Registers for the PHI in endMBB
21338 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
21339 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
21341 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
21342 MachineFunction *MF = MBB->getParent();
21343 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21344 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21345 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21347 MachineFunction::iterator MBBIter = ++MBB->getIterator();
21349 // Insert the new basic blocks
21350 MF->insert(MBBIter, offsetMBB);
21351 MF->insert(MBBIter, overflowMBB);
21352 MF->insert(MBBIter, endMBB);
21354 // Transfer the remainder of MBB and its successor edges to endMBB.
21355 endMBB->splice(endMBB->begin(), thisMBB,
21356 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
21357 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
21359 // Make offsetMBB and overflowMBB successors of thisMBB
21360 thisMBB->addSuccessor(offsetMBB);
21361 thisMBB->addSuccessor(overflowMBB);
21363 // endMBB is a successor of both offsetMBB and overflowMBB
21364 offsetMBB->addSuccessor(endMBB);
21365 overflowMBB->addSuccessor(endMBB);
21367 // Load the offset value into a register
21368 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
21369 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
21373 .addDisp(Disp, UseFPOffset ? 4 : 0)
21374 .addOperand(Segment)
21375 .setMemRefs(MMOBegin, MMOEnd);
21377 // Check if there is enough room left to pull this argument.
21378 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
21380 .addImm(MaxOffset + 8 - ArgSizeA8);
21382 // Branch to "overflowMBB" if offset >= max
21383 // Fall through to "offsetMBB" otherwise
21384 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
21385 .addMBB(overflowMBB);
21388 // In offsetMBB, emit code to use the reg_save_area.
21390 assert(OffsetReg != 0);
21392 // Read the reg_save_area address.
21393 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
21394 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
21399 .addOperand(Segment)
21400 .setMemRefs(MMOBegin, MMOEnd);
21402 // Zero-extend the offset
21403 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
21404 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
21407 .addImm(X86::sub_32bit);
21409 // Add the offset to the reg_save_area to get the final address.
21410 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
21411 .addReg(OffsetReg64)
21412 .addReg(RegSaveReg);
21414 // Compute the offset for the next argument
21415 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
21416 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
21418 .addImm(UseFPOffset ? 16 : 8);
21420 // Store it back into the va_list.
21421 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
21425 .addDisp(Disp, UseFPOffset ? 4 : 0)
21426 .addOperand(Segment)
21427 .addReg(NextOffsetReg)
21428 .setMemRefs(MMOBegin, MMOEnd);
21431 BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
21436 // Emit code to use overflow area
21439 // Load the overflow_area address into a register.
21440 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
21441 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
21446 .addOperand(Segment)
21447 .setMemRefs(MMOBegin, MMOEnd);
21449 // If we need to align it, do so. Otherwise, just copy the address
21450 // to OverflowDestReg.
21452 // Align the overflow address
21453 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
21454 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
21456 // aligned_addr = (addr + (align-1)) & ~(align-1)
21457 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
21458 .addReg(OverflowAddrReg)
21461 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
21463 .addImm(~(uint64_t)(Align-1));
21465 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
21466 .addReg(OverflowAddrReg);
21469 // Compute the next overflow address after this argument.
21470 // (the overflow address should be kept 8-byte aligned)
21471 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
21472 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
21473 .addReg(OverflowDestReg)
21474 .addImm(ArgSizeA8);
21476 // Store the new overflow address.
21477 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
21482 .addOperand(Segment)
21483 .addReg(NextAddrReg)
21484 .setMemRefs(MMOBegin, MMOEnd);
21486 // If we branched, emit the PHI to the front of endMBB.
21488 BuildMI(*endMBB, endMBB->begin(), DL,
21489 TII->get(X86::PHI), DestReg)
21490 .addReg(OffsetDestReg).addMBB(offsetMBB)
21491 .addReg(OverflowDestReg).addMBB(overflowMBB);
21494 // Erase the pseudo instruction
21495 MI->eraseFromParent();
21500 MachineBasicBlock *
21501 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
21503 MachineBasicBlock *MBB) const {
21504 // Emit code to save XMM registers to the stack. The ABI says that the
21505 // number of registers to save is given in %al, so it's theoretically
21506 // possible to do an indirect jump trick to avoid saving all of them,
21507 // however this code takes a simpler approach and just executes all
21508 // of the stores if %al is non-zero. It's less code, and it's probably
21509 // easier on the hardware branch predictor, and stores aren't all that
21510 // expensive anyway.
21512 // Create the new basic blocks. One block contains all the XMM stores,
21513 // and one block is the final destination regardless of whether any
21514 // stores were performed.
21515 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
21516 MachineFunction *F = MBB->getParent();
21517 MachineFunction::iterator MBBIter = ++MBB->getIterator();
21518 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
21519 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
21520 F->insert(MBBIter, XMMSaveMBB);
21521 F->insert(MBBIter, EndMBB);
21523 // Transfer the remainder of MBB and its successor edges to EndMBB.
21524 EndMBB->splice(EndMBB->begin(), MBB,
21525 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
21526 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
21528 // The original block will now fall through to the XMM save block.
21529 MBB->addSuccessor(XMMSaveMBB);
21530 // The XMMSaveMBB will fall through to the end block.
21531 XMMSaveMBB->addSuccessor(EndMBB);
21533 // Now add the instructions.
21534 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21535 DebugLoc DL = MI->getDebugLoc();
21537 unsigned CountReg = MI->getOperand(0).getReg();
21538 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
21539 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
21541 if (!Subtarget->isCallingConvWin64(F->getFunction()->getCallingConv())) {
21542 // If %al is 0, branch around the XMM save block.
21543 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
21544 BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
21545 MBB->addSuccessor(EndMBB);
21548 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
21549 // that was just emitted, but clearly shouldn't be "saved".
21550 assert((MI->getNumOperands() <= 3 ||
21551 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
21552 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
21553 && "Expected last argument to be EFLAGS");
21554 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
21555 // In the XMM save block, save all the XMM argument registers.
21556 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
21557 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
21558 MachineMemOperand *MMO = F->getMachineMemOperand(
21559 MachinePointerInfo::getFixedStack(*F, RegSaveFrameIndex, Offset),
21560 MachineMemOperand::MOStore,
21561 /*Size=*/16, /*Align=*/16);
21562 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
21563 .addFrameIndex(RegSaveFrameIndex)
21564 .addImm(/*Scale=*/1)
21565 .addReg(/*IndexReg=*/0)
21566 .addImm(/*Disp=*/Offset)
21567 .addReg(/*Segment=*/0)
21568 .addReg(MI->getOperand(i).getReg())
21569 .addMemOperand(MMO);
21572 MI->eraseFromParent(); // The pseudo instruction is gone now.
21577 // The EFLAGS operand of SelectItr might be missing a kill marker
21578 // because there were multiple uses of EFLAGS, and ISel didn't know
21579 // which to mark. Figure out whether SelectItr should have had a
21580 // kill marker, and set it if it should. Returns the correct kill
21582 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
21583 MachineBasicBlock* BB,
21584 const TargetRegisterInfo* TRI) {
21585 // Scan forward through BB for a use/def of EFLAGS.
21586 MachineBasicBlock::iterator miI(std::next(SelectItr));
21587 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
21588 const MachineInstr& mi = *miI;
21589 if (mi.readsRegister(X86::EFLAGS))
21591 if (mi.definesRegister(X86::EFLAGS))
21592 break; // Should have kill-flag - update below.
21595 // If we hit the end of the block, check whether EFLAGS is live into a
21597 if (miI == BB->end()) {
21598 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
21599 sEnd = BB->succ_end();
21600 sItr != sEnd; ++sItr) {
21601 MachineBasicBlock* succ = *sItr;
21602 if (succ->isLiveIn(X86::EFLAGS))
21607 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
21608 // out. SelectMI should have a kill flag on EFLAGS.
21609 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
21613 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
21614 // together with other CMOV pseudo-opcodes into a single basic-block with
21615 // conditional jump around it.
21616 static bool isCMOVPseudo(MachineInstr *MI) {
21617 switch (MI->getOpcode()) {
21618 case X86::CMOV_FR32:
21619 case X86::CMOV_FR64:
21620 case X86::CMOV_GR8:
21621 case X86::CMOV_GR16:
21622 case X86::CMOV_GR32:
21623 case X86::CMOV_RFP32:
21624 case X86::CMOV_RFP64:
21625 case X86::CMOV_RFP80:
21626 case X86::CMOV_V2F64:
21627 case X86::CMOV_V2I64:
21628 case X86::CMOV_V4F32:
21629 case X86::CMOV_V4F64:
21630 case X86::CMOV_V4I64:
21631 case X86::CMOV_V16F32:
21632 case X86::CMOV_V8F32:
21633 case X86::CMOV_V8F64:
21634 case X86::CMOV_V8I64:
21635 case X86::CMOV_V8I1:
21636 case X86::CMOV_V16I1:
21637 case X86::CMOV_V32I1:
21638 case X86::CMOV_V64I1:
21646 MachineBasicBlock *
21647 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
21648 MachineBasicBlock *BB) const {
21649 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21650 DebugLoc DL = MI->getDebugLoc();
21652 // To "insert" a SELECT_CC instruction, we actually have to insert the
21653 // diamond control-flow pattern. The incoming instruction knows the
21654 // destination vreg to set, the condition code register to branch on, the
21655 // true/false values to select between, and a branch opcode to use.
21656 const BasicBlock *LLVM_BB = BB->getBasicBlock();
21657 MachineFunction::iterator It = ++BB->getIterator();
21662 // cmpTY ccX, r1, r2
21664 // fallthrough --> copy0MBB
21665 MachineBasicBlock *thisMBB = BB;
21666 MachineFunction *F = BB->getParent();
21668 // This code lowers all pseudo-CMOV instructions. Generally it lowers these
21669 // as described above, by inserting a BB, and then making a PHI at the join
21670 // point to select the true and false operands of the CMOV in the PHI.
21672 // The code also handles two different cases of multiple CMOV opcodes
21676 // In this case, there are multiple CMOVs in a row, all which are based on
21677 // the same condition setting (or the exact opposite condition setting).
21678 // In this case we can lower all the CMOVs using a single inserted BB, and
21679 // then make a number of PHIs at the join point to model the CMOVs. The only
21680 // trickiness here, is that in a case like:
21682 // t2 = CMOV cond1 t1, f1
21683 // t3 = CMOV cond1 t2, f2
21685 // when rewriting this into PHIs, we have to perform some renaming on the
21686 // temps since you cannot have a PHI operand refer to a PHI result earlier
21687 // in the same block. The "simple" but wrong lowering would be:
21689 // t2 = PHI t1(BB1), f1(BB2)
21690 // t3 = PHI t2(BB1), f2(BB2)
21692 // but clearly t2 is not defined in BB1, so that is incorrect. The proper
21693 // renaming is to note that on the path through BB1, t2 is really just a
21694 // copy of t1, and do that renaming, properly generating:
21696 // t2 = PHI t1(BB1), f1(BB2)
21697 // t3 = PHI t1(BB1), f2(BB2)
21699 // Case 2, we lower cascaded CMOVs such as
21701 // (CMOV (CMOV F, T, cc1), T, cc2)
21703 // to two successives branches. For that, we look for another CMOV as the
21704 // following instruction.
21706 // Without this, we would add a PHI between the two jumps, which ends up
21707 // creating a few copies all around. For instance, for
21709 // (sitofp (zext (fcmp une)))
21711 // we would generate:
21713 // ucomiss %xmm1, %xmm0
21714 // movss <1.0f>, %xmm0
21715 // movaps %xmm0, %xmm1
21717 // xorps %xmm1, %xmm1
21720 // movaps %xmm1, %xmm0
21724 // because this custom-inserter would have generated:
21736 // A: X = ...; Y = ...
21738 // C: Z = PHI [X, A], [Y, B]
21740 // E: PHI [X, C], [Z, D]
21742 // If we lower both CMOVs in a single step, we can instead generate:
21754 // A: X = ...; Y = ...
21756 // E: PHI [X, A], [X, C], [Y, D]
21758 // Which, in our sitofp/fcmp example, gives us something like:
21760 // ucomiss %xmm1, %xmm0
21761 // movss <1.0f>, %xmm0
21764 // xorps %xmm0, %xmm0
21768 MachineInstr *CascadedCMOV = nullptr;
21769 MachineInstr *LastCMOV = MI;
21770 X86::CondCode CC = X86::CondCode(MI->getOperand(3).getImm());
21771 X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
21772 MachineBasicBlock::iterator NextMIIt =
21773 std::next(MachineBasicBlock::iterator(MI));
21775 // Check for case 1, where there are multiple CMOVs with the same condition
21776 // first. Of the two cases of multiple CMOV lowerings, case 1 reduces the
21777 // number of jumps the most.
21779 if (isCMOVPseudo(MI)) {
21780 // See if we have a string of CMOVS with the same condition.
21781 while (NextMIIt != BB->end() &&
21782 isCMOVPseudo(NextMIIt) &&
21783 (NextMIIt->getOperand(3).getImm() == CC ||
21784 NextMIIt->getOperand(3).getImm() == OppCC)) {
21785 LastCMOV = &*NextMIIt;
21790 // This checks for case 2, but only do this if we didn't already find
21791 // case 1, as indicated by LastCMOV == MI.
21792 if (LastCMOV == MI &&
21793 NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
21794 NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
21795 NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg()) {
21796 CascadedCMOV = &*NextMIIt;
21799 MachineBasicBlock *jcc1MBB = nullptr;
21801 // If we have a cascaded CMOV, we lower it to two successive branches to
21802 // the same block. EFLAGS is used by both, so mark it as live in the second.
21803 if (CascadedCMOV) {
21804 jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
21805 F->insert(It, jcc1MBB);
21806 jcc1MBB->addLiveIn(X86::EFLAGS);
21809 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
21810 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
21811 F->insert(It, copy0MBB);
21812 F->insert(It, sinkMBB);
21814 // If the EFLAGS register isn't dead in the terminator, then claim that it's
21815 // live into the sink and copy blocks.
21816 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
21818 MachineInstr *LastEFLAGSUser = CascadedCMOV ? CascadedCMOV : LastCMOV;
21819 if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
21820 !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
21821 copy0MBB->addLiveIn(X86::EFLAGS);
21822 sinkMBB->addLiveIn(X86::EFLAGS);
21825 // Transfer the remainder of BB and its successor edges to sinkMBB.
21826 sinkMBB->splice(sinkMBB->begin(), BB,
21827 std::next(MachineBasicBlock::iterator(LastCMOV)), BB->end());
21828 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
21830 // Add the true and fallthrough blocks as its successors.
21831 if (CascadedCMOV) {
21832 // The fallthrough block may be jcc1MBB, if we have a cascaded CMOV.
21833 BB->addSuccessor(jcc1MBB);
21835 // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
21836 // jump to the sinkMBB.
21837 jcc1MBB->addSuccessor(copy0MBB);
21838 jcc1MBB->addSuccessor(sinkMBB);
21840 BB->addSuccessor(copy0MBB);
21843 // The true block target of the first (or only) branch is always sinkMBB.
21844 BB->addSuccessor(sinkMBB);
21846 // Create the conditional branch instruction.
21847 unsigned Opc = X86::GetCondBranchFromCond(CC);
21848 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
21850 if (CascadedCMOV) {
21851 unsigned Opc2 = X86::GetCondBranchFromCond(
21852 (X86::CondCode)CascadedCMOV->getOperand(3).getImm());
21853 BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
21857 // %FalseValue = ...
21858 // # fallthrough to sinkMBB
21859 copy0MBB->addSuccessor(sinkMBB);
21862 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
21864 MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
21865 MachineBasicBlock::iterator MIItEnd =
21866 std::next(MachineBasicBlock::iterator(LastCMOV));
21867 MachineBasicBlock::iterator SinkInsertionPoint = sinkMBB->begin();
21868 DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
21869 MachineInstrBuilder MIB;
21871 // As we are creating the PHIs, we have to be careful if there is more than
21872 // one. Later CMOVs may reference the results of earlier CMOVs, but later
21873 // PHIs have to reference the individual true/false inputs from earlier PHIs.
21874 // That also means that PHI construction must work forward from earlier to
21875 // later, and that the code must maintain a mapping from earlier PHI's
21876 // destination registers, and the registers that went into the PHI.
21878 for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
21879 unsigned DestReg = MIIt->getOperand(0).getReg();
21880 unsigned Op1Reg = MIIt->getOperand(1).getReg();
21881 unsigned Op2Reg = MIIt->getOperand(2).getReg();
21883 // If this CMOV we are generating is the opposite condition from
21884 // the jump we generated, then we have to swap the operands for the
21885 // PHI that is going to be generated.
21886 if (MIIt->getOperand(3).getImm() == OppCC)
21887 std::swap(Op1Reg, Op2Reg);
21889 if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
21890 Op1Reg = RegRewriteTable[Op1Reg].first;
21892 if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
21893 Op2Reg = RegRewriteTable[Op2Reg].second;
21895 MIB = BuildMI(*sinkMBB, SinkInsertionPoint, DL,
21896 TII->get(X86::PHI), DestReg)
21897 .addReg(Op1Reg).addMBB(copy0MBB)
21898 .addReg(Op2Reg).addMBB(thisMBB);
21900 // Add this PHI to the rewrite table.
21901 RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
21904 // If we have a cascaded CMOV, the second Jcc provides the same incoming
21905 // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
21906 if (CascadedCMOV) {
21907 MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
21908 // Copy the PHI result to the register defined by the second CMOV.
21909 BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
21910 DL, TII->get(TargetOpcode::COPY),
21911 CascadedCMOV->getOperand(0).getReg())
21912 .addReg(MI->getOperand(0).getReg());
21913 CascadedCMOV->eraseFromParent();
21916 // Now remove the CMOV(s).
21917 for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; )
21918 (MIIt++)->eraseFromParent();
21923 MachineBasicBlock *
21924 X86TargetLowering::EmitLoweredAtomicFP(MachineInstr *MI,
21925 MachineBasicBlock *BB) const {
21926 // Combine the following atomic floating-point modification pattern:
21927 // a.store(reg OP a.load(acquire), release)
21928 // Transform them into:
21929 // OPss (%gpr), %xmm
21930 // movss %xmm, (%gpr)
21931 // Or sd equivalent for 64-bit operations.
21933 switch (MI->getOpcode()) {
21934 default: llvm_unreachable("unexpected instr type for EmitLoweredAtomicFP");
21935 case X86::RELEASE_FADD32mr: MOp = X86::MOVSSmr; FOp = X86::ADDSSrm; break;
21936 case X86::RELEASE_FADD64mr: MOp = X86::MOVSDmr; FOp = X86::ADDSDrm; break;
21938 const X86InstrInfo *TII = Subtarget->getInstrInfo();
21939 DebugLoc DL = MI->getDebugLoc();
21940 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
21941 MachineOperand MSrc = MI->getOperand(0);
21942 unsigned VSrc = MI->getOperand(5).getReg();
21943 const MachineOperand &Disp = MI->getOperand(3);
21944 MachineOperand ZeroDisp = MachineOperand::CreateImm(0);
21945 bool hasDisp = Disp.isGlobal() || Disp.isImm();
21946 if (hasDisp && MSrc.isReg())
21947 MSrc.setIsKill(false);
21948 MachineInstrBuilder MIM = BuildMI(*BB, MI, DL, TII->get(MOp))
21949 .addOperand(/*Base=*/MSrc)
21950 .addImm(/*Scale=*/1)
21951 .addReg(/*Index=*/0)
21952 .addDisp(hasDisp ? Disp : ZeroDisp, /*off=*/0)
21954 MachineInstr *MIO = BuildMI(*BB, (MachineInstr *)MIM, DL, TII->get(FOp),
21955 MRI.createVirtualRegister(MRI.getRegClass(VSrc)))
21957 .addOperand(/*Base=*/MSrc)
21958 .addImm(/*Scale=*/1)
21959 .addReg(/*Index=*/0)
21960 .addDisp(hasDisp ? Disp : ZeroDisp, /*off=*/0)
21961 .addReg(/*Segment=*/0);
21962 MIM.addReg(MIO->getOperand(0).getReg(), RegState::Kill);
21963 MI->eraseFromParent(); // The pseudo instruction is gone now.
21967 MachineBasicBlock *
21968 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
21969 MachineBasicBlock *BB) const {
21970 MachineFunction *MF = BB->getParent();
21971 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21972 DebugLoc DL = MI->getDebugLoc();
21973 const BasicBlock *LLVM_BB = BB->getBasicBlock();
21975 assert(MF->shouldSplitStack());
21977 const bool Is64Bit = Subtarget->is64Bit();
21978 const bool IsLP64 = Subtarget->isTarget64BitLP64();
21980 const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
21981 const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
21984 // ... [Till the alloca]
21985 // If stacklet is not large enough, jump to mallocMBB
21988 // Allocate by subtracting from RSP
21989 // Jump to continueMBB
21992 // Allocate by call to runtime
21996 // [rest of original BB]
21999 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
22000 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
22001 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
22003 MachineRegisterInfo &MRI = MF->getRegInfo();
22004 const TargetRegisterClass *AddrRegClass =
22005 getRegClassFor(getPointerTy(MF->getDataLayout()));
22007 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
22008 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
22009 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
22010 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
22011 sizeVReg = MI->getOperand(1).getReg(),
22012 physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
22014 MachineFunction::iterator MBBIter = ++BB->getIterator();
22016 MF->insert(MBBIter, bumpMBB);
22017 MF->insert(MBBIter, mallocMBB);
22018 MF->insert(MBBIter, continueMBB);
22020 continueMBB->splice(continueMBB->begin(), BB,
22021 std::next(MachineBasicBlock::iterator(MI)), BB->end());
22022 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
22024 // Add code to the main basic block to check if the stack limit has been hit,
22025 // and if so, jump to mallocMBB otherwise to bumpMBB.
22026 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
22027 BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
22028 .addReg(tmpSPVReg).addReg(sizeVReg);
22029 BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
22030 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
22031 .addReg(SPLimitVReg);
22032 BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
22034 // bumpMBB simply decreases the stack pointer, since we know the current
22035 // stacklet has enough space.
22036 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
22037 .addReg(SPLimitVReg);
22038 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
22039 .addReg(SPLimitVReg);
22040 BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
22042 // Calls into a routine in libgcc to allocate more space from the heap.
22043 const uint32_t *RegMask =
22044 Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
22046 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
22048 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
22049 .addExternalSymbol("__morestack_allocate_stack_space")
22050 .addRegMask(RegMask)
22051 .addReg(X86::RDI, RegState::Implicit)
22052 .addReg(X86::RAX, RegState::ImplicitDefine);
22053 } else if (Is64Bit) {
22054 BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
22056 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
22057 .addExternalSymbol("__morestack_allocate_stack_space")
22058 .addRegMask(RegMask)
22059 .addReg(X86::EDI, RegState::Implicit)
22060 .addReg(X86::EAX, RegState::ImplicitDefine);
22062 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
22064 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
22065 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
22066 .addExternalSymbol("__morestack_allocate_stack_space")
22067 .addRegMask(RegMask)
22068 .addReg(X86::EAX, RegState::ImplicitDefine);
22072 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
22075 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
22076 .addReg(IsLP64 ? X86::RAX : X86::EAX);
22077 BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
22079 // Set up the CFG correctly.
22080 BB->addSuccessor(bumpMBB);
22081 BB->addSuccessor(mallocMBB);
22082 mallocMBB->addSuccessor(continueMBB);
22083 bumpMBB->addSuccessor(continueMBB);
22085 // Take care of the PHI nodes.
22086 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
22087 MI->getOperand(0).getReg())
22088 .addReg(mallocPtrVReg).addMBB(mallocMBB)
22089 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
22091 // Delete the original pseudo instruction.
22092 MI->eraseFromParent();
22095 return continueMBB;
22098 MachineBasicBlock *
22099 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
22100 MachineBasicBlock *BB) const {
22101 assert(!Subtarget->isTargetMachO());
22102 DebugLoc DL = MI->getDebugLoc();
22103 MachineInstr *ResumeMI = Subtarget->getFrameLowering()->emitStackProbe(
22104 *BB->getParent(), *BB, MI, DL, false);
22105 MachineBasicBlock *ResumeBB = ResumeMI->getParent();
22106 MI->eraseFromParent(); // The pseudo instruction is gone now.
22110 MachineBasicBlock *
22111 X86TargetLowering::EmitLoweredCatchRet(MachineInstr *MI,
22112 MachineBasicBlock *BB) const {
22113 MachineFunction *MF = BB->getParent();
22114 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
22115 MachineBasicBlock *TargetMBB = MI->getOperand(0).getMBB();
22116 DebugLoc DL = MI->getDebugLoc();
22118 assert(!isAsynchronousEHPersonality(
22119 classifyEHPersonality(MF->getFunction()->getPersonalityFn())) &&
22120 "SEH does not use catchret!");
22122 // Only 32-bit EH needs to worry about manually restoring stack pointers.
22123 if (!Subtarget->is32Bit())
22126 // C++ EH creates a new target block to hold the restore code, and wires up
22127 // the new block to the return destination with a normal JMP_4.
22128 MachineBasicBlock *RestoreMBB =
22129 MF->CreateMachineBasicBlock(BB->getBasicBlock());
22130 assert(BB->succ_size() == 1);
22131 MF->insert(std::next(BB->getIterator()), RestoreMBB);
22132 RestoreMBB->transferSuccessorsAndUpdatePHIs(BB);
22133 BB->addSuccessor(RestoreMBB);
22134 MI->getOperand(0).setMBB(RestoreMBB);
22136 auto RestoreMBBI = RestoreMBB->begin();
22137 BuildMI(*RestoreMBB, RestoreMBBI, DL, TII.get(X86::EH_RESTORE));
22138 BuildMI(*RestoreMBB, RestoreMBBI, DL, TII.get(X86::JMP_4)).addMBB(TargetMBB);
22142 MachineBasicBlock *
22143 X86TargetLowering::EmitLoweredCatchPad(MachineInstr *MI,
22144 MachineBasicBlock *BB) const {
22145 MachineFunction *MF = BB->getParent();
22146 const Constant *PerFn = MF->getFunction()->getPersonalityFn();
22147 bool IsSEH = isAsynchronousEHPersonality(classifyEHPersonality(PerFn));
22148 // Only 32-bit SEH requires special handling for catchpad.
22149 if (IsSEH && Subtarget->is32Bit()) {
22150 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
22151 DebugLoc DL = MI->getDebugLoc();
22152 BuildMI(*BB, MI, DL, TII.get(X86::EH_RESTORE));
22154 MI->eraseFromParent();
22158 MachineBasicBlock *
22159 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
22160 MachineBasicBlock *BB) const {
22161 // This is pretty easy. We're taking the value that we received from
22162 // our load from the relocation, sticking it in either RDI (x86-64)
22163 // or EAX and doing an indirect call. The return value will then
22164 // be in the normal return register.
22165 MachineFunction *F = BB->getParent();
22166 const X86InstrInfo *TII = Subtarget->getInstrInfo();
22167 DebugLoc DL = MI->getDebugLoc();
22169 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
22170 assert(MI->getOperand(3).isGlobal() && "This should be a global");
22172 // Get a register mask for the lowered call.
22173 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
22174 // proper register mask.
22175 const uint32_t *RegMask =
22176 Subtarget->is64Bit() ?
22177 Subtarget->getRegisterInfo()->getDarwinTLSCallPreservedMask() :
22178 Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
22179 if (Subtarget->is64Bit()) {
22180 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
22181 TII->get(X86::MOV64rm), X86::RDI)
22183 .addImm(0).addReg(0)
22184 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
22185 MI->getOperand(3).getTargetFlags())
22187 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
22188 addDirectMem(MIB, X86::RDI);
22189 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
22190 } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
22191 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
22192 TII->get(X86::MOV32rm), X86::EAX)
22194 .addImm(0).addReg(0)
22195 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
22196 MI->getOperand(3).getTargetFlags())
22198 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
22199 addDirectMem(MIB, X86::EAX);
22200 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
22202 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
22203 TII->get(X86::MOV32rm), X86::EAX)
22204 .addReg(TII->getGlobalBaseReg(F))
22205 .addImm(0).addReg(0)
22206 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
22207 MI->getOperand(3).getTargetFlags())
22209 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
22210 addDirectMem(MIB, X86::EAX);
22211 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
22214 MI->eraseFromParent(); // The pseudo instruction is gone now.
22218 MachineBasicBlock *
22219 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
22220 MachineBasicBlock *MBB) const {
22221 DebugLoc DL = MI->getDebugLoc();
22222 MachineFunction *MF = MBB->getParent();
22223 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22224 MachineRegisterInfo &MRI = MF->getRegInfo();
22226 const BasicBlock *BB = MBB->getBasicBlock();
22227 MachineFunction::iterator I = ++MBB->getIterator();
22229 // Memory Reference
22230 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
22231 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
22234 unsigned MemOpndSlot = 0;
22236 unsigned CurOp = 0;
22238 DstReg = MI->getOperand(CurOp++).getReg();
22239 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
22240 assert(RC->hasType(MVT::i32) && "Invalid destination!");
22241 unsigned mainDstReg = MRI.createVirtualRegister(RC);
22242 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
22244 MemOpndSlot = CurOp;
22246 MVT PVT = getPointerTy(MF->getDataLayout());
22247 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
22248 "Invalid Pointer Size!");
22250 // For v = setjmp(buf), we generate
22253 // buf[LabelOffset] = restoreMBB <-- takes address of restoreMBB
22254 // SjLjSetup restoreMBB
22260 // v = phi(main, restore)
22263 // if base pointer being used, load it from frame
22266 MachineBasicBlock *thisMBB = MBB;
22267 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
22268 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
22269 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
22270 MF->insert(I, mainMBB);
22271 MF->insert(I, sinkMBB);
22272 MF->push_back(restoreMBB);
22273 restoreMBB->setHasAddressTaken();
22275 MachineInstrBuilder MIB;
22277 // Transfer the remainder of BB and its successor edges to sinkMBB.
22278 sinkMBB->splice(sinkMBB->begin(), MBB,
22279 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
22280 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
22283 unsigned PtrStoreOpc = 0;
22284 unsigned LabelReg = 0;
22285 const int64_t LabelOffset = 1 * PVT.getStoreSize();
22286 Reloc::Model RM = MF->getTarget().getRelocationModel();
22287 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
22288 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
22290 // Prepare IP either in reg or imm.
22291 if (!UseImmLabel) {
22292 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
22293 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
22294 LabelReg = MRI.createVirtualRegister(PtrRC);
22295 if (Subtarget->is64Bit()) {
22296 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
22300 .addMBB(restoreMBB)
22303 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
22304 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
22305 .addReg(XII->getGlobalBaseReg(MF))
22308 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
22312 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
22314 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
22315 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
22316 if (i == X86::AddrDisp)
22317 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
22319 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
22322 MIB.addReg(LabelReg);
22324 MIB.addMBB(restoreMBB);
22325 MIB.setMemRefs(MMOBegin, MMOEnd);
22327 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
22328 .addMBB(restoreMBB);
22330 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
22331 MIB.addRegMask(RegInfo->getNoPreservedMask());
22332 thisMBB->addSuccessor(mainMBB);
22333 thisMBB->addSuccessor(restoreMBB);
22337 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
22338 mainMBB->addSuccessor(sinkMBB);
22341 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
22342 TII->get(X86::PHI), DstReg)
22343 .addReg(mainDstReg).addMBB(mainMBB)
22344 .addReg(restoreDstReg).addMBB(restoreMBB);
22347 if (RegInfo->hasBasePointer(*MF)) {
22348 const bool Uses64BitFramePtr =
22349 Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
22350 X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
22351 X86FI->setRestoreBasePointer(MF);
22352 unsigned FramePtr = RegInfo->getFrameRegister(*MF);
22353 unsigned BasePtr = RegInfo->getBaseRegister();
22354 unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
22355 addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
22356 FramePtr, true, X86FI->getRestoreBasePointerOffset())
22357 .setMIFlag(MachineInstr::FrameSetup);
22359 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
22360 BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
22361 restoreMBB->addSuccessor(sinkMBB);
22363 MI->eraseFromParent();
22367 MachineBasicBlock *
22368 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
22369 MachineBasicBlock *MBB) const {
22370 DebugLoc DL = MI->getDebugLoc();
22371 MachineFunction *MF = MBB->getParent();
22372 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22373 MachineRegisterInfo &MRI = MF->getRegInfo();
22375 // Memory Reference
22376 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
22377 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
22379 MVT PVT = getPointerTy(MF->getDataLayout());
22380 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
22381 "Invalid Pointer Size!");
22383 const TargetRegisterClass *RC =
22384 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
22385 unsigned Tmp = MRI.createVirtualRegister(RC);
22386 // Since FP is only updated here but NOT referenced, it's treated as GPR.
22387 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
22388 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
22389 unsigned SP = RegInfo->getStackRegister();
22391 MachineInstrBuilder MIB;
22393 const int64_t LabelOffset = 1 * PVT.getStoreSize();
22394 const int64_t SPOffset = 2 * PVT.getStoreSize();
22396 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
22397 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
22400 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
22401 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
22402 MIB.addOperand(MI->getOperand(i));
22403 MIB.setMemRefs(MMOBegin, MMOEnd);
22405 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
22406 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
22407 if (i == X86::AddrDisp)
22408 MIB.addDisp(MI->getOperand(i), LabelOffset);
22410 MIB.addOperand(MI->getOperand(i));
22412 MIB.setMemRefs(MMOBegin, MMOEnd);
22414 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
22415 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
22416 if (i == X86::AddrDisp)
22417 MIB.addDisp(MI->getOperand(i), SPOffset);
22419 MIB.addOperand(MI->getOperand(i));
22421 MIB.setMemRefs(MMOBegin, MMOEnd);
22423 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
22425 MI->eraseFromParent();
22429 // Replace 213-type (isel default) FMA3 instructions with 231-type for
22430 // accumulator loops. Writing back to the accumulator allows the coalescer
22431 // to remove extra copies in the loop.
22432 // FIXME: Do this on AVX512. We don't support 231 variants yet (PR23937).
22433 MachineBasicBlock *
22434 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
22435 MachineBasicBlock *MBB) const {
22436 MachineOperand &AddendOp = MI->getOperand(3);
22438 // Bail out early if the addend isn't a register - we can't switch these.
22439 if (!AddendOp.isReg())
22442 MachineFunction &MF = *MBB->getParent();
22443 MachineRegisterInfo &MRI = MF.getRegInfo();
22445 // Check whether the addend is defined by a PHI:
22446 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
22447 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
22448 if (!AddendDef.isPHI())
22451 // Look for the following pattern:
22453 // %addend = phi [%entry, 0], [%loop, %result]
22455 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
22459 // %addend = phi [%entry, 0], [%loop, %result]
22461 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
22463 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
22464 assert(AddendDef.getOperand(i).isReg());
22465 MachineOperand PHISrcOp = AddendDef.getOperand(i);
22466 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
22467 if (&PHISrcInst == MI) {
22468 // Found a matching instruction.
22469 unsigned NewFMAOpc = 0;
22470 switch (MI->getOpcode()) {
22471 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
22472 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
22473 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
22474 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
22475 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
22476 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
22477 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
22478 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
22479 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
22480 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
22481 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
22482 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
22483 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
22484 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
22485 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
22486 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
22487 case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
22488 case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
22489 case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
22490 case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
22492 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
22493 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
22494 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
22495 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
22496 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
22497 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
22498 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
22499 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
22500 case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
22501 case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
22502 case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
22503 case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
22504 default: llvm_unreachable("Unrecognized FMA variant.");
22507 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
22508 MachineInstrBuilder MIB =
22509 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
22510 .addOperand(MI->getOperand(0))
22511 .addOperand(MI->getOperand(3))
22512 .addOperand(MI->getOperand(2))
22513 .addOperand(MI->getOperand(1));
22514 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
22515 MI->eraseFromParent();
22522 MachineBasicBlock *
22523 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
22524 MachineBasicBlock *BB) const {
22525 switch (MI->getOpcode()) {
22526 default: llvm_unreachable("Unexpected instr type to insert");
22527 case X86::TAILJMPd64:
22528 case X86::TAILJMPr64:
22529 case X86::TAILJMPm64:
22530 case X86::TAILJMPd64_REX:
22531 case X86::TAILJMPr64_REX:
22532 case X86::TAILJMPm64_REX:
22533 llvm_unreachable("TAILJMP64 would not be touched here.");
22534 case X86::TCRETURNdi64:
22535 case X86::TCRETURNri64:
22536 case X86::TCRETURNmi64:
22538 case X86::WIN_ALLOCA:
22539 return EmitLoweredWinAlloca(MI, BB);
22540 case X86::CATCHRET:
22541 return EmitLoweredCatchRet(MI, BB);
22542 case X86::CATCHPAD:
22543 return EmitLoweredCatchPad(MI, BB);
22544 case X86::SEG_ALLOCA_32:
22545 case X86::SEG_ALLOCA_64:
22546 return EmitLoweredSegAlloca(MI, BB);
22547 case X86::TLSCall_32:
22548 case X86::TLSCall_64:
22549 return EmitLoweredTLSCall(MI, BB);
22550 case X86::CMOV_FR32:
22551 case X86::CMOV_FR64:
22552 case X86::CMOV_FR128:
22553 case X86::CMOV_GR8:
22554 case X86::CMOV_GR16:
22555 case X86::CMOV_GR32:
22556 case X86::CMOV_RFP32:
22557 case X86::CMOV_RFP64:
22558 case X86::CMOV_RFP80:
22559 case X86::CMOV_V2F64:
22560 case X86::CMOV_V2I64:
22561 case X86::CMOV_V4F32:
22562 case X86::CMOV_V4F64:
22563 case X86::CMOV_V4I64:
22564 case X86::CMOV_V16F32:
22565 case X86::CMOV_V8F32:
22566 case X86::CMOV_V8F64:
22567 case X86::CMOV_V8I64:
22568 case X86::CMOV_V8I1:
22569 case X86::CMOV_V16I1:
22570 case X86::CMOV_V32I1:
22571 case X86::CMOV_V64I1:
22572 return EmitLoweredSelect(MI, BB);
22574 case X86::RDFLAGS32:
22575 case X86::RDFLAGS64: {
22576 DebugLoc DL = MI->getDebugLoc();
22577 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22579 MI->getOpcode() == X86::RDFLAGS32 ? X86::PUSHF32 : X86::PUSHF64;
22581 MI->getOpcode() == X86::RDFLAGS32 ? X86::POP32r : X86::POP64r;
22582 BuildMI(*BB, MI, DL, TII->get(PushF));
22583 BuildMI(*BB, MI, DL, TII->get(Pop), MI->getOperand(0).getReg());
22585 MI->eraseFromParent(); // The pseudo is gone now.
22589 case X86::WRFLAGS32:
22590 case X86::WRFLAGS64: {
22591 DebugLoc DL = MI->getDebugLoc();
22592 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22594 MI->getOpcode() == X86::WRFLAGS32 ? X86::PUSH32r : X86::PUSH64r;
22596 MI->getOpcode() == X86::WRFLAGS32 ? X86::POPF32 : X86::POPF64;
22597 BuildMI(*BB, MI, DL, TII->get(Push)).addReg(MI->getOperand(0).getReg());
22598 BuildMI(*BB, MI, DL, TII->get(PopF));
22600 MI->eraseFromParent(); // The pseudo is gone now.
22604 case X86::RELEASE_FADD32mr:
22605 case X86::RELEASE_FADD64mr:
22606 return EmitLoweredAtomicFP(MI, BB);
22608 case X86::FP32_TO_INT16_IN_MEM:
22609 case X86::FP32_TO_INT32_IN_MEM:
22610 case X86::FP32_TO_INT64_IN_MEM:
22611 case X86::FP64_TO_INT16_IN_MEM:
22612 case X86::FP64_TO_INT32_IN_MEM:
22613 case X86::FP64_TO_INT64_IN_MEM:
22614 case X86::FP80_TO_INT16_IN_MEM:
22615 case X86::FP80_TO_INT32_IN_MEM:
22616 case X86::FP80_TO_INT64_IN_MEM: {
22617 MachineFunction *F = BB->getParent();
22618 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22619 DebugLoc DL = MI->getDebugLoc();
22621 // Change the floating point control register to use "round towards zero"
22622 // mode when truncating to an integer value.
22623 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
22624 addFrameReference(BuildMI(*BB, MI, DL,
22625 TII->get(X86::FNSTCW16m)), CWFrameIdx);
22627 // Load the old value of the high byte of the control word...
22629 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
22630 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
22633 // Set the high part to be round to zero...
22634 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
22637 // Reload the modified control word now...
22638 addFrameReference(BuildMI(*BB, MI, DL,
22639 TII->get(X86::FLDCW16m)), CWFrameIdx);
22641 // Restore the memory image of control word to original value
22642 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
22645 // Get the X86 opcode to use.
22647 switch (MI->getOpcode()) {
22648 default: llvm_unreachable("illegal opcode!");
22649 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
22650 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
22651 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
22652 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
22653 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
22654 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
22655 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
22656 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
22657 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
22661 MachineOperand &Op = MI->getOperand(0);
22663 AM.BaseType = X86AddressMode::RegBase;
22664 AM.Base.Reg = Op.getReg();
22666 AM.BaseType = X86AddressMode::FrameIndexBase;
22667 AM.Base.FrameIndex = Op.getIndex();
22669 Op = MI->getOperand(1);
22671 AM.Scale = Op.getImm();
22672 Op = MI->getOperand(2);
22674 AM.IndexReg = Op.getImm();
22675 Op = MI->getOperand(3);
22676 if (Op.isGlobal()) {
22677 AM.GV = Op.getGlobal();
22679 AM.Disp = Op.getImm();
22681 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
22682 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
22684 // Reload the original control word now.
22685 addFrameReference(BuildMI(*BB, MI, DL,
22686 TII->get(X86::FLDCW16m)), CWFrameIdx);
22688 MI->eraseFromParent(); // The pseudo instruction is gone now.
22691 // String/text processing lowering.
22692 case X86::PCMPISTRM128REG:
22693 case X86::VPCMPISTRM128REG:
22694 case X86::PCMPISTRM128MEM:
22695 case X86::VPCMPISTRM128MEM:
22696 case X86::PCMPESTRM128REG:
22697 case X86::VPCMPESTRM128REG:
22698 case X86::PCMPESTRM128MEM:
22699 case X86::VPCMPESTRM128MEM:
22700 assert(Subtarget->hasSSE42() &&
22701 "Target must have SSE4.2 or AVX features enabled");
22702 return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
22704 // String/text processing lowering.
22705 case X86::PCMPISTRIREG:
22706 case X86::VPCMPISTRIREG:
22707 case X86::PCMPISTRIMEM:
22708 case X86::VPCMPISTRIMEM:
22709 case X86::PCMPESTRIREG:
22710 case X86::VPCMPESTRIREG:
22711 case X86::PCMPESTRIMEM:
22712 case X86::VPCMPESTRIMEM:
22713 assert(Subtarget->hasSSE42() &&
22714 "Target must have SSE4.2 or AVX features enabled");
22715 return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
22717 // Thread synchronization.
22719 return EmitMonitor(MI, BB, Subtarget);
22722 return EmitWRPKRU(MI, BB, Subtarget);
22724 return EmitRDPKRU(MI, BB, Subtarget);
22727 return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
22729 case X86::VASTART_SAVE_XMM_REGS:
22730 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
22732 case X86::VAARG_64:
22733 return EmitVAARG64WithCustomInserter(MI, BB);
22735 case X86::EH_SjLj_SetJmp32:
22736 case X86::EH_SjLj_SetJmp64:
22737 return emitEHSjLjSetJmp(MI, BB);
22739 case X86::EH_SjLj_LongJmp32:
22740 case X86::EH_SjLj_LongJmp64:
22741 return emitEHSjLjLongJmp(MI, BB);
22743 case TargetOpcode::STATEPOINT:
22744 // As an implementation detail, STATEPOINT shares the STACKMAP format at
22745 // this point in the process. We diverge later.
22746 return emitPatchPoint(MI, BB);
22748 case TargetOpcode::STACKMAP:
22749 case TargetOpcode::PATCHPOINT:
22750 return emitPatchPoint(MI, BB);
22752 case X86::VFMADDPDr213r:
22753 case X86::VFMADDPSr213r:
22754 case X86::VFMADDSDr213r:
22755 case X86::VFMADDSSr213r:
22756 case X86::VFMSUBPDr213r:
22757 case X86::VFMSUBPSr213r:
22758 case X86::VFMSUBSDr213r:
22759 case X86::VFMSUBSSr213r:
22760 case X86::VFNMADDPDr213r:
22761 case X86::VFNMADDPSr213r:
22762 case X86::VFNMADDSDr213r:
22763 case X86::VFNMADDSSr213r:
22764 case X86::VFNMSUBPDr213r:
22765 case X86::VFNMSUBPSr213r:
22766 case X86::VFNMSUBSDr213r:
22767 case X86::VFNMSUBSSr213r:
22768 case X86::VFMADDSUBPDr213r:
22769 case X86::VFMADDSUBPSr213r:
22770 case X86::VFMSUBADDPDr213r:
22771 case X86::VFMSUBADDPSr213r:
22772 case X86::VFMADDPDr213rY:
22773 case X86::VFMADDPSr213rY:
22774 case X86::VFMSUBPDr213rY:
22775 case X86::VFMSUBPSr213rY:
22776 case X86::VFNMADDPDr213rY:
22777 case X86::VFNMADDPSr213rY:
22778 case X86::VFNMSUBPDr213rY:
22779 case X86::VFNMSUBPSr213rY:
22780 case X86::VFMADDSUBPDr213rY:
22781 case X86::VFMADDSUBPSr213rY:
22782 case X86::VFMSUBADDPDr213rY:
22783 case X86::VFMSUBADDPSr213rY:
22784 return emitFMA3Instr(MI, BB);
22788 //===----------------------------------------------------------------------===//
22789 // X86 Optimization Hooks
22790 //===----------------------------------------------------------------------===//
22792 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
22795 const SelectionDAG &DAG,
22796 unsigned Depth) const {
22797 unsigned BitWidth = KnownZero.getBitWidth();
22798 unsigned Opc = Op.getOpcode();
22799 assert((Opc >= ISD::BUILTIN_OP_END ||
22800 Opc == ISD::INTRINSIC_WO_CHAIN ||
22801 Opc == ISD::INTRINSIC_W_CHAIN ||
22802 Opc == ISD::INTRINSIC_VOID) &&
22803 "Should use MaskedValueIsZero if you don't know whether Op"
22804 " is a target node!");
22806 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
22820 // These nodes' second result is a boolean.
22821 if (Op.getResNo() == 0)
22824 case X86ISD::SETCC:
22825 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
22827 case ISD::INTRINSIC_WO_CHAIN: {
22828 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
22829 unsigned NumLoBits = 0;
22832 case Intrinsic::x86_sse_movmsk_ps:
22833 case Intrinsic::x86_avx_movmsk_ps_256:
22834 case Intrinsic::x86_sse2_movmsk_pd:
22835 case Intrinsic::x86_avx_movmsk_pd_256:
22836 case Intrinsic::x86_mmx_pmovmskb:
22837 case Intrinsic::x86_sse2_pmovmskb_128:
22838 case Intrinsic::x86_avx2_pmovmskb: {
22839 // High bits of movmskp{s|d}, pmovmskb are known zero.
22841 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
22842 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
22843 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
22844 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
22845 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
22846 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
22847 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
22848 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
22850 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
22859 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
22861 const SelectionDAG &,
22862 unsigned Depth) const {
22863 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
22864 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
22865 return Op.getValueType().getScalarSizeInBits();
22871 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
22872 /// node is a GlobalAddress + offset.
22873 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
22874 const GlobalValue* &GA,
22875 int64_t &Offset) const {
22876 if (N->getOpcode() == X86ISD::Wrapper) {
22877 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
22878 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
22879 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
22883 return TargetLowering::isGAPlusOffset(N, GA, Offset);
22886 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
22887 /// FIXME: This could be expanded to support 512 bit vectors as well.
22888 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
22889 TargetLowering::DAGCombinerInfo &DCI,
22890 const X86Subtarget* Subtarget) {
22892 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22893 SDValue V1 = SVOp->getOperand(0);
22894 SDValue V2 = SVOp->getOperand(1);
22895 MVT VT = SVOp->getSimpleValueType(0);
22896 unsigned NumElems = VT.getVectorNumElements();
22898 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
22899 V2.getOpcode() == ISD::CONCAT_VECTORS) {
22903 // V UNDEF BUILD_VECTOR UNDEF
22905 // CONCAT_VECTOR CONCAT_VECTOR
22908 // RESULT: V + zero extended
22910 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
22911 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
22912 V1.getOperand(1).getOpcode() != ISD::UNDEF)
22915 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
22918 // To match the shuffle mask, the first half of the mask should
22919 // be exactly the first vector, and all the rest a splat with the
22920 // first element of the second one.
22921 for (unsigned i = 0; i != NumElems/2; ++i)
22922 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
22923 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
22926 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
22927 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
22928 if (Ld->hasNUsesOfValue(1, 0)) {
22929 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
22930 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
22932 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
22934 Ld->getPointerInfo(),
22935 Ld->getAlignment(),
22936 false/*isVolatile*/, true/*ReadMem*/,
22937 false/*WriteMem*/);
22939 // Make sure the newly-created LOAD is in the same position as Ld in
22940 // terms of dependency. We create a TokenFactor for Ld and ResNode,
22941 // and update uses of Ld's output chain to use the TokenFactor.
22942 if (Ld->hasAnyUseOfValue(1)) {
22943 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
22944 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
22945 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
22946 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
22947 SDValue(ResNode.getNode(), 1));
22950 return DAG.getBitcast(VT, ResNode);
22954 // Emit a zeroed vector and insert the desired subvector on its
22956 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
22957 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
22958 return DCI.CombineTo(N, InsV);
22964 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
22967 /// This is the leaf of the recursive combinine below. When we have found some
22968 /// chain of single-use x86 shuffle instructions and accumulated the combined
22969 /// shuffle mask represented by them, this will try to pattern match that mask
22970 /// into either a single instruction if there is a special purpose instruction
22971 /// for this operation, or into a PSHUFB instruction which is a fully general
22972 /// instruction but should only be used to replace chains over a certain depth.
22973 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
22974 int Depth, bool HasPSHUFB, SelectionDAG &DAG,
22975 TargetLowering::DAGCombinerInfo &DCI,
22976 const X86Subtarget *Subtarget) {
22977 assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
22979 // Find the operand that enters the chain. Note that multiple uses are OK
22980 // here, we're not going to remove the operand we find.
22981 SDValue Input = Op.getOperand(0);
22982 while (Input.getOpcode() == ISD::BITCAST)
22983 Input = Input.getOperand(0);
22985 MVT VT = Input.getSimpleValueType();
22986 MVT RootVT = Root.getSimpleValueType();
22989 if (Mask.size() == 1) {
22990 int Index = Mask[0];
22991 assert((Index >= 0 || Index == SM_SentinelUndef ||
22992 Index == SM_SentinelZero) &&
22993 "Invalid shuffle index found!");
22995 // We may end up with an accumulated mask of size 1 as a result of
22996 // widening of shuffle operands (see function canWidenShuffleElements).
22997 // If the only shuffle index is equal to SM_SentinelZero then propagate
22998 // a zero vector. Otherwise, the combine shuffle mask is a no-op shuffle
22999 // mask, and therefore the entire chain of shuffles can be folded away.
23000 if (Index == SM_SentinelZero)
23001 DCI.CombineTo(Root.getNode(), getZeroVector(RootVT, Subtarget, DAG, DL));
23003 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
23008 // Use the float domain if the operand type is a floating point type.
23009 bool FloatDomain = VT.isFloatingPoint();
23011 // For floating point shuffles, we don't have free copies in the shuffle
23012 // instructions or the ability to load as part of the instruction, so
23013 // canonicalize their shuffles to UNPCK or MOV variants.
23015 // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
23016 // vectors because it can have a load folded into it that UNPCK cannot. This
23017 // doesn't preclude something switching to the shorter encoding post-RA.
23019 // FIXME: Should teach these routines about AVX vector widths.
23020 if (FloatDomain && VT.is128BitVector()) {
23021 if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
23022 bool Lo = Mask.equals({0, 0});
23025 // Check if we have SSE3 which will let us use MOVDDUP. That instruction
23026 // is no slower than UNPCKLPD but has the option to fold the input operand
23027 // into even an unaligned memory load.
23028 if (Lo && Subtarget->hasSSE3()) {
23029 Shuffle = X86ISD::MOVDDUP;
23030 ShuffleVT = MVT::v2f64;
23032 // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
23033 // than the UNPCK variants.
23034 Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
23035 ShuffleVT = MVT::v4f32;
23037 if (Depth == 1 && Root->getOpcode() == Shuffle)
23038 return false; // Nothing to do!
23039 Op = DAG.getBitcast(ShuffleVT, Input);
23040 DCI.AddToWorklist(Op.getNode());
23041 if (Shuffle == X86ISD::MOVDDUP)
23042 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
23044 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
23045 DCI.AddToWorklist(Op.getNode());
23046 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
23050 if (Subtarget->hasSSE3() &&
23051 (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
23052 bool Lo = Mask.equals({0, 0, 2, 2});
23053 unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
23054 MVT ShuffleVT = MVT::v4f32;
23055 if (Depth == 1 && Root->getOpcode() == Shuffle)
23056 return false; // Nothing to do!
23057 Op = DAG.getBitcast(ShuffleVT, Input);
23058 DCI.AddToWorklist(Op.getNode());
23059 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
23060 DCI.AddToWorklist(Op.getNode());
23061 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
23065 if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
23066 bool Lo = Mask.equals({0, 0, 1, 1});
23067 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
23068 MVT ShuffleVT = MVT::v4f32;
23069 if (Depth == 1 && Root->getOpcode() == Shuffle)
23070 return false; // Nothing to do!
23071 Op = DAG.getBitcast(ShuffleVT, Input);
23072 DCI.AddToWorklist(Op.getNode());
23073 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
23074 DCI.AddToWorklist(Op.getNode());
23075 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
23081 // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
23082 // variants as none of these have single-instruction variants that are
23083 // superior to the UNPCK formulation.
23084 if (!FloatDomain && VT.is128BitVector() &&
23085 (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
23086 Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
23087 Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
23089 {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
23090 bool Lo = Mask[0] == 0;
23091 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
23092 if (Depth == 1 && Root->getOpcode() == Shuffle)
23093 return false; // Nothing to do!
23095 switch (Mask.size()) {
23097 ShuffleVT = MVT::v8i16;
23100 ShuffleVT = MVT::v16i8;
23103 llvm_unreachable("Impossible mask size!");
23105 Op = DAG.getBitcast(ShuffleVT, Input);
23106 DCI.AddToWorklist(Op.getNode());
23107 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
23108 DCI.AddToWorklist(Op.getNode());
23109 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
23114 // Don't try to re-form single instruction chains under any circumstances now
23115 // that we've done encoding canonicalization for them.
23119 // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
23120 // can replace them with a single PSHUFB instruction profitably. Intel's
23121 // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
23122 // in practice PSHUFB tends to be *very* fast so we're more aggressive.
23123 if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
23124 SmallVector<SDValue, 16> PSHUFBMask;
23125 int NumBytes = VT.getSizeInBits() / 8;
23126 int Ratio = NumBytes / Mask.size();
23127 for (int i = 0; i < NumBytes; ++i) {
23128 if (Mask[i / Ratio] == SM_SentinelUndef) {
23129 PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
23132 int M = Mask[i / Ratio] != SM_SentinelZero
23133 ? Ratio * Mask[i / Ratio] + i % Ratio
23135 PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
23137 MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
23138 Op = DAG.getBitcast(ByteVT, Input);
23139 DCI.AddToWorklist(Op.getNode());
23140 SDValue PSHUFBMaskOp =
23141 DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
23142 DCI.AddToWorklist(PSHUFBMaskOp.getNode());
23143 Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
23144 DCI.AddToWorklist(Op.getNode());
23145 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
23150 // Failed to find any combines.
23154 /// \brief Fully generic combining of x86 shuffle instructions.
23156 /// This should be the last combine run over the x86 shuffle instructions. Once
23157 /// they have been fully optimized, this will recursively consider all chains
23158 /// of single-use shuffle instructions, build a generic model of the cumulative
23159 /// shuffle operation, and check for simpler instructions which implement this
23160 /// operation. We use this primarily for two purposes:
23162 /// 1) Collapse generic shuffles to specialized single instructions when
23163 /// equivalent. In most cases, this is just an encoding size win, but
23164 /// sometimes we will collapse multiple generic shuffles into a single
23165 /// special-purpose shuffle.
23166 /// 2) Look for sequences of shuffle instructions with 3 or more total
23167 /// instructions, and replace them with the slightly more expensive SSSE3
23168 /// PSHUFB instruction if available. We do this as the last combining step
23169 /// to ensure we avoid using PSHUFB if we can implement the shuffle with
23170 /// a suitable short sequence of other instructions. The PHUFB will either
23171 /// use a register or have to read from memory and so is slightly (but only
23172 /// slightly) more expensive than the other shuffle instructions.
23174 /// Because this is inherently a quadratic operation (for each shuffle in
23175 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
23176 /// This should never be an issue in practice as the shuffle lowering doesn't
23177 /// produce sequences of more than 8 instructions.
23179 /// FIXME: We will currently miss some cases where the redundant shuffling
23180 /// would simplify under the threshold for PSHUFB formation because of
23181 /// combine-ordering. To fix this, we should do the redundant instruction
23182 /// combining in this recursive walk.
23183 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
23184 ArrayRef<int> RootMask,
23185 int Depth, bool HasPSHUFB,
23187 TargetLowering::DAGCombinerInfo &DCI,
23188 const X86Subtarget *Subtarget) {
23189 // Bound the depth of our recursive combine because this is ultimately
23190 // quadratic in nature.
23194 // Directly rip through bitcasts to find the underlying operand.
23195 while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
23196 Op = Op.getOperand(0);
23198 MVT VT = Op.getSimpleValueType();
23199 if (!VT.isVector())
23200 return false; // Bail if we hit a non-vector.
23202 assert(Root.getSimpleValueType().isVector() &&
23203 "Shuffles operate on vector types!");
23204 assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
23205 "Can only combine shuffles of the same vector register size.");
23207 if (!isTargetShuffle(Op.getOpcode()))
23209 SmallVector<int, 16> OpMask;
23211 bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, true, OpMask, IsUnary);
23212 // We only can combine unary shuffles which we can decode the mask for.
23213 if (!HaveMask || !IsUnary)
23216 assert(VT.getVectorNumElements() == OpMask.size() &&
23217 "Different mask size from vector size!");
23218 assert(((RootMask.size() > OpMask.size() &&
23219 RootMask.size() % OpMask.size() == 0) ||
23220 (OpMask.size() > RootMask.size() &&
23221 OpMask.size() % RootMask.size() == 0) ||
23222 OpMask.size() == RootMask.size()) &&
23223 "The smaller number of elements must divide the larger.");
23224 int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
23225 int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
23226 assert(((RootRatio == 1 && OpRatio == 1) ||
23227 (RootRatio == 1) != (OpRatio == 1)) &&
23228 "Must not have a ratio for both incoming and op masks!");
23230 SmallVector<int, 16> Mask;
23231 Mask.reserve(std::max(OpMask.size(), RootMask.size()));
23233 // Merge this shuffle operation's mask into our accumulated mask. Note that
23234 // this shuffle's mask will be the first applied to the input, followed by the
23235 // root mask to get us all the way to the root value arrangement. The reason
23236 // for this order is that we are recursing up the operation chain.
23237 for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
23238 int RootIdx = i / RootRatio;
23239 if (RootMask[RootIdx] < 0) {
23240 // This is a zero or undef lane, we're done.
23241 Mask.push_back(RootMask[RootIdx]);
23245 int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
23246 int OpIdx = RootMaskedIdx / OpRatio;
23247 if (OpMask[OpIdx] < 0) {
23248 // The incoming lanes are zero or undef, it doesn't matter which ones we
23250 Mask.push_back(OpMask[OpIdx]);
23254 // Ok, we have non-zero lanes, map them through.
23255 Mask.push_back(OpMask[OpIdx] * OpRatio +
23256 RootMaskedIdx % OpRatio);
23259 // See if we can recurse into the operand to combine more things.
23260 switch (Op.getOpcode()) {
23261 case X86ISD::PSHUFB:
23263 case X86ISD::PSHUFD:
23264 case X86ISD::PSHUFHW:
23265 case X86ISD::PSHUFLW:
23266 if (Op.getOperand(0).hasOneUse() &&
23267 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
23268 HasPSHUFB, DAG, DCI, Subtarget))
23272 case X86ISD::UNPCKL:
23273 case X86ISD::UNPCKH:
23274 assert(Op.getOperand(0) == Op.getOperand(1) &&
23275 "We only combine unary shuffles!");
23276 // We can't check for single use, we have to check that this shuffle is the
23278 if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
23279 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
23280 HasPSHUFB, DAG, DCI, Subtarget))
23285 // Minor canonicalization of the accumulated shuffle mask to make it easier
23286 // to match below. All this does is detect masks with squential pairs of
23287 // elements, and shrink them to the half-width mask. It does this in a loop
23288 // so it will reduce the size of the mask to the minimal width mask which
23289 // performs an equivalent shuffle.
23290 SmallVector<int, 16> WidenedMask;
23291 while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
23292 Mask = std::move(WidenedMask);
23293 WidenedMask.clear();
23296 return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
23300 /// \brief Get the PSHUF-style mask from PSHUF node.
23302 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
23303 /// PSHUF-style masks that can be reused with such instructions.
23304 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
23305 MVT VT = N.getSimpleValueType();
23306 SmallVector<int, 4> Mask;
23308 bool HaveMask = getTargetShuffleMask(N.getNode(), VT, false, Mask, IsUnary);
23312 // If we have more than 128-bits, only the low 128-bits of shuffle mask
23313 // matter. Check that the upper masks are repeats and remove them.
23314 if (VT.getSizeInBits() > 128) {
23315 int LaneElts = 128 / VT.getScalarSizeInBits();
23317 for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
23318 for (int j = 0; j < LaneElts; ++j)
23319 assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
23320 "Mask doesn't repeat in high 128-bit lanes!");
23322 Mask.resize(LaneElts);
23325 switch (N.getOpcode()) {
23326 case X86ISD::PSHUFD:
23328 case X86ISD::PSHUFLW:
23331 case X86ISD::PSHUFHW:
23332 Mask.erase(Mask.begin(), Mask.begin() + 4);
23333 for (int &M : Mask)
23337 llvm_unreachable("No valid shuffle instruction found!");
23341 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
23343 /// We walk up the chain and look for a combinable shuffle, skipping over
23344 /// shuffles that we could hoist this shuffle's transformation past without
23345 /// altering anything.
23347 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
23349 TargetLowering::DAGCombinerInfo &DCI) {
23350 assert(N.getOpcode() == X86ISD::PSHUFD &&
23351 "Called with something other than an x86 128-bit half shuffle!");
23354 // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
23355 // of the shuffles in the chain so that we can form a fresh chain to replace
23357 SmallVector<SDValue, 8> Chain;
23358 SDValue V = N.getOperand(0);
23359 for (; V.hasOneUse(); V = V.getOperand(0)) {
23360 switch (V.getOpcode()) {
23362 return SDValue(); // Nothing combined!
23365 // Skip bitcasts as we always know the type for the target specific
23369 case X86ISD::PSHUFD:
23370 // Found another dword shuffle.
23373 case X86ISD::PSHUFLW:
23374 // Check that the low words (being shuffled) are the identity in the
23375 // dword shuffle, and the high words are self-contained.
23376 if (Mask[0] != 0 || Mask[1] != 1 ||
23377 !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
23380 Chain.push_back(V);
23383 case X86ISD::PSHUFHW:
23384 // Check that the high words (being shuffled) are the identity in the
23385 // dword shuffle, and the low words are self-contained.
23386 if (Mask[2] != 2 || Mask[3] != 3 ||
23387 !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
23390 Chain.push_back(V);
23393 case X86ISD::UNPCKL:
23394 case X86ISD::UNPCKH:
23395 // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
23396 // shuffle into a preceding word shuffle.
23397 if (V.getSimpleValueType().getVectorElementType() != MVT::i8 &&
23398 V.getSimpleValueType().getVectorElementType() != MVT::i16)
23401 // Search for a half-shuffle which we can combine with.
23402 unsigned CombineOp =
23403 V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
23404 if (V.getOperand(0) != V.getOperand(1) ||
23405 !V->isOnlyUserOf(V.getOperand(0).getNode()))
23407 Chain.push_back(V);
23408 V = V.getOperand(0);
23410 switch (V.getOpcode()) {
23412 return SDValue(); // Nothing to combine.
23414 case X86ISD::PSHUFLW:
23415 case X86ISD::PSHUFHW:
23416 if (V.getOpcode() == CombineOp)
23419 Chain.push_back(V);
23423 V = V.getOperand(0);
23427 } while (V.hasOneUse());
23430 // Break out of the loop if we break out of the switch.
23434 if (!V.hasOneUse())
23435 // We fell out of the loop without finding a viable combining instruction.
23438 // Merge this node's mask and our incoming mask.
23439 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
23440 for (int &M : Mask)
23442 V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
23443 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
23445 // Rebuild the chain around this new shuffle.
23446 while (!Chain.empty()) {
23447 SDValue W = Chain.pop_back_val();
23449 if (V.getValueType() != W.getOperand(0).getValueType())
23450 V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
23452 switch (W.getOpcode()) {
23454 llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
23456 case X86ISD::UNPCKL:
23457 case X86ISD::UNPCKH:
23458 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
23461 case X86ISD::PSHUFD:
23462 case X86ISD::PSHUFLW:
23463 case X86ISD::PSHUFHW:
23464 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
23468 if (V.getValueType() != N.getValueType())
23469 V = DAG.getBitcast(N.getValueType(), V);
23471 // Return the new chain to replace N.
23475 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or
23478 /// We walk up the chain, skipping shuffles of the other half and looking
23479 /// through shuffles which switch halves trying to find a shuffle of the same
23480 /// pair of dwords.
23481 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
23483 TargetLowering::DAGCombinerInfo &DCI) {
23485 (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
23486 "Called with something other than an x86 128-bit half shuffle!");
23488 unsigned CombineOpcode = N.getOpcode();
23490 // Walk up a single-use chain looking for a combinable shuffle.
23491 SDValue V = N.getOperand(0);
23492 for (; V.hasOneUse(); V = V.getOperand(0)) {
23493 switch (V.getOpcode()) {
23495 return false; // Nothing combined!
23498 // Skip bitcasts as we always know the type for the target specific
23502 case X86ISD::PSHUFLW:
23503 case X86ISD::PSHUFHW:
23504 if (V.getOpcode() == CombineOpcode)
23507 // Other-half shuffles are no-ops.
23510 // Break out of the loop if we break out of the switch.
23514 if (!V.hasOneUse())
23515 // We fell out of the loop without finding a viable combining instruction.
23518 // Combine away the bottom node as its shuffle will be accumulated into
23519 // a preceding shuffle.
23520 DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
23522 // Record the old value.
23525 // Merge this node's mask and our incoming mask (adjusted to account for all
23526 // the pshufd instructions encountered).
23527 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
23528 for (int &M : Mask)
23530 V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
23531 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
23533 // Check that the shuffles didn't cancel each other out. If not, we need to
23534 // combine to the new one.
23536 // Replace the combinable shuffle with the combined one, updating all users
23537 // so that we re-evaluate the chain here.
23538 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
23543 /// \brief Try to combine x86 target specific shuffles.
23544 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
23545 TargetLowering::DAGCombinerInfo &DCI,
23546 const X86Subtarget *Subtarget) {
23548 MVT VT = N.getSimpleValueType();
23549 SmallVector<int, 4> Mask;
23551 switch (N.getOpcode()) {
23552 case X86ISD::PSHUFD:
23553 case X86ISD::PSHUFLW:
23554 case X86ISD::PSHUFHW:
23555 Mask = getPSHUFShuffleMask(N);
23556 assert(Mask.size() == 4);
23558 case X86ISD::UNPCKL: {
23559 // Combine X86ISD::UNPCKL and ISD::VECTOR_SHUFFLE into X86ISD::UNPCKH, in
23560 // which X86ISD::UNPCKL has a ISD::UNDEF operand, and ISD::VECTOR_SHUFFLE
23561 // moves upper half elements into the lower half part. For example:
23563 // t2: v16i8 = vector_shuffle<8,9,10,11,12,13,14,15,u,u,u,u,u,u,u,u> t1,
23565 // t3: v16i8 = X86ISD::UNPCKL undef:v16i8, t2
23567 // will be combined to:
23569 // t3: v16i8 = X86ISD::UNPCKH undef:v16i8, t1
23571 // This is only for 128-bit vectors. From SSE4.1 onward this combine may not
23572 // happen due to advanced instructions.
23573 if (!VT.is128BitVector())
23576 auto Op0 = N.getOperand(0);
23577 auto Op1 = N.getOperand(1);
23578 if (Op0.getOpcode() == ISD::UNDEF &&
23579 Op1.getNode()->getOpcode() == ISD::VECTOR_SHUFFLE) {
23580 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op1.getNode())->getMask();
23582 unsigned NumElts = VT.getVectorNumElements();
23583 SmallVector<int, 8> ExpectedMask(NumElts, -1);
23584 std::iota(ExpectedMask.begin(), ExpectedMask.begin() + NumElts / 2,
23587 auto ShufOp = Op1.getOperand(0);
23588 if (isShuffleEquivalent(Op1, ShufOp, Mask, ExpectedMask))
23589 return DAG.getNode(X86ISD::UNPCKH, DL, VT, N.getOperand(0), ShufOp);
23593 case X86ISD::BLENDI: {
23594 SDValue V0 = N->getOperand(0);
23595 SDValue V1 = N->getOperand(1);
23596 assert(VT == V0.getSimpleValueType() && VT == V1.getSimpleValueType() &&
23597 "Unexpected input vector types");
23599 // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
23600 // operands and changing the mask to 1. This saves us a bunch of
23601 // pattern-matching possibilities related to scalar math ops in SSE/AVX.
23602 // x86InstrInfo knows how to commute this back after instruction selection
23603 // if it would help register allocation.
23605 // TODO: If optimizing for size or a processor that doesn't suffer from
23606 // partial register update stalls, this should be transformed into a MOVSD
23607 // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
23609 if (VT == MVT::v2f64)
23610 if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
23611 if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
23612 SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
23613 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
23622 // Nuke no-op shuffles that show up after combining.
23623 if (isNoopShuffleMask(Mask))
23624 return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
23626 // Look for simplifications involving one or two shuffle instructions.
23627 SDValue V = N.getOperand(0);
23628 switch (N.getOpcode()) {
23631 case X86ISD::PSHUFLW:
23632 case X86ISD::PSHUFHW:
23633 assert(VT.getVectorElementType() == MVT::i16 && "Bad word shuffle type!");
23635 if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
23636 return SDValue(); // We combined away this shuffle, so we're done.
23638 // See if this reduces to a PSHUFD which is no more expensive and can
23639 // combine with more operations. Note that it has to at least flip the
23640 // dwords as otherwise it would have been removed as a no-op.
23641 if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
23642 int DMask[] = {0, 1, 2, 3};
23643 int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
23644 DMask[DOffset + 0] = DOffset + 1;
23645 DMask[DOffset + 1] = DOffset + 0;
23646 MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
23647 V = DAG.getBitcast(DVT, V);
23648 DCI.AddToWorklist(V.getNode());
23649 V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
23650 getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
23651 DCI.AddToWorklist(V.getNode());
23652 return DAG.getBitcast(VT, V);
23655 // Look for shuffle patterns which can be implemented as a single unpack.
23656 // FIXME: This doesn't handle the location of the PSHUFD generically, and
23657 // only works when we have a PSHUFD followed by two half-shuffles.
23658 if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
23659 (V.getOpcode() == X86ISD::PSHUFLW ||
23660 V.getOpcode() == X86ISD::PSHUFHW) &&
23661 V.getOpcode() != N.getOpcode() &&
23663 SDValue D = V.getOperand(0);
23664 while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
23665 D = D.getOperand(0);
23666 if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
23667 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
23668 SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
23669 int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
23670 int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
23672 for (int i = 0; i < 4; ++i) {
23673 WordMask[i + NOffset] = Mask[i] + NOffset;
23674 WordMask[i + VOffset] = VMask[i] + VOffset;
23676 // Map the word mask through the DWord mask.
23678 for (int i = 0; i < 8; ++i)
23679 MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
23680 if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
23681 makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
23682 // We can replace all three shuffles with an unpack.
23683 V = DAG.getBitcast(VT, D.getOperand(0));
23684 DCI.AddToWorklist(V.getNode());
23685 return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
23694 case X86ISD::PSHUFD:
23695 if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
23704 /// \brief Try to combine a shuffle into a target-specific add-sub node.
23706 /// We combine this directly on the abstract vector shuffle nodes so it is
23707 /// easier to generically match. We also insert dummy vector shuffle nodes for
23708 /// the operands which explicitly discard the lanes which are unused by this
23709 /// operation to try to flow through the rest of the combiner the fact that
23710 /// they're unused.
23711 static SDValue combineShuffleToAddSub(SDNode *N, const X86Subtarget *Subtarget,
23712 SelectionDAG &DAG) {
23714 EVT VT = N->getValueType(0);
23715 if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
23716 (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
23719 // We only handle target-independent shuffles.
23720 // FIXME: It would be easy and harmless to use the target shuffle mask
23721 // extraction tool to support more.
23722 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
23725 auto *SVN = cast<ShuffleVectorSDNode>(N);
23726 SmallVector<int, 8> Mask;
23727 for (int M : SVN->getMask())
23730 SDValue V1 = N->getOperand(0);
23731 SDValue V2 = N->getOperand(1);
23733 // We require the first shuffle operand to be the FSUB node, and the second to
23734 // be the FADD node.
23735 if (V1.getOpcode() == ISD::FADD && V2.getOpcode() == ISD::FSUB) {
23736 ShuffleVectorSDNode::commuteMask(Mask);
23738 } else if (V1.getOpcode() != ISD::FSUB || V2.getOpcode() != ISD::FADD)
23741 // If there are other uses of these operations we can't fold them.
23742 if (!V1->hasOneUse() || !V2->hasOneUse())
23745 // Ensure that both operations have the same operands. Note that we can
23746 // commute the FADD operands.
23747 SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
23748 if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
23749 (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
23752 // We're looking for blends between FADD and FSUB nodes. We insist on these
23753 // nodes being lined up in a specific expected pattern.
23754 if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
23755 isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
23756 isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
23759 return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
23762 /// PerformShuffleCombine - Performs several different shuffle combines.
23763 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
23764 TargetLowering::DAGCombinerInfo &DCI,
23765 const X86Subtarget *Subtarget) {
23767 SDValue N0 = N->getOperand(0);
23768 SDValue N1 = N->getOperand(1);
23769 EVT VT = N->getValueType(0);
23771 // Don't create instructions with illegal types after legalize types has run.
23772 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23773 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
23776 // If we have legalized the vector types, look for blends of FADD and FSUB
23777 // nodes that we can fuse into an ADDSUB node.
23778 if (TLI.isTypeLegal(VT))
23779 if (SDValue AddSub = combineShuffleToAddSub(N, Subtarget, DAG))
23782 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
23783 if (TLI.isTypeLegal(VT) && Subtarget->hasFp256() && VT.is256BitVector() &&
23784 N->getOpcode() == ISD::VECTOR_SHUFFLE)
23785 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
23787 // During Type Legalization, when promoting illegal vector types,
23788 // the backend might introduce new shuffle dag nodes and bitcasts.
23790 // This code performs the following transformation:
23791 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
23792 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
23794 // We do this only if both the bitcast and the BINOP dag nodes have
23795 // one use. Also, perform this transformation only if the new binary
23796 // operation is legal. This is to avoid introducing dag nodes that
23797 // potentially need to be further expanded (or custom lowered) into a
23798 // less optimal sequence of dag nodes.
23799 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
23800 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
23801 N0.getOpcode() == ISD::BITCAST) {
23802 SDValue BC0 = N0.getOperand(0);
23803 EVT SVT = BC0.getValueType();
23804 unsigned Opcode = BC0.getOpcode();
23805 unsigned NumElts = VT.getVectorNumElements();
23807 if (BC0.hasOneUse() && SVT.isVector() &&
23808 SVT.getVectorNumElements() * 2 == NumElts &&
23809 TLI.isOperationLegal(Opcode, VT)) {
23810 bool CanFold = false;
23822 unsigned SVTNumElts = SVT.getVectorNumElements();
23823 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
23824 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
23825 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
23826 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
23827 CanFold = SVOp->getMaskElt(i) < 0;
23830 SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
23831 SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
23832 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
23833 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
23838 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
23839 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
23840 // consecutive, non-overlapping, and in the right order.
23841 SmallVector<SDValue, 16> Elts;
23842 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
23843 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
23845 if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
23848 if (isTargetShuffle(N->getOpcode())) {
23850 PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
23851 if (Shuffle.getNode())
23854 // Try recursively combining arbitrary sequences of x86 shuffle
23855 // instructions into higher-order shuffles. We do this after combining
23856 // specific PSHUF instruction sequences into their minimal form so that we
23857 // can evaluate how many specialized shuffle instructions are involved in
23858 // a particular chain.
23859 SmallVector<int, 1> NonceMask; // Just a placeholder.
23860 NonceMask.push_back(0);
23861 if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
23862 /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
23864 return SDValue(); // This routine will use CombineTo to replace N.
23870 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
23871 /// specific shuffle of a load can be folded into a single element load.
23872 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
23873 /// shuffles have been custom lowered so we need to handle those here.
23874 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
23875 TargetLowering::DAGCombinerInfo &DCI) {
23876 if (DCI.isBeforeLegalizeOps())
23879 SDValue InVec = N->getOperand(0);
23880 SDValue EltNo = N->getOperand(1);
23881 EVT EltVT = N->getValueType(0);
23883 if (!isa<ConstantSDNode>(EltNo))
23886 EVT OriginalVT = InVec.getValueType();
23888 if (InVec.getOpcode() == ISD::BITCAST) {
23889 // Don't duplicate a load with other uses.
23890 if (!InVec.hasOneUse())
23892 EVT BCVT = InVec.getOperand(0).getValueType();
23893 if (!BCVT.isVector() ||
23894 BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
23896 InVec = InVec.getOperand(0);
23899 EVT CurrentVT = InVec.getValueType();
23901 if (!isTargetShuffle(InVec.getOpcode()))
23904 // Don't duplicate a load with other uses.
23905 if (!InVec.hasOneUse())
23908 SmallVector<int, 16> ShuffleMask;
23910 if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(), true,
23911 ShuffleMask, UnaryShuffle))
23914 // Select the input vector, guarding against out of range extract vector.
23915 unsigned NumElems = CurrentVT.getVectorNumElements();
23916 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
23917 int Idx = (Elt > (int)NumElems) ? SM_SentinelUndef : ShuffleMask[Elt];
23919 if (Idx == SM_SentinelZero)
23920 return EltVT.isInteger() ? DAG.getConstant(0, SDLoc(N), EltVT)
23921 : DAG.getConstantFP(+0.0, SDLoc(N), EltVT);
23922 if (Idx == SM_SentinelUndef)
23923 return DAG.getUNDEF(EltVT);
23925 assert(0 <= Idx && Idx < (int)(2 * NumElems) && "Shuffle index out of range");
23926 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
23927 : InVec.getOperand(1);
23929 // If inputs to shuffle are the same for both ops, then allow 2 uses
23930 unsigned AllowedUses = InVec.getNumOperands() > 1 &&
23931 InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
23933 if (LdNode.getOpcode() == ISD::BITCAST) {
23934 // Don't duplicate a load with other uses.
23935 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
23938 AllowedUses = 1; // only allow 1 load use if we have a bitcast
23939 LdNode = LdNode.getOperand(0);
23942 if (!ISD::isNormalLoad(LdNode.getNode()))
23945 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
23947 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
23950 // If there's a bitcast before the shuffle, check if the load type and
23951 // alignment is valid.
23952 unsigned Align = LN0->getAlignment();
23953 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23954 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
23955 EltVT.getTypeForEVT(*DAG.getContext()));
23957 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
23960 // All checks match so transform back to vector_shuffle so that DAG combiner
23961 // can finish the job
23964 // Create shuffle node taking into account the case that its a unary shuffle
23965 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
23966 : InVec.getOperand(1);
23967 Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
23968 InVec.getOperand(0), Shuffle,
23970 Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
23971 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
23975 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG,
23976 const X86Subtarget *Subtarget) {
23977 SDValue N0 = N->getOperand(0);
23978 EVT VT = N->getValueType(0);
23980 // Detect bitcasts between i32 to x86mmx low word. Since MMX types are
23981 // special and don't usually play with other vector types, it's better to
23982 // handle them early to be sure we emit efficient code by avoiding
23983 // store-load conversions.
23984 if (VT == MVT::x86mmx && N0.getOpcode() == ISD::BUILD_VECTOR &&
23985 N0.getValueType() == MVT::v2i32 &&
23986 isNullConstant(N0.getOperand(1))) {
23987 SDValue N00 = N0->getOperand(0);
23988 if (N00.getValueType() == MVT::i32)
23989 return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(N00), VT, N00);
23992 // Convert a bitcasted integer logic operation that has one bitcasted
23993 // floating-point operand and one constant operand into a floating-point
23994 // logic operation. This may create a load of the constant, but that is
23995 // cheaper than materializing the constant in an integer register and
23996 // transferring it to an SSE register or transferring the SSE operand to
23997 // integer register and back.
23999 switch (N0.getOpcode()) {
24000 case ISD::AND: FPOpcode = X86ISD::FAND; break;
24001 case ISD::OR: FPOpcode = X86ISD::FOR; break;
24002 case ISD::XOR: FPOpcode = X86ISD::FXOR; break;
24003 default: return SDValue();
24005 if (((Subtarget->hasSSE1() && VT == MVT::f32) ||
24006 (Subtarget->hasSSE2() && VT == MVT::f64)) &&
24007 isa<ConstantSDNode>(N0.getOperand(1)) &&
24008 N0.getOperand(0).getOpcode() == ISD::BITCAST &&
24009 N0.getOperand(0).getOperand(0).getValueType() == VT) {
24010 SDValue N000 = N0.getOperand(0).getOperand(0);
24011 SDValue FPConst = DAG.getBitcast(VT, N0.getOperand(1));
24012 return DAG.getNode(FPOpcode, SDLoc(N0), VT, N000, FPConst);
24018 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
24019 /// generation and convert it from being a bunch of shuffles and extracts
24020 /// into a somewhat faster sequence. For i686, the best sequence is apparently
24021 /// storing the value and loading scalars back, while for x64 we should
24022 /// use 64-bit extracts and shifts.
24023 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
24024 TargetLowering::DAGCombinerInfo &DCI) {
24025 if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
24028 SDValue InputVector = N->getOperand(0);
24029 SDLoc dl(InputVector);
24030 // Detect mmx to i32 conversion through a v2i32 elt extract.
24031 if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
24032 N->getValueType(0) == MVT::i32 &&
24033 InputVector.getValueType() == MVT::v2i32) {
24035 // The bitcast source is a direct mmx result.
24036 SDValue MMXSrc = InputVector.getNode()->getOperand(0);
24037 if (MMXSrc.getValueType() == MVT::x86mmx)
24038 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
24039 N->getValueType(0),
24040 InputVector.getNode()->getOperand(0));
24042 // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
24043 if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
24044 MMXSrc.getValueType() == MVT::i64) {
24045 SDValue MMXSrcOp = MMXSrc.getOperand(0);
24046 if (MMXSrcOp.hasOneUse() && MMXSrcOp.getOpcode() == ISD::BITCAST &&
24047 MMXSrcOp.getValueType() == MVT::v1i64 &&
24048 MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
24049 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
24050 N->getValueType(0), MMXSrcOp.getOperand(0));
24054 EVT VT = N->getValueType(0);
24056 if (VT == MVT::i1 && isa<ConstantSDNode>(N->getOperand(1)) &&
24057 InputVector.getOpcode() == ISD::BITCAST &&
24058 isa<ConstantSDNode>(InputVector.getOperand(0))) {
24059 uint64_t ExtractedElt =
24060 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
24061 uint64_t InputValue =
24062 cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
24063 uint64_t Res = (InputValue >> ExtractedElt) & 1;
24064 return DAG.getConstant(Res, dl, MVT::i1);
24066 // Only operate on vectors of 4 elements, where the alternative shuffling
24067 // gets to be more expensive.
24068 if (InputVector.getValueType() != MVT::v4i32)
24071 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
24072 // single use which is a sign-extend or zero-extend, and all elements are
24074 SmallVector<SDNode *, 4> Uses;
24075 unsigned ExtractedElements = 0;
24076 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
24077 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
24078 if (UI.getUse().getResNo() != InputVector.getResNo())
24081 SDNode *Extract = *UI;
24082 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
24085 if (Extract->getValueType(0) != MVT::i32)
24087 if (!Extract->hasOneUse())
24089 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
24090 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
24092 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
24095 // Record which element was extracted.
24096 ExtractedElements |=
24097 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
24099 Uses.push_back(Extract);
24102 // If not all the elements were used, this may not be worthwhile.
24103 if (ExtractedElements != 15)
24106 // Ok, we've now decided to do the transformation.
24107 // If 64-bit shifts are legal, use the extract-shift sequence,
24108 // otherwise bounce the vector off the cache.
24109 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24112 if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
24113 SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
24114 auto &DL = DAG.getDataLayout();
24115 EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
24116 SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
24117 DAG.getConstant(0, dl, VecIdxTy));
24118 SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
24119 DAG.getConstant(1, dl, VecIdxTy));
24121 SDValue ShAmt = DAG.getConstant(
24122 32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
24123 Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
24124 Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
24125 DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
24126 Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
24127 Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
24128 DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
24130 // Store the value to a temporary stack slot.
24131 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
24132 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
24133 MachinePointerInfo(), false, false, 0);
24135 EVT ElementType = InputVector.getValueType().getVectorElementType();
24136 unsigned EltSize = ElementType.getSizeInBits() / 8;
24138 // Replace each use (extract) with a load of the appropriate element.
24139 for (unsigned i = 0; i < 4; ++i) {
24140 uint64_t Offset = EltSize * i;
24141 auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
24142 SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
24144 SDValue ScalarAddr =
24145 DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
24147 // Load the scalar.
24148 Vals[i] = DAG.getLoad(ElementType, dl, Ch,
24149 ScalarAddr, MachinePointerInfo(),
24150 false, false, false, 0);
24155 // Replace the extracts
24156 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
24157 UE = Uses.end(); UI != UE; ++UI) {
24158 SDNode *Extract = *UI;
24160 SDValue Idx = Extract->getOperand(1);
24161 uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
24162 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
24165 // The replacement was made in place; don't return anything.
24170 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
24171 const X86Subtarget *Subtarget) {
24173 SDValue Cond = N->getOperand(0);
24174 SDValue LHS = N->getOperand(1);
24175 SDValue RHS = N->getOperand(2);
24177 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
24178 SDValue CondSrc = Cond->getOperand(0);
24179 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
24180 Cond = CondSrc->getOperand(0);
24183 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
24186 // A vselect where all conditions and data are constants can be optimized into
24187 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
24188 if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
24189 ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
24192 unsigned MaskValue = 0;
24193 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
24196 MVT VT = N->getSimpleValueType(0);
24197 unsigned NumElems = VT.getVectorNumElements();
24198 SmallVector<int, 8> ShuffleMask(NumElems, -1);
24199 for (unsigned i = 0; i < NumElems; ++i) {
24200 // Be sure we emit undef where we can.
24201 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
24202 ShuffleMask[i] = -1;
24204 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
24207 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24208 if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
24210 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
24213 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
24215 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
24216 TargetLowering::DAGCombinerInfo &DCI,
24217 const X86Subtarget *Subtarget) {
24219 SDValue Cond = N->getOperand(0);
24220 // Get the LHS/RHS of the select.
24221 SDValue LHS = N->getOperand(1);
24222 SDValue RHS = N->getOperand(2);
24223 EVT VT = LHS.getValueType();
24224 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24226 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
24227 // instructions match the semantics of the common C idiom x<y?x:y but not
24228 // x<=y?x:y, because of how they handle negative zero (which can be
24229 // ignored in unsafe-math mode).
24230 // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
24231 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
24232 VT != MVT::f80 && VT != MVT::f128 &&
24233 (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
24234 (Subtarget->hasSSE2() ||
24235 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
24236 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
24238 unsigned Opcode = 0;
24239 // Check for x CC y ? x : y.
24240 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
24241 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
24245 // Converting this to a min would handle NaNs incorrectly, and swapping
24246 // the operands would cause it to handle comparisons between positive
24247 // and negative zero incorrectly.
24248 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
24249 if (!DAG.getTarget().Options.UnsafeFPMath &&
24250 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
24252 std::swap(LHS, RHS);
24254 Opcode = X86ISD::FMIN;
24257 // Converting this to a min would handle comparisons between positive
24258 // and negative zero incorrectly.
24259 if (!DAG.getTarget().Options.UnsafeFPMath &&
24260 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
24262 Opcode = X86ISD::FMIN;
24265 // Converting this to a min would handle both negative zeros and NaNs
24266 // incorrectly, but we can swap the operands to fix both.
24267 std::swap(LHS, RHS);
24271 Opcode = X86ISD::FMIN;
24275 // Converting this to a max would handle comparisons between positive
24276 // and negative zero incorrectly.
24277 if (!DAG.getTarget().Options.UnsafeFPMath &&
24278 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
24280 Opcode = X86ISD::FMAX;
24283 // Converting this to a max would handle NaNs incorrectly, and swapping
24284 // the operands would cause it to handle comparisons between positive
24285 // and negative zero incorrectly.
24286 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
24287 if (!DAG.getTarget().Options.UnsafeFPMath &&
24288 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
24290 std::swap(LHS, RHS);
24292 Opcode = X86ISD::FMAX;
24295 // Converting this to a max would handle both negative zeros and NaNs
24296 // incorrectly, but we can swap the operands to fix both.
24297 std::swap(LHS, RHS);
24301 Opcode = X86ISD::FMAX;
24304 // Check for x CC y ? y : x -- a min/max with reversed arms.
24305 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
24306 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
24310 // Converting this to a min would handle comparisons between positive
24311 // and negative zero incorrectly, and swapping the operands would
24312 // cause it to handle NaNs incorrectly.
24313 if (!DAG.getTarget().Options.UnsafeFPMath &&
24314 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
24315 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
24317 std::swap(LHS, RHS);
24319 Opcode = X86ISD::FMIN;
24322 // Converting this to a min would handle NaNs incorrectly.
24323 if (!DAG.getTarget().Options.UnsafeFPMath &&
24324 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
24326 Opcode = X86ISD::FMIN;
24329 // Converting this to a min would handle both negative zeros and NaNs
24330 // incorrectly, but we can swap the operands to fix both.
24331 std::swap(LHS, RHS);
24335 Opcode = X86ISD::FMIN;
24339 // Converting this to a max would handle NaNs incorrectly.
24340 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
24342 Opcode = X86ISD::FMAX;
24345 // Converting this to a max would handle comparisons between positive
24346 // and negative zero incorrectly, and swapping the operands would
24347 // cause it to handle NaNs incorrectly.
24348 if (!DAG.getTarget().Options.UnsafeFPMath &&
24349 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
24350 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
24352 std::swap(LHS, RHS);
24354 Opcode = X86ISD::FMAX;
24357 // Converting this to a max would handle both negative zeros and NaNs
24358 // incorrectly, but we can swap the operands to fix both.
24359 std::swap(LHS, RHS);
24363 Opcode = X86ISD::FMAX;
24369 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
24372 EVT CondVT = Cond.getValueType();
24373 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
24374 CondVT.getVectorElementType() == MVT::i1) {
24375 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
24376 // lowering on KNL. In this case we convert it to
24377 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
24378 // The same situation for all 128 and 256-bit vectors of i8 and i16.
24379 // Since SKX these selects have a proper lowering.
24380 EVT OpVT = LHS.getValueType();
24381 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
24382 (OpVT.getVectorElementType() == MVT::i8 ||
24383 OpVT.getVectorElementType() == MVT::i16) &&
24384 !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
24385 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
24386 DCI.AddToWorklist(Cond.getNode());
24387 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
24390 // If this is a select between two integer constants, try to do some
24392 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
24393 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
24394 // Don't do this for crazy integer types.
24395 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
24396 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
24397 // so that TrueC (the true value) is larger than FalseC.
24398 bool NeedsCondInvert = false;
24400 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
24401 // Efficiently invertible.
24402 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
24403 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
24404 isa<ConstantSDNode>(Cond.getOperand(1))))) {
24405 NeedsCondInvert = true;
24406 std::swap(TrueC, FalseC);
24409 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
24410 if (FalseC->getAPIntValue() == 0 &&
24411 TrueC->getAPIntValue().isPowerOf2()) {
24412 if (NeedsCondInvert) // Invert the condition if needed.
24413 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
24414 DAG.getConstant(1, DL, Cond.getValueType()));
24416 // Zero extend the condition if needed.
24417 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
24419 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
24420 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
24421 DAG.getConstant(ShAmt, DL, MVT::i8));
24424 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
24425 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
24426 if (NeedsCondInvert) // Invert the condition if needed.
24427 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
24428 DAG.getConstant(1, DL, Cond.getValueType()));
24430 // Zero extend the condition if needed.
24431 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
24432 FalseC->getValueType(0), Cond);
24433 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24434 SDValue(FalseC, 0));
24437 // Optimize cases that will turn into an LEA instruction. This requires
24438 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
24439 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
24440 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
24441 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
24443 bool isFastMultiplier = false;
24445 switch ((unsigned char)Diff) {
24447 case 1: // result = add base, cond
24448 case 2: // result = lea base( , cond*2)
24449 case 3: // result = lea base(cond, cond*2)
24450 case 4: // result = lea base( , cond*4)
24451 case 5: // result = lea base(cond, cond*4)
24452 case 8: // result = lea base( , cond*8)
24453 case 9: // result = lea base(cond, cond*8)
24454 isFastMultiplier = true;
24459 if (isFastMultiplier) {
24460 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
24461 if (NeedsCondInvert) // Invert the condition if needed.
24462 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
24463 DAG.getConstant(1, DL, Cond.getValueType()));
24465 // Zero extend the condition if needed.
24466 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
24468 // Scale the condition by the difference.
24470 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
24471 DAG.getConstant(Diff, DL,
24472 Cond.getValueType()));
24474 // Add the base if non-zero.
24475 if (FalseC->getAPIntValue() != 0)
24476 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24477 SDValue(FalseC, 0));
24484 // Canonicalize max and min:
24485 // (x > y) ? x : y -> (x >= y) ? x : y
24486 // (x < y) ? x : y -> (x <= y) ? x : y
24487 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
24488 // the need for an extra compare
24489 // against zero. e.g.
24490 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
24492 // testl %edi, %edi
24494 // cmovgl %edi, %eax
24498 // cmovsl %eax, %edi
24499 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
24500 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
24501 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
24502 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
24507 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
24508 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
24509 Cond.getOperand(0), Cond.getOperand(1), NewCC);
24510 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
24515 // Early exit check
24516 if (!TLI.isTypeLegal(VT))
24519 // Match VSELECTs into subs with unsigned saturation.
24520 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
24521 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
24522 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
24523 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
24524 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
24526 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
24527 // left side invert the predicate to simplify logic below.
24529 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
24531 CC = ISD::getSetCCInverse(CC, true);
24532 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
24536 if (Other.getNode() && Other->getNumOperands() == 2 &&
24537 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
24538 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
24539 SDValue CondRHS = Cond->getOperand(1);
24541 // Look for a general sub with unsigned saturation first.
24542 // x >= y ? x-y : 0 --> subus x, y
24543 // x > y ? x-y : 0 --> subus x, y
24544 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
24545 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
24546 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
24548 if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
24549 if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
24550 if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
24551 if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
24552 // If the RHS is a constant we have to reverse the const
24553 // canonicalization.
24554 // x > C-1 ? x+-C : 0 --> subus x, C
24555 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
24556 CondRHSConst->getAPIntValue() ==
24557 (-OpRHSConst->getAPIntValue() - 1))
24558 return DAG.getNode(
24559 X86ISD::SUBUS, DL, VT, OpLHS,
24560 DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
24562 // Another special case: If C was a sign bit, the sub has been
24563 // canonicalized into a xor.
24564 // FIXME: Would it be better to use computeKnownBits to determine
24565 // whether it's safe to decanonicalize the xor?
24566 // x s< 0 ? x^C : 0 --> subus x, C
24567 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
24568 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
24569 OpRHSConst->getAPIntValue().isSignBit())
24570 // Note that we have to rebuild the RHS constant here to ensure we
24571 // don't rely on particular values of undef lanes.
24572 return DAG.getNode(
24573 X86ISD::SUBUS, DL, VT, OpLHS,
24574 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
24579 // Simplify vector selection if condition value type matches vselect
24581 if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
24582 assert(Cond.getValueType().isVector() &&
24583 "vector select expects a vector selector!");
24585 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
24586 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
24588 // Try invert the condition if true value is not all 1s and false value
24590 if (!TValIsAllOnes && !FValIsAllZeros &&
24591 // Check if the selector will be produced by CMPP*/PCMP*
24592 Cond.getOpcode() == ISD::SETCC &&
24593 // Check if SETCC has already been promoted
24594 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
24596 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
24597 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
24599 if (TValIsAllZeros || FValIsAllOnes) {
24600 SDValue CC = Cond.getOperand(2);
24601 ISD::CondCode NewCC =
24602 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
24603 Cond.getOperand(0).getValueType().isInteger());
24604 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
24605 std::swap(LHS, RHS);
24606 TValIsAllOnes = FValIsAllOnes;
24607 FValIsAllZeros = TValIsAllZeros;
24611 if (TValIsAllOnes || FValIsAllZeros) {
24614 if (TValIsAllOnes && FValIsAllZeros)
24616 else if (TValIsAllOnes)
24618 DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
24619 else if (FValIsAllZeros)
24620 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
24621 DAG.getBitcast(CondVT, LHS));
24623 return DAG.getBitcast(VT, Ret);
24627 // We should generate an X86ISD::BLENDI from a vselect if its argument
24628 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
24629 // constants. This specific pattern gets generated when we split a
24630 // selector for a 512 bit vector in a machine without AVX512 (but with
24631 // 256-bit vectors), during legalization:
24633 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
24635 // Iff we find this pattern and the build_vectors are built from
24636 // constants, we translate the vselect into a shuffle_vector that we
24637 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
24638 if ((N->getOpcode() == ISD::VSELECT ||
24639 N->getOpcode() == X86ISD::SHRUNKBLEND) &&
24640 !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
24641 SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
24642 if (Shuffle.getNode())
24646 // If this is a *dynamic* select (non-constant condition) and we can match
24647 // this node with one of the variable blend instructions, restructure the
24648 // condition so that the blends can use the high bit of each element and use
24649 // SimplifyDemandedBits to simplify the condition operand.
24650 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
24651 !DCI.isBeforeLegalize() &&
24652 !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
24653 unsigned BitWidth = Cond.getValueType().getScalarSizeInBits();
24655 // Don't optimize vector selects that map to mask-registers.
24659 // We can only handle the cases where VSELECT is directly legal on the
24660 // subtarget. We custom lower VSELECT nodes with constant conditions and
24661 // this makes it hard to see whether a dynamic VSELECT will correctly
24662 // lower, so we both check the operation's status and explicitly handle the
24663 // cases where a *dynamic* blend will fail even though a constant-condition
24664 // blend could be custom lowered.
24665 // FIXME: We should find a better way to handle this class of problems.
24666 // Potentially, we should combine constant-condition vselect nodes
24667 // pre-legalization into shuffles and not mark as many types as custom
24669 if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
24671 // FIXME: We don't support i16-element blends currently. We could and
24672 // should support them by making *all* the bits in the condition be set
24673 // rather than just the high bit and using an i8-element blend.
24674 if (VT.getVectorElementType() == MVT::i16)
24676 // Dynamic blending was only available from SSE4.1 onward.
24677 if (VT.is128BitVector() && !Subtarget->hasSSE41())
24679 // Byte blends are only available in AVX2
24680 if (VT == MVT::v32i8 && !Subtarget->hasAVX2())
24683 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
24684 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
24686 APInt KnownZero, KnownOne;
24687 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
24688 DCI.isBeforeLegalizeOps());
24689 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
24690 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
24692 // If we changed the computation somewhere in the DAG, this change
24693 // will affect all users of Cond.
24694 // Make sure it is fine and update all the nodes so that we do not
24695 // use the generic VSELECT anymore. Otherwise, we may perform
24696 // wrong optimizations as we messed up with the actual expectation
24697 // for the vector boolean values.
24698 if (Cond != TLO.Old) {
24699 // Check all uses of that condition operand to check whether it will be
24700 // consumed by non-BLEND instructions, which may depend on all bits are
24702 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
24704 if (I->getOpcode() != ISD::VSELECT)
24705 // TODO: Add other opcodes eventually lowered into BLEND.
24708 // Update all the users of the condition, before committing the change,
24709 // so that the VSELECT optimizations that expect the correct vector
24710 // boolean value will not be triggered.
24711 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
24713 DAG.ReplaceAllUsesOfValueWith(
24715 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
24716 Cond, I->getOperand(1), I->getOperand(2)));
24717 DCI.CommitTargetLoweringOpt(TLO);
24720 // At this point, only Cond is changed. Change the condition
24721 // just for N to keep the opportunity to optimize all other
24722 // users their own way.
24723 DAG.ReplaceAllUsesOfValueWith(
24725 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
24726 TLO.New, N->getOperand(1), N->getOperand(2)));
24734 // Check whether a boolean test is testing a boolean value generated by
24735 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
24738 // Simplify the following patterns:
24739 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
24740 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
24741 // to (Op EFLAGS Cond)
24743 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
24744 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
24745 // to (Op EFLAGS !Cond)
24747 // where Op could be BRCOND or CMOV.
24749 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
24750 // Quit if not CMP and SUB with its value result used.
24751 if (Cmp.getOpcode() != X86ISD::CMP &&
24752 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
24755 // Quit if not used as a boolean value.
24756 if (CC != X86::COND_E && CC != X86::COND_NE)
24759 // Check CMP operands. One of them should be 0 or 1 and the other should be
24760 // an SetCC or extended from it.
24761 SDValue Op1 = Cmp.getOperand(0);
24762 SDValue Op2 = Cmp.getOperand(1);
24765 const ConstantSDNode* C = nullptr;
24766 bool needOppositeCond = (CC == X86::COND_E);
24767 bool checkAgainstTrue = false; // Is it a comparison against 1?
24769 if ((C = dyn_cast<ConstantSDNode>(Op1)))
24771 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
24773 else // Quit if all operands are not constants.
24776 if (C->getZExtValue() == 1) {
24777 needOppositeCond = !needOppositeCond;
24778 checkAgainstTrue = true;
24779 } else if (C->getZExtValue() != 0)
24780 // Quit if the constant is neither 0 or 1.
24783 bool truncatedToBoolWithAnd = false;
24784 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
24785 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
24786 SetCC.getOpcode() == ISD::TRUNCATE ||
24787 SetCC.getOpcode() == ISD::AND) {
24788 if (SetCC.getOpcode() == ISD::AND) {
24790 if (isOneConstant(SetCC.getOperand(0)))
24792 if (isOneConstant(SetCC.getOperand(1)))
24796 SetCC = SetCC.getOperand(OpIdx);
24797 truncatedToBoolWithAnd = true;
24799 SetCC = SetCC.getOperand(0);
24802 switch (SetCC.getOpcode()) {
24803 case X86ISD::SETCC_CARRY:
24804 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
24805 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
24806 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
24807 // truncated to i1 using 'and'.
24808 if (checkAgainstTrue && !truncatedToBoolWithAnd)
24810 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
24811 "Invalid use of SETCC_CARRY!");
24813 case X86ISD::SETCC:
24814 // Set the condition code or opposite one if necessary.
24815 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
24816 if (needOppositeCond)
24817 CC = X86::GetOppositeBranchCondition(CC);
24818 return SetCC.getOperand(1);
24819 case X86ISD::CMOV: {
24820 // Check whether false/true value has canonical one, i.e. 0 or 1.
24821 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
24822 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
24823 // Quit if true value is not a constant.
24826 // Quit if false value is not a constant.
24828 SDValue Op = SetCC.getOperand(0);
24829 // Skip 'zext' or 'trunc' node.
24830 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
24831 Op.getOpcode() == ISD::TRUNCATE)
24832 Op = Op.getOperand(0);
24833 // A special case for rdrand/rdseed, where 0 is set if false cond is
24835 if ((Op.getOpcode() != X86ISD::RDRAND &&
24836 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
24839 // Quit if false value is not the constant 0 or 1.
24840 bool FValIsFalse = true;
24841 if (FVal && FVal->getZExtValue() != 0) {
24842 if (FVal->getZExtValue() != 1)
24844 // If FVal is 1, opposite cond is needed.
24845 needOppositeCond = !needOppositeCond;
24846 FValIsFalse = false;
24848 // Quit if TVal is not the constant opposite of FVal.
24849 if (FValIsFalse && TVal->getZExtValue() != 1)
24851 if (!FValIsFalse && TVal->getZExtValue() != 0)
24853 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
24854 if (needOppositeCond)
24855 CC = X86::GetOppositeBranchCondition(CC);
24856 return SetCC.getOperand(3);
24863 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
24865 /// (X86or (X86setcc) (X86setcc))
24866 /// (X86cmp (and (X86setcc) (X86setcc)), 0)
24867 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
24868 X86::CondCode &CC1, SDValue &Flags,
24870 if (Cond->getOpcode() == X86ISD::CMP) {
24871 if (!isNullConstant(Cond->getOperand(1)))
24874 Cond = Cond->getOperand(0);
24879 SDValue SetCC0, SetCC1;
24880 switch (Cond->getOpcode()) {
24881 default: return false;
24888 SetCC0 = Cond->getOperand(0);
24889 SetCC1 = Cond->getOperand(1);
24893 // Make sure we have SETCC nodes, using the same flags value.
24894 if (SetCC0.getOpcode() != X86ISD::SETCC ||
24895 SetCC1.getOpcode() != X86ISD::SETCC ||
24896 SetCC0->getOperand(1) != SetCC1->getOperand(1))
24899 CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
24900 CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
24901 Flags = SetCC0->getOperand(1);
24905 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
24906 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
24907 TargetLowering::DAGCombinerInfo &DCI,
24908 const X86Subtarget *Subtarget) {
24911 // If the flag operand isn't dead, don't touch this CMOV.
24912 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
24915 SDValue FalseOp = N->getOperand(0);
24916 SDValue TrueOp = N->getOperand(1);
24917 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
24918 SDValue Cond = N->getOperand(3);
24920 if (CC == X86::COND_E || CC == X86::COND_NE) {
24921 switch (Cond.getOpcode()) {
24925 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
24926 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
24927 return (CC == X86::COND_E) ? FalseOp : TrueOp;
24933 Flags = checkBoolTestSetCCCombine(Cond, CC);
24934 if (Flags.getNode() &&
24935 // Extra check as FCMOV only supports a subset of X86 cond.
24936 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
24937 SDValue Ops[] = { FalseOp, TrueOp,
24938 DAG.getConstant(CC, DL, MVT::i8), Flags };
24939 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
24942 // If this is a select between two integer constants, try to do some
24943 // optimizations. Note that the operands are ordered the opposite of SELECT
24945 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
24946 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
24947 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
24948 // larger than FalseC (the false value).
24949 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
24950 CC = X86::GetOppositeBranchCondition(CC);
24951 std::swap(TrueC, FalseC);
24952 std::swap(TrueOp, FalseOp);
24955 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
24956 // This is efficient for any integer data type (including i8/i16) and
24958 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
24959 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
24960 DAG.getConstant(CC, DL, MVT::i8), Cond);
24962 // Zero extend the condition if needed.
24963 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
24965 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
24966 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
24967 DAG.getConstant(ShAmt, DL, MVT::i8));
24968 if (N->getNumValues() == 2) // Dead flag value?
24969 return DCI.CombineTo(N, Cond, SDValue());
24973 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
24974 // for any integer data type, including i8/i16.
24975 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
24976 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
24977 DAG.getConstant(CC, DL, MVT::i8), Cond);
24979 // Zero extend the condition if needed.
24980 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
24981 FalseC->getValueType(0), Cond);
24982 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24983 SDValue(FalseC, 0));
24985 if (N->getNumValues() == 2) // Dead flag value?
24986 return DCI.CombineTo(N, Cond, SDValue());
24990 // Optimize cases that will turn into an LEA instruction. This requires
24991 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
24992 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
24993 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
24994 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
24996 bool isFastMultiplier = false;
24998 switch ((unsigned char)Diff) {
25000 case 1: // result = add base, cond
25001 case 2: // result = lea base( , cond*2)
25002 case 3: // result = lea base(cond, cond*2)
25003 case 4: // result = lea base( , cond*4)
25004 case 5: // result = lea base(cond, cond*4)
25005 case 8: // result = lea base( , cond*8)
25006 case 9: // result = lea base(cond, cond*8)
25007 isFastMultiplier = true;
25012 if (isFastMultiplier) {
25013 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
25014 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
25015 DAG.getConstant(CC, DL, MVT::i8), Cond);
25016 // Zero extend the condition if needed.
25017 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
25019 // Scale the condition by the difference.
25021 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
25022 DAG.getConstant(Diff, DL, Cond.getValueType()));
25024 // Add the base if non-zero.
25025 if (FalseC->getAPIntValue() != 0)
25026 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
25027 SDValue(FalseC, 0));
25028 if (N->getNumValues() == 2) // Dead flag value?
25029 return DCI.CombineTo(N, Cond, SDValue());
25036 // Handle these cases:
25037 // (select (x != c), e, c) -> select (x != c), e, x),
25038 // (select (x == c), c, e) -> select (x == c), x, e)
25039 // where the c is an integer constant, and the "select" is the combination
25040 // of CMOV and CMP.
25042 // The rationale for this change is that the conditional-move from a constant
25043 // needs two instructions, however, conditional-move from a register needs
25044 // only one instruction.
25046 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
25047 // some instruction-combining opportunities. This opt needs to be
25048 // postponed as late as possible.
25050 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
25051 // the DCI.xxxx conditions are provided to postpone the optimization as
25052 // late as possible.
25054 ConstantSDNode *CmpAgainst = nullptr;
25055 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
25056 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
25057 !isa<ConstantSDNode>(Cond.getOperand(0))) {
25059 if (CC == X86::COND_NE &&
25060 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
25061 CC = X86::GetOppositeBranchCondition(CC);
25062 std::swap(TrueOp, FalseOp);
25065 if (CC == X86::COND_E &&
25066 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
25067 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
25068 DAG.getConstant(CC, DL, MVT::i8), Cond };
25069 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
25074 // Fold and/or of setcc's to double CMOV:
25075 // (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
25076 // (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
25078 // This combine lets us generate:
25079 // cmovcc1 (jcc1 if we don't have CMOV)
25085 // cmovne (jne if we don't have CMOV)
25086 // When we can't use the CMOV instruction, it might increase branch
25088 // When we can use CMOV, or when there is no mispredict, this improves
25089 // throughput and reduces register pressure.
25091 if (CC == X86::COND_NE) {
25093 X86::CondCode CC0, CC1;
25095 if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
25097 std::swap(FalseOp, TrueOp);
25098 CC0 = X86::GetOppositeBranchCondition(CC0);
25099 CC1 = X86::GetOppositeBranchCondition(CC1);
25102 SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
25104 SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
25105 SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
25106 SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
25107 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
25115 /// PerformMulCombine - Optimize a single multiply with constant into two
25116 /// in order to implement it with two cheaper instructions, e.g.
25117 /// LEA + SHL, LEA + LEA.
25118 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
25119 TargetLowering::DAGCombinerInfo &DCI) {
25120 // An imul is usually smaller than the alternative sequence.
25121 if (DAG.getMachineFunction().getFunction()->optForMinSize())
25124 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
25127 EVT VT = N->getValueType(0);
25128 if (VT != MVT::i64 && VT != MVT::i32)
25131 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
25134 uint64_t MulAmt = C->getZExtValue();
25135 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
25138 uint64_t MulAmt1 = 0;
25139 uint64_t MulAmt2 = 0;
25140 if ((MulAmt % 9) == 0) {
25142 MulAmt2 = MulAmt / 9;
25143 } else if ((MulAmt % 5) == 0) {
25145 MulAmt2 = MulAmt / 5;
25146 } else if ((MulAmt % 3) == 0) {
25148 MulAmt2 = MulAmt / 3;
25154 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
25156 if (isPowerOf2_64(MulAmt2) &&
25157 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
25158 // If second multiplifer is pow2, issue it first. We want the multiply by
25159 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
25161 std::swap(MulAmt1, MulAmt2);
25163 if (isPowerOf2_64(MulAmt1))
25164 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
25165 DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
25167 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
25168 DAG.getConstant(MulAmt1, DL, VT));
25170 if (isPowerOf2_64(MulAmt2))
25171 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
25172 DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
25174 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
25175 DAG.getConstant(MulAmt2, DL, VT));
25179 assert(MulAmt != 0 && MulAmt != (VT == MVT::i64 ? UINT64_MAX : UINT32_MAX)
25180 && "Both cases that could cause potential overflows should have "
25181 "already been handled.");
25182 if (isPowerOf2_64(MulAmt - 1))
25183 // (mul x, 2^N + 1) => (add (shl x, N), x)
25184 NewMul = DAG.getNode(ISD::ADD, DL, VT, N->getOperand(0),
25185 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
25186 DAG.getConstant(Log2_64(MulAmt - 1), DL,
25189 else if (isPowerOf2_64(MulAmt + 1))
25190 // (mul x, 2^N - 1) => (sub (shl x, N), x)
25191 NewMul = DAG.getNode(ISD::SUB, DL, VT, DAG.getNode(ISD::SHL, DL, VT,
25193 DAG.getConstant(Log2_64(MulAmt + 1),
25194 DL, MVT::i8)), N->getOperand(0));
25198 // Do not add new nodes to DAG combiner worklist.
25199 DCI.CombineTo(N, NewMul, false);
25204 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
25205 SDValue N0 = N->getOperand(0);
25206 SDValue N1 = N->getOperand(1);
25207 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
25208 EVT VT = N0.getValueType();
25210 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
25211 // since the result of setcc_c is all zero's or all ones.
25212 if (VT.isInteger() && !VT.isVector() &&
25213 N1C && N0.getOpcode() == ISD::AND &&
25214 N0.getOperand(1).getOpcode() == ISD::Constant) {
25215 SDValue N00 = N0.getOperand(0);
25216 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
25217 APInt ShAmt = N1C->getAPIntValue();
25218 Mask = Mask.shl(ShAmt);
25219 bool MaskOK = false;
25220 // We can handle cases concerning bit-widening nodes containing setcc_c if
25221 // we carefully interrogate the mask to make sure we are semantics
25223 // The transform is not safe if the result of C1 << C2 exceeds the bitwidth
25224 // of the underlying setcc_c operation if the setcc_c was zero extended.
25225 // Consider the following example:
25226 // zext(setcc_c) -> i32 0x0000FFFF
25227 // c1 -> i32 0x0000FFFF
25228 // c2 -> i32 0x00000001
25229 // (shl (and (setcc_c), c1), c2) -> i32 0x0001FFFE
25230 // (and setcc_c, (c1 << c2)) -> i32 0x0000FFFE
25231 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25233 } else if (N00.getOpcode() == ISD::SIGN_EXTEND &&
25234 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
25236 } else if ((N00.getOpcode() == ISD::ZERO_EXTEND ||
25237 N00.getOpcode() == ISD::ANY_EXTEND) &&
25238 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
25239 MaskOK = Mask.isIntN(N00.getOperand(0).getValueSizeInBits());
25241 if (MaskOK && Mask != 0) {
25243 return DAG.getNode(ISD::AND, DL, VT, N00, DAG.getConstant(Mask, DL, VT));
25247 // Hardware support for vector shifts is sparse which makes us scalarize the
25248 // vector operations in many cases. Also, on sandybridge ADD is faster than
25250 // (shl V, 1) -> add V,V
25251 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
25252 if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
25253 assert(N0.getValueType().isVector() && "Invalid vector shift type");
25254 // We shift all of the values by one. In many cases we do not have
25255 // hardware support for this operation. This is better expressed as an ADD
25257 if (N1SplatC->getAPIntValue() == 1)
25258 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
25264 static SDValue PerformSRACombine(SDNode *N, SelectionDAG &DAG) {
25265 SDValue N0 = N->getOperand(0);
25266 SDValue N1 = N->getOperand(1);
25267 EVT VT = N0.getValueType();
25268 unsigned Size = VT.getSizeInBits();
25270 // fold (ashr (shl, a, [56,48,32,24,16]), SarConst)
25271 // into (shl, (sext (a), [56,48,32,24,16] - SarConst)) or
25272 // into (lshr, (sext (a), SarConst - [56,48,32,24,16]))
25273 // depending on sign of (SarConst - [56,48,32,24,16])
25275 // sexts in X86 are MOVs. The MOVs have the same code size
25276 // as above SHIFTs (only SHIFT on 1 has lower code size).
25277 // However the MOVs have 2 advantages to a SHIFT:
25278 // 1. MOVs can write to a register that differs from source
25279 // 2. MOVs accept memory operands
25281 if (!VT.isInteger() || VT.isVector() || N1.getOpcode() != ISD::Constant ||
25282 N0.getOpcode() != ISD::SHL || !N0.hasOneUse() ||
25283 N0.getOperand(1).getOpcode() != ISD::Constant)
25286 SDValue N00 = N0.getOperand(0);
25287 SDValue N01 = N0.getOperand(1);
25288 APInt ShlConst = (cast<ConstantSDNode>(N01))->getAPIntValue();
25289 APInt SarConst = (cast<ConstantSDNode>(N1))->getAPIntValue();
25290 EVT CVT = N1.getValueType();
25292 if (SarConst.isNegative())
25295 for (MVT SVT : MVT::integer_valuetypes()) {
25296 unsigned ShiftSize = SVT.getSizeInBits();
25297 // skipping types without corresponding sext/zext and
25298 // ShlConst that is not one of [56,48,32,24,16]
25299 if (ShiftSize < 8 || ShiftSize > 64 || ShlConst != Size - ShiftSize)
25303 DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, N00, DAG.getValueType(SVT));
25304 SarConst = SarConst - (Size - ShiftSize);
25307 else if (SarConst.isNegative())
25308 return DAG.getNode(ISD::SHL, DL, VT, NN,
25309 DAG.getConstant(-SarConst, DL, CVT));
25311 return DAG.getNode(ISD::SRA, DL, VT, NN,
25312 DAG.getConstant(SarConst, DL, CVT));
25317 /// \brief Returns a vector of 0s if the node in input is a vector logical
25318 /// shift by a constant amount which is known to be bigger than or equal
25319 /// to the vector element size in bits.
25320 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
25321 const X86Subtarget *Subtarget) {
25322 EVT VT = N->getValueType(0);
25324 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
25325 (!Subtarget->hasInt256() ||
25326 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
25329 SDValue Amt = N->getOperand(1);
25331 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
25332 if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
25333 APInt ShiftAmt = AmtSplat->getAPIntValue();
25334 unsigned MaxAmount =
25335 VT.getSimpleVT().getVectorElementType().getSizeInBits();
25337 // SSE2/AVX2 logical shifts always return a vector of 0s
25338 // if the shift amount is bigger than or equal to
25339 // the element size. The constant shift amount will be
25340 // encoded as a 8-bit immediate.
25341 if (ShiftAmt.trunc(8).uge(MaxAmount))
25342 return getZeroVector(VT.getSimpleVT(), Subtarget, DAG, DL);
25348 /// PerformShiftCombine - Combine shifts.
25349 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
25350 TargetLowering::DAGCombinerInfo &DCI,
25351 const X86Subtarget *Subtarget) {
25352 if (N->getOpcode() == ISD::SHL)
25353 if (SDValue V = PerformSHLCombine(N, DAG))
25356 if (N->getOpcode() == ISD::SRA)
25357 if (SDValue V = PerformSRACombine(N, DAG))
25360 // Try to fold this logical shift into a zero vector.
25361 if (N->getOpcode() != ISD::SRA)
25362 if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
25368 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
25369 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
25370 // and friends. Likewise for OR -> CMPNEQSS.
25371 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
25372 TargetLowering::DAGCombinerInfo &DCI,
25373 const X86Subtarget *Subtarget) {
25376 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
25377 // we're requiring SSE2 for both.
25378 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
25379 SDValue N0 = N->getOperand(0);
25380 SDValue N1 = N->getOperand(1);
25381 SDValue CMP0 = N0->getOperand(1);
25382 SDValue CMP1 = N1->getOperand(1);
25385 // The SETCCs should both refer to the same CMP.
25386 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
25389 SDValue CMP00 = CMP0->getOperand(0);
25390 SDValue CMP01 = CMP0->getOperand(1);
25391 EVT VT = CMP00.getValueType();
25393 if (VT == MVT::f32 || VT == MVT::f64) {
25394 bool ExpectingFlags = false;
25395 // Check for any users that want flags:
25396 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
25397 !ExpectingFlags && UI != UE; ++UI)
25398 switch (UI->getOpcode()) {
25403 ExpectingFlags = true;
25405 case ISD::CopyToReg:
25406 case ISD::SIGN_EXTEND:
25407 case ISD::ZERO_EXTEND:
25408 case ISD::ANY_EXTEND:
25412 if (!ExpectingFlags) {
25413 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
25414 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
25416 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
25417 X86::CondCode tmp = cc0;
25422 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
25423 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
25424 // FIXME: need symbolic constants for these magic numbers.
25425 // See X86ATTInstPrinter.cpp:printSSECC().
25426 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
25427 if (Subtarget->hasAVX512()) {
25428 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
25430 DAG.getConstant(x86cc, DL, MVT::i8));
25431 if (N->getValueType(0) != MVT::i1)
25432 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
25436 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
25437 CMP00.getValueType(), CMP00, CMP01,
25438 DAG.getConstant(x86cc, DL,
25441 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
25442 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
25444 if (is64BitFP && !Subtarget->is64Bit()) {
25445 // On a 32-bit target, we cannot bitcast the 64-bit float to a
25446 // 64-bit integer, since that's not a legal type. Since
25447 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
25448 // bits, but can do this little dance to extract the lowest 32 bits
25449 // and work with those going forward.
25450 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
25452 SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
25453 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
25454 Vector32, DAG.getIntPtrConstant(0, DL));
25458 SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
25459 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
25460 DAG.getConstant(1, DL, IntVT));
25461 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
25463 return OneBitOfTruth;
25471 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
25472 /// so it can be folded inside ANDNP.
25473 static bool CanFoldXORWithAllOnes(const SDNode *N) {
25474 EVT VT = N->getValueType(0);
25476 // Match direct AllOnes for 128 and 256-bit vectors
25477 if (ISD::isBuildVectorAllOnes(N))
25480 // Look through a bit convert.
25481 if (N->getOpcode() == ISD::BITCAST)
25482 N = N->getOperand(0).getNode();
25484 // Sometimes the operand may come from a insert_subvector building a 256-bit
25486 if (VT.is256BitVector() &&
25487 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
25488 SDValue V1 = N->getOperand(0);
25489 SDValue V2 = N->getOperand(1);
25491 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
25492 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
25493 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
25494 ISD::isBuildVectorAllOnes(V2.getNode()))
25501 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
25502 // register. In most cases we actually compare or select YMM-sized registers
25503 // and mixing the two types creates horrible code. This method optimizes
25504 // some of the transition sequences.
25505 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
25506 TargetLowering::DAGCombinerInfo &DCI,
25507 const X86Subtarget *Subtarget) {
25508 EVT VT = N->getValueType(0);
25509 if (!VT.is256BitVector())
25512 assert((N->getOpcode() == ISD::ANY_EXTEND ||
25513 N->getOpcode() == ISD::ZERO_EXTEND ||
25514 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
25516 SDValue Narrow = N->getOperand(0);
25517 EVT NarrowVT = Narrow->getValueType(0);
25518 if (!NarrowVT.is128BitVector())
25521 if (Narrow->getOpcode() != ISD::XOR &&
25522 Narrow->getOpcode() != ISD::AND &&
25523 Narrow->getOpcode() != ISD::OR)
25526 SDValue N0 = Narrow->getOperand(0);
25527 SDValue N1 = Narrow->getOperand(1);
25530 // The Left side has to be a trunc.
25531 if (N0.getOpcode() != ISD::TRUNCATE)
25534 // The type of the truncated inputs.
25535 EVT WideVT = N0->getOperand(0)->getValueType(0);
25539 // The right side has to be a 'trunc' or a constant vector.
25540 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
25541 ConstantSDNode *RHSConstSplat = nullptr;
25542 if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
25543 RHSConstSplat = RHSBV->getConstantSplatNode();
25544 if (!RHSTrunc && !RHSConstSplat)
25547 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25549 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
25552 // Set N0 and N1 to hold the inputs to the new wide operation.
25553 N0 = N0->getOperand(0);
25554 if (RHSConstSplat) {
25555 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getVectorElementType(),
25556 SDValue(RHSConstSplat, 0));
25557 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
25558 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
25559 } else if (RHSTrunc) {
25560 N1 = N1->getOperand(0);
25563 // Generate the wide operation.
25564 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
25565 unsigned Opcode = N->getOpcode();
25567 case ISD::ANY_EXTEND:
25569 case ISD::ZERO_EXTEND: {
25570 unsigned InBits = NarrowVT.getScalarSizeInBits();
25571 APInt Mask = APInt::getAllOnesValue(InBits);
25572 Mask = Mask.zext(VT.getScalarSizeInBits());
25573 return DAG.getNode(ISD::AND, DL, VT,
25574 Op, DAG.getConstant(Mask, DL, VT));
25576 case ISD::SIGN_EXTEND:
25577 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
25578 Op, DAG.getValueType(NarrowVT));
25580 llvm_unreachable("Unexpected opcode");
25584 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
25585 TargetLowering::DAGCombinerInfo &DCI,
25586 const X86Subtarget *Subtarget) {
25587 SDValue N0 = N->getOperand(0);
25588 SDValue N1 = N->getOperand(1);
25591 // A vector zext_in_reg may be represented as a shuffle,
25592 // feeding into a bitcast (this represents anyext) feeding into
25593 // an and with a mask.
25594 // We'd like to try to combine that into a shuffle with zero
25595 // plus a bitcast, removing the and.
25596 if (N0.getOpcode() != ISD::BITCAST ||
25597 N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
25600 // The other side of the AND should be a splat of 2^C, where C
25601 // is the number of bits in the source type.
25602 if (N1.getOpcode() == ISD::BITCAST)
25603 N1 = N1.getOperand(0);
25604 if (N1.getOpcode() != ISD::BUILD_VECTOR)
25606 BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
25608 ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
25609 EVT SrcType = Shuffle->getValueType(0);
25611 // We expect a single-source shuffle
25612 if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
25615 unsigned SrcSize = SrcType.getScalarSizeInBits();
25617 APInt SplatValue, SplatUndef;
25618 unsigned SplatBitSize;
25620 if (!Vector->isConstantSplat(SplatValue, SplatUndef,
25621 SplatBitSize, HasAnyUndefs))
25624 unsigned ResSize = N1.getValueType().getScalarSizeInBits();
25625 // Make sure the splat matches the mask we expect
25626 if (SplatBitSize > ResSize ||
25627 (SplatValue + 1).exactLogBase2() != (int)SrcSize)
25630 // Make sure the input and output size make sense
25631 if (SrcSize >= ResSize || ResSize % SrcSize)
25634 // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
25635 // The number of u's between each two values depends on the ratio between
25636 // the source and dest type.
25637 unsigned ZextRatio = ResSize / SrcSize;
25638 bool IsZext = true;
25639 for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
25640 if (i % ZextRatio) {
25641 if (Shuffle->getMaskElt(i) > 0) {
25647 if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
25648 // Expected element number
25658 // Ok, perform the transformation - replace the shuffle with
25659 // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
25660 // (instead of undef) where the k elements come from the zero vector.
25661 SmallVector<int, 8> Mask;
25662 unsigned NumElems = SrcType.getVectorNumElements();
25663 for (unsigned i = 0; i < NumElems; ++i)
25665 Mask.push_back(NumElems);
25667 Mask.push_back(i / ZextRatio);
25669 SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
25670 Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
25671 return DAG.getBitcast(N0.getValueType(), NewShuffle);
25674 /// If both input operands of a logic op are being cast from floating point
25675 /// types, try to convert this into a floating point logic node to avoid
25676 /// unnecessary moves from SSE to integer registers.
25677 static SDValue convertIntLogicToFPLogic(SDNode *N, SelectionDAG &DAG,
25678 const X86Subtarget *Subtarget) {
25679 unsigned FPOpcode = ISD::DELETED_NODE;
25680 if (N->getOpcode() == ISD::AND)
25681 FPOpcode = X86ISD::FAND;
25682 else if (N->getOpcode() == ISD::OR)
25683 FPOpcode = X86ISD::FOR;
25684 else if (N->getOpcode() == ISD::XOR)
25685 FPOpcode = X86ISD::FXOR;
25687 assert(FPOpcode != ISD::DELETED_NODE &&
25688 "Unexpected input node for FP logic conversion");
25690 EVT VT = N->getValueType(0);
25691 SDValue N0 = N->getOperand(0);
25692 SDValue N1 = N->getOperand(1);
25694 if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST &&
25695 ((Subtarget->hasSSE1() && VT == MVT::i32) ||
25696 (Subtarget->hasSSE2() && VT == MVT::i64))) {
25697 SDValue N00 = N0.getOperand(0);
25698 SDValue N10 = N1.getOperand(0);
25699 EVT N00Type = N00.getValueType();
25700 EVT N10Type = N10.getValueType();
25701 if (N00Type.isFloatingPoint() && N10Type.isFloatingPoint()) {
25702 SDValue FPLogic = DAG.getNode(FPOpcode, DL, N00Type, N00, N10);
25703 return DAG.getBitcast(VT, FPLogic);
25709 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
25710 TargetLowering::DAGCombinerInfo &DCI,
25711 const X86Subtarget *Subtarget) {
25712 if (DCI.isBeforeLegalizeOps())
25715 if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
25718 if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
25721 if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
25724 EVT VT = N->getValueType(0);
25725 SDValue N0 = N->getOperand(0);
25726 SDValue N1 = N->getOperand(1);
25729 // Create BEXTR instructions
25730 // BEXTR is ((X >> imm) & (2**size-1))
25731 if (VT == MVT::i32 || VT == MVT::i64) {
25732 // Check for BEXTR.
25733 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
25734 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
25735 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
25736 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
25737 if (MaskNode && ShiftNode) {
25738 uint64_t Mask = MaskNode->getZExtValue();
25739 uint64_t Shift = ShiftNode->getZExtValue();
25740 if (isMask_64(Mask)) {
25741 uint64_t MaskSize = countPopulation(Mask);
25742 if (Shift + MaskSize <= VT.getSizeInBits())
25743 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
25744 DAG.getConstant(Shift | (MaskSize << 8), DL,
25753 // Want to form ANDNP nodes:
25754 // 1) In the hopes of then easily combining them with OR and AND nodes
25755 // to form PBLEND/PSIGN.
25756 // 2) To match ANDN packed intrinsics
25757 if (VT != MVT::v2i64 && VT != MVT::v4i64)
25760 // Check LHS for vnot
25761 if (N0.getOpcode() == ISD::XOR &&
25762 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
25763 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
25764 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
25766 // Check RHS for vnot
25767 if (N1.getOpcode() == ISD::XOR &&
25768 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
25769 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
25770 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
25775 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
25776 TargetLowering::DAGCombinerInfo &DCI,
25777 const X86Subtarget *Subtarget) {
25778 if (DCI.isBeforeLegalizeOps())
25781 if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
25784 if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
25787 SDValue N0 = N->getOperand(0);
25788 SDValue N1 = N->getOperand(1);
25789 EVT VT = N->getValueType(0);
25791 // look for psign/blend
25792 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
25793 if (!Subtarget->hasSSSE3() ||
25794 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
25797 // Canonicalize pandn to RHS
25798 if (N0.getOpcode() == X86ISD::ANDNP)
25800 // or (and (m, y), (pandn m, x))
25801 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
25802 SDValue Mask = N1.getOperand(0);
25803 SDValue X = N1.getOperand(1);
25805 if (N0.getOperand(0) == Mask)
25806 Y = N0.getOperand(1);
25807 if (N0.getOperand(1) == Mask)
25808 Y = N0.getOperand(0);
25810 // Check to see if the mask appeared in both the AND and ANDNP and
25814 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
25815 // Look through mask bitcast.
25816 if (Mask.getOpcode() == ISD::BITCAST)
25817 Mask = Mask.getOperand(0);
25818 if (X.getOpcode() == ISD::BITCAST)
25819 X = X.getOperand(0);
25820 if (Y.getOpcode() == ISD::BITCAST)
25821 Y = Y.getOperand(0);
25823 EVT MaskVT = Mask.getValueType();
25825 // Validate that the Mask operand is a vector sra node.
25826 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
25827 // there is no psrai.b
25828 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
25829 unsigned SraAmt = ~0;
25830 if (Mask.getOpcode() == ISD::SRA) {
25831 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
25832 if (auto *AmtConst = AmtBV->getConstantSplatNode())
25833 SraAmt = AmtConst->getZExtValue();
25834 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
25835 SDValue SraC = Mask.getOperand(1);
25836 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
25838 if ((SraAmt + 1) != EltBits)
25843 // Now we know we at least have a plendvb with the mask val. See if
25844 // we can form a psignb/w/d.
25845 // psign = x.type == y.type == mask.type && y = sub(0, x);
25846 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
25847 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
25848 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
25849 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
25850 "Unsupported VT for PSIGN");
25851 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
25852 return DAG.getBitcast(VT, Mask);
25854 // PBLENDVB only available on SSE 4.1
25855 if (!Subtarget->hasSSE41())
25858 MVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
25860 X = DAG.getBitcast(BlendVT, X);
25861 Y = DAG.getBitcast(BlendVT, Y);
25862 Mask = DAG.getBitcast(BlendVT, Mask);
25863 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
25864 return DAG.getBitcast(VT, Mask);
25868 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
25871 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
25872 bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
25874 // SHLD/SHRD instructions have lower register pressure, but on some
25875 // platforms they have higher latency than the equivalent
25876 // series of shifts/or that would otherwise be generated.
25877 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
25878 // have higher latencies and we are not optimizing for size.
25879 if (!OptForSize && Subtarget->isSHLDSlow())
25882 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
25884 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
25886 if (!N0.hasOneUse() || !N1.hasOneUse())
25889 SDValue ShAmt0 = N0.getOperand(1);
25890 if (ShAmt0.getValueType() != MVT::i8)
25892 SDValue ShAmt1 = N1.getOperand(1);
25893 if (ShAmt1.getValueType() != MVT::i8)
25895 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
25896 ShAmt0 = ShAmt0.getOperand(0);
25897 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
25898 ShAmt1 = ShAmt1.getOperand(0);
25901 unsigned Opc = X86ISD::SHLD;
25902 SDValue Op0 = N0.getOperand(0);
25903 SDValue Op1 = N1.getOperand(0);
25904 if (ShAmt0.getOpcode() == ISD::SUB) {
25905 Opc = X86ISD::SHRD;
25906 std::swap(Op0, Op1);
25907 std::swap(ShAmt0, ShAmt1);
25910 unsigned Bits = VT.getSizeInBits();
25911 if (ShAmt1.getOpcode() == ISD::SUB) {
25912 SDValue Sum = ShAmt1.getOperand(0);
25913 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
25914 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
25915 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
25916 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
25917 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
25918 return DAG.getNode(Opc, DL, VT,
25920 DAG.getNode(ISD::TRUNCATE, DL,
25923 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
25924 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
25926 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
25927 return DAG.getNode(Opc, DL, VT,
25928 N0.getOperand(0), N1.getOperand(0),
25929 DAG.getNode(ISD::TRUNCATE, DL,
25936 // Generate NEG and CMOV for integer abs.
25937 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
25938 EVT VT = N->getValueType(0);
25940 // Since X86 does not have CMOV for 8-bit integer, we don't convert
25941 // 8-bit integer abs to NEG and CMOV.
25942 if (VT.isInteger() && VT.getSizeInBits() == 8)
25945 SDValue N0 = N->getOperand(0);
25946 SDValue N1 = N->getOperand(1);
25949 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
25950 // and change it to SUB and CMOV.
25951 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
25952 N0.getOpcode() == ISD::ADD &&
25953 N0.getOperand(1) == N1 &&
25954 N1.getOpcode() == ISD::SRA &&
25955 N1.getOperand(0) == N0.getOperand(0))
25956 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
25957 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
25958 // Generate SUB & CMOV.
25959 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
25960 DAG.getConstant(0, DL, VT), N0.getOperand(0));
25962 SDValue Ops[] = { N0.getOperand(0), Neg,
25963 DAG.getConstant(X86::COND_GE, DL, MVT::i8),
25964 SDValue(Neg.getNode(), 1) };
25965 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
25970 // Try to turn tests against the signbit in the form of:
25971 // XOR(TRUNCATE(SRL(X, size(X)-1)), 1)
25974 static SDValue foldXorTruncShiftIntoCmp(SDNode *N, SelectionDAG &DAG) {
25975 // This is only worth doing if the output type is i8.
25976 if (N->getValueType(0) != MVT::i8)
25979 SDValue N0 = N->getOperand(0);
25980 SDValue N1 = N->getOperand(1);
25982 // We should be performing an xor against a truncated shift.
25983 if (N0.getOpcode() != ISD::TRUNCATE || !N0.hasOneUse())
25986 // Make sure we are performing an xor against one.
25987 if (!isOneConstant(N1))
25990 // SetCC on x86 zero extends so only act on this if it's a logical shift.
25991 SDValue Shift = N0.getOperand(0);
25992 if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse())
25995 // Make sure we are truncating from one of i16, i32 or i64.
25996 EVT ShiftTy = Shift.getValueType();
25997 if (ShiftTy != MVT::i16 && ShiftTy != MVT::i32 && ShiftTy != MVT::i64)
26000 // Make sure the shift amount extracts the sign bit.
26001 if (!isa<ConstantSDNode>(Shift.getOperand(1)) ||
26002 Shift.getConstantOperandVal(1) != ShiftTy.getSizeInBits() - 1)
26005 // Create a greater-than comparison against -1.
26006 // N.B. Using SETGE against 0 works but we want a canonical looking
26007 // comparison, using SETGT matches up with what TranslateX86CC.
26009 SDValue ShiftOp = Shift.getOperand(0);
26010 EVT ShiftOpTy = ShiftOp.getValueType();
26011 SDValue Cond = DAG.getSetCC(DL, MVT::i8, ShiftOp,
26012 DAG.getConstant(-1, DL, ShiftOpTy), ISD::SETGT);
26016 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
26017 TargetLowering::DAGCombinerInfo &DCI,
26018 const X86Subtarget *Subtarget) {
26019 if (DCI.isBeforeLegalizeOps())
26022 if (SDValue RV = foldXorTruncShiftIntoCmp(N, DAG))
26025 if (Subtarget->hasCMov())
26026 if (SDValue RV = performIntegerAbsCombine(N, DAG))
26029 if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
26035 /// This function detects the AVG pattern between vectors of unsigned i8/i16,
26036 /// which is c = (a + b + 1) / 2, and replace this operation with the efficient
26037 /// X86ISD::AVG instruction.
26038 static SDValue detectAVGPattern(SDValue In, EVT VT, SelectionDAG &DAG,
26039 const X86Subtarget *Subtarget, SDLoc DL) {
26040 if (!VT.isVector() || !VT.isSimple())
26042 EVT InVT = In.getValueType();
26043 unsigned NumElems = VT.getVectorNumElements();
26045 EVT ScalarVT = VT.getVectorElementType();
26046 if (!((ScalarVT == MVT::i8 || ScalarVT == MVT::i16) &&
26047 isPowerOf2_32(NumElems)))
26050 // InScalarVT is the intermediate type in AVG pattern and it should be greater
26051 // than the original input type (i8/i16).
26052 EVT InScalarVT = InVT.getVectorElementType();
26053 if (InScalarVT.getSizeInBits() <= ScalarVT.getSizeInBits())
26056 if (Subtarget->hasAVX512()) {
26057 if (VT.getSizeInBits() > 512)
26059 } else if (Subtarget->hasAVX2()) {
26060 if (VT.getSizeInBits() > 256)
26063 if (VT.getSizeInBits() > 128)
26067 // Detect the following pattern:
26069 // %1 = zext <N x i8> %a to <N x i32>
26070 // %2 = zext <N x i8> %b to <N x i32>
26071 // %3 = add nuw nsw <N x i32> %1, <i32 1 x N>
26072 // %4 = add nuw nsw <N x i32> %3, %2
26073 // %5 = lshr <N x i32> %N, <i32 1 x N>
26074 // %6 = trunc <N x i32> %5 to <N x i8>
26076 // In AVX512, the last instruction can also be a trunc store.
26078 if (In.getOpcode() != ISD::SRL)
26081 // A lambda checking the given SDValue is a constant vector and each element
26082 // is in the range [Min, Max].
26083 auto IsConstVectorInRange = [](SDValue V, unsigned Min, unsigned Max) {
26084 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(V);
26085 if (!BV || !BV->isConstant())
26087 for (unsigned i = 0, e = V.getNumOperands(); i < e; i++) {
26088 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(i));
26091 uint64_t Val = C->getZExtValue();
26092 if (Val < Min || Val > Max)
26098 // Check if each element of the vector is left-shifted by one.
26099 auto LHS = In.getOperand(0);
26100 auto RHS = In.getOperand(1);
26101 if (!IsConstVectorInRange(RHS, 1, 1))
26103 if (LHS.getOpcode() != ISD::ADD)
26106 // Detect a pattern of a + b + 1 where the order doesn't matter.
26107 SDValue Operands[3];
26108 Operands[0] = LHS.getOperand(0);
26109 Operands[1] = LHS.getOperand(1);
26111 // Take care of the case when one of the operands is a constant vector whose
26112 // element is in the range [1, 256].
26113 if (IsConstVectorInRange(Operands[1], 1, ScalarVT == MVT::i8 ? 256 : 65536) &&
26114 Operands[0].getOpcode() == ISD::ZERO_EXTEND &&
26115 Operands[0].getOperand(0).getValueType() == VT) {
26116 // The pattern is detected. Subtract one from the constant vector, then
26117 // demote it and emit X86ISD::AVG instruction.
26118 SDValue One = DAG.getConstant(1, DL, InScalarVT);
26119 SDValue Ones = DAG.getNode(ISD::BUILD_VECTOR, DL, InVT,
26120 SmallVector<SDValue, 8>(NumElems, One));
26121 Operands[1] = DAG.getNode(ISD::SUB, DL, InVT, Operands[1], Ones);
26122 Operands[1] = DAG.getNode(ISD::TRUNCATE, DL, VT, Operands[1]);
26123 return DAG.getNode(X86ISD::AVG, DL, VT, Operands[0].getOperand(0),
26127 if (Operands[0].getOpcode() == ISD::ADD)
26128 std::swap(Operands[0], Operands[1]);
26129 else if (Operands[1].getOpcode() != ISD::ADD)
26131 Operands[2] = Operands[1].getOperand(0);
26132 Operands[1] = Operands[1].getOperand(1);
26134 // Now we have three operands of two additions. Check that one of them is a
26135 // constant vector with ones, and the other two are promoted from i8/i16.
26136 for (int i = 0; i < 3; ++i) {
26137 if (!IsConstVectorInRange(Operands[i], 1, 1))
26139 std::swap(Operands[i], Operands[2]);
26141 // Check if Operands[0] and Operands[1] are results of type promotion.
26142 for (int j = 0; j < 2; ++j)
26143 if (Operands[j].getOpcode() != ISD::ZERO_EXTEND ||
26144 Operands[j].getOperand(0).getValueType() != VT)
26147 // The pattern is detected, emit X86ISD::AVG instruction.
26148 return DAG.getNode(X86ISD::AVG, DL, VT, Operands[0].getOperand(0),
26149 Operands[1].getOperand(0));
26155 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
26156 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
26157 TargetLowering::DAGCombinerInfo &DCI,
26158 const X86Subtarget *Subtarget) {
26159 LoadSDNode *Ld = cast<LoadSDNode>(N);
26160 EVT RegVT = Ld->getValueType(0);
26161 EVT MemVT = Ld->getMemoryVT();
26163 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26165 // For chips with slow 32-byte unaligned loads, break the 32-byte operation
26166 // into two 16-byte operations.
26167 ISD::LoadExtType Ext = Ld->getExtensionType();
26169 unsigned AddressSpace = Ld->getAddressSpace();
26170 unsigned Alignment = Ld->getAlignment();
26171 if (RegVT.is256BitVector() && !DCI.isBeforeLegalizeOps() &&
26172 Ext == ISD::NON_EXTLOAD &&
26173 TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), RegVT,
26174 AddressSpace, Alignment, &Fast) && !Fast) {
26175 unsigned NumElems = RegVT.getVectorNumElements();
26179 SDValue Ptr = Ld->getBasePtr();
26180 SDValue Increment =
26181 DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
26183 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
26185 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
26186 Ld->getPointerInfo(), Ld->isVolatile(),
26187 Ld->isNonTemporal(), Ld->isInvariant(),
26189 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
26190 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
26191 Ld->getPointerInfo(), Ld->isVolatile(),
26192 Ld->isNonTemporal(), Ld->isInvariant(),
26193 std::min(16U, Alignment));
26194 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
26196 Load2.getValue(1));
26198 SDValue NewVec = DAG.getUNDEF(RegVT);
26199 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
26200 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
26201 return DCI.CombineTo(N, NewVec, TF, true);
26207 /// PerformMLOADCombine - Resolve extending loads
26208 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
26209 TargetLowering::DAGCombinerInfo &DCI,
26210 const X86Subtarget *Subtarget) {
26211 MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
26212 if (Mld->getExtensionType() != ISD::SEXTLOAD)
26215 EVT VT = Mld->getValueType(0);
26216 unsigned NumElems = VT.getVectorNumElements();
26217 EVT LdVT = Mld->getMemoryVT();
26220 assert(LdVT != VT && "Cannot extend to the same type");
26221 unsigned ToSz = VT.getVectorElementType().getSizeInBits();
26222 unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
26223 // From, To sizes and ElemCount must be pow of two
26224 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
26225 "Unexpected size for extending masked load");
26227 unsigned SizeRatio = ToSz / FromSz;
26228 assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
26230 // Create a type on which we perform the shuffle
26231 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
26232 LdVT.getScalarType(), NumElems*SizeRatio);
26233 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
26235 // Convert Src0 value
26236 SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
26237 if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
26238 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
26239 for (unsigned i = 0; i != NumElems; ++i)
26240 ShuffleVec[i] = i * SizeRatio;
26242 // Can't shuffle using an illegal type.
26243 assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
26244 "WideVecVT should be legal");
26245 WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
26246 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
26248 // Prepare the new mask
26250 SDValue Mask = Mld->getMask();
26251 if (Mask.getValueType() == VT) {
26252 // Mask and original value have the same type
26253 NewMask = DAG.getBitcast(WideVecVT, Mask);
26254 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
26255 for (unsigned i = 0; i != NumElems; ++i)
26256 ShuffleVec[i] = i * SizeRatio;
26257 for (unsigned i = NumElems; i != NumElems * SizeRatio; ++i)
26258 ShuffleVec[i] = NumElems * SizeRatio;
26259 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
26260 DAG.getConstant(0, dl, WideVecVT),
26264 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
26265 unsigned WidenNumElts = NumElems*SizeRatio;
26266 unsigned MaskNumElts = VT.getVectorNumElements();
26267 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
26270 unsigned NumConcat = WidenNumElts / MaskNumElts;
26271 SmallVector<SDValue, 16> Ops(NumConcat);
26272 SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
26274 for (unsigned i = 1; i != NumConcat; ++i)
26277 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
26280 SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
26281 Mld->getBasePtr(), NewMask, WideSrc0,
26282 Mld->getMemoryVT(), Mld->getMemOperand(),
26284 SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
26285 return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
26287 /// PerformMSTORECombine - Resolve truncating stores
26288 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
26289 const X86Subtarget *Subtarget) {
26290 MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
26291 if (!Mst->isTruncatingStore())
26294 EVT VT = Mst->getValue().getValueType();
26295 unsigned NumElems = VT.getVectorNumElements();
26296 EVT StVT = Mst->getMemoryVT();
26299 assert(StVT != VT && "Cannot truncate to the same type");
26300 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
26301 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
26303 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26305 // The truncating store is legal in some cases. For example
26306 // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
26307 // are designated for truncate store.
26308 // In this case we don't need any further transformations.
26309 if (TLI.isTruncStoreLegal(VT, StVT))
26312 // From, To sizes and ElemCount must be pow of two
26313 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
26314 "Unexpected size for truncating masked store");
26315 // We are going to use the original vector elt for storing.
26316 // Accumulated smaller vector elements must be a multiple of the store size.
26317 assert (((NumElems * FromSz) % ToSz) == 0 &&
26318 "Unexpected ratio for truncating masked store");
26320 unsigned SizeRatio = FromSz / ToSz;
26321 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
26323 // Create a type on which we perform the shuffle
26324 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
26325 StVT.getScalarType(), NumElems*SizeRatio);
26327 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
26329 SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
26330 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
26331 for (unsigned i = 0; i != NumElems; ++i)
26332 ShuffleVec[i] = i * SizeRatio;
26334 // Can't shuffle using an illegal type.
26335 assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
26336 "WideVecVT should be legal");
26338 SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
26339 DAG.getUNDEF(WideVecVT),
26343 SDValue Mask = Mst->getMask();
26344 if (Mask.getValueType() == VT) {
26345 // Mask and original value have the same type
26346 NewMask = DAG.getBitcast(WideVecVT, Mask);
26347 for (unsigned i = 0; i != NumElems; ++i)
26348 ShuffleVec[i] = i * SizeRatio;
26349 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
26350 ShuffleVec[i] = NumElems*SizeRatio;
26351 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
26352 DAG.getConstant(0, dl, WideVecVT),
26356 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
26357 unsigned WidenNumElts = NumElems*SizeRatio;
26358 unsigned MaskNumElts = VT.getVectorNumElements();
26359 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
26362 unsigned NumConcat = WidenNumElts / MaskNumElts;
26363 SmallVector<SDValue, 16> Ops(NumConcat);
26364 SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
26366 for (unsigned i = 1; i != NumConcat; ++i)
26369 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
26372 return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal,
26373 Mst->getBasePtr(), NewMask, StVT,
26374 Mst->getMemOperand(), false);
26376 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
26377 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
26378 const X86Subtarget *Subtarget) {
26379 StoreSDNode *St = cast<StoreSDNode>(N);
26380 EVT VT = St->getValue().getValueType();
26381 EVT StVT = St->getMemoryVT();
26383 SDValue StoredVal = St->getOperand(1);
26384 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26386 // If we are saving a concatenation of two XMM registers and 32-byte stores
26387 // are slow, such as on Sandy Bridge, perform two 16-byte stores.
26389 unsigned AddressSpace = St->getAddressSpace();
26390 unsigned Alignment = St->getAlignment();
26391 if (VT.is256BitVector() && StVT == VT &&
26392 TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
26393 AddressSpace, Alignment, &Fast) && !Fast) {
26394 unsigned NumElems = VT.getVectorNumElements();
26398 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
26399 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
26402 DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
26403 SDValue Ptr0 = St->getBasePtr();
26404 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
26406 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
26407 St->getPointerInfo(), St->isVolatile(),
26408 St->isNonTemporal(), Alignment);
26409 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
26410 St->getPointerInfo(), St->isVolatile(),
26411 St->isNonTemporal(),
26412 std::min(16U, Alignment));
26413 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
26416 // Optimize trunc store (of multiple scalars) to shuffle and store.
26417 // First, pack all of the elements in one place. Next, store to memory
26418 // in fewer chunks.
26419 if (St->isTruncatingStore() && VT.isVector()) {
26420 // Check if we can detect an AVG pattern from the truncation. If yes,
26421 // replace the trunc store by a normal store with the result of X86ISD::AVG
26424 detectAVGPattern(St->getValue(), St->getMemoryVT(), DAG, Subtarget, dl);
26426 return DAG.getStore(St->getChain(), dl, Avg, St->getBasePtr(),
26427 St->getPointerInfo(), St->isVolatile(),
26428 St->isNonTemporal(), St->getAlignment());
26430 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26431 unsigned NumElems = VT.getVectorNumElements();
26432 assert(StVT != VT && "Cannot truncate to the same type");
26433 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
26434 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
26436 // The truncating store is legal in some cases. For example
26437 // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
26438 // are designated for truncate store.
26439 // In this case we don't need any further transformations.
26440 if (TLI.isTruncStoreLegal(VT, StVT))
26443 // From, To sizes and ElemCount must be pow of two
26444 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
26445 // We are going to use the original vector elt for storing.
26446 // Accumulated smaller vector elements must be a multiple of the store size.
26447 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
26449 unsigned SizeRatio = FromSz / ToSz;
26451 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
26453 // Create a type on which we perform the shuffle
26454 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
26455 StVT.getScalarType(), NumElems*SizeRatio);
26457 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
26459 SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
26460 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
26461 for (unsigned i = 0; i != NumElems; ++i)
26462 ShuffleVec[i] = i * SizeRatio;
26464 // Can't shuffle using an illegal type.
26465 if (!TLI.isTypeLegal(WideVecVT))
26468 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
26469 DAG.getUNDEF(WideVecVT),
26471 // At this point all of the data is stored at the bottom of the
26472 // register. We now need to save it to mem.
26474 // Find the largest store unit
26475 MVT StoreType = MVT::i8;
26476 for (MVT Tp : MVT::integer_valuetypes()) {
26477 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
26481 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
26482 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
26483 (64 <= NumElems * ToSz))
26484 StoreType = MVT::f64;
26486 // Bitcast the original vector into a vector of store-size units
26487 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
26488 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
26489 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
26490 SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
26491 SmallVector<SDValue, 8> Chains;
26492 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
26493 TLI.getPointerTy(DAG.getDataLayout()));
26494 SDValue Ptr = St->getBasePtr();
26496 // Perform one or more big stores into memory.
26497 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
26498 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
26499 StoreType, ShuffWide,
26500 DAG.getIntPtrConstant(i, dl));
26501 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
26502 St->getPointerInfo(), St->isVolatile(),
26503 St->isNonTemporal(), St->getAlignment());
26504 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
26505 Chains.push_back(Ch);
26508 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
26511 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
26512 // the FP state in cases where an emms may be missing.
26513 // A preferable solution to the general problem is to figure out the right
26514 // places to insert EMMS. This qualifies as a quick hack.
26516 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
26517 if (VT.getSizeInBits() != 64)
26520 const Function *F = DAG.getMachineFunction().getFunction();
26521 bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
26523 !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
26524 if ((VT.isVector() ||
26525 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
26526 isa<LoadSDNode>(St->getValue()) &&
26527 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
26528 St->getChain().hasOneUse() && !St->isVolatile()) {
26529 SDNode* LdVal = St->getValue().getNode();
26530 LoadSDNode *Ld = nullptr;
26531 int TokenFactorIndex = -1;
26532 SmallVector<SDValue, 8> Ops;
26533 SDNode* ChainVal = St->getChain().getNode();
26534 // Must be a store of a load. We currently handle two cases: the load
26535 // is a direct child, and it's under an intervening TokenFactor. It is
26536 // possible to dig deeper under nested TokenFactors.
26537 if (ChainVal == LdVal)
26538 Ld = cast<LoadSDNode>(St->getChain());
26539 else if (St->getValue().hasOneUse() &&
26540 ChainVal->getOpcode() == ISD::TokenFactor) {
26541 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
26542 if (ChainVal->getOperand(i).getNode() == LdVal) {
26543 TokenFactorIndex = i;
26544 Ld = cast<LoadSDNode>(St->getValue());
26546 Ops.push_back(ChainVal->getOperand(i));
26550 if (!Ld || !ISD::isNormalLoad(Ld))
26553 // If this is not the MMX case, i.e. we are just turning i64 load/store
26554 // into f64 load/store, avoid the transformation if there are multiple
26555 // uses of the loaded value.
26556 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
26561 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
26562 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
26564 if (Subtarget->is64Bit() || F64IsLegal) {
26565 MVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
26566 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
26567 Ld->getPointerInfo(), Ld->isVolatile(),
26568 Ld->isNonTemporal(), Ld->isInvariant(),
26569 Ld->getAlignment());
26570 SDValue NewChain = NewLd.getValue(1);
26571 if (TokenFactorIndex != -1) {
26572 Ops.push_back(NewChain);
26573 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
26575 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
26576 St->getPointerInfo(),
26577 St->isVolatile(), St->isNonTemporal(),
26578 St->getAlignment());
26581 // Otherwise, lower to two pairs of 32-bit loads / stores.
26582 SDValue LoAddr = Ld->getBasePtr();
26583 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
26584 DAG.getConstant(4, LdDL, MVT::i32));
26586 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
26587 Ld->getPointerInfo(),
26588 Ld->isVolatile(), Ld->isNonTemporal(),
26589 Ld->isInvariant(), Ld->getAlignment());
26590 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
26591 Ld->getPointerInfo().getWithOffset(4),
26592 Ld->isVolatile(), Ld->isNonTemporal(),
26594 MinAlign(Ld->getAlignment(), 4));
26596 SDValue NewChain = LoLd.getValue(1);
26597 if (TokenFactorIndex != -1) {
26598 Ops.push_back(LoLd);
26599 Ops.push_back(HiLd);
26600 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
26603 LoAddr = St->getBasePtr();
26604 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
26605 DAG.getConstant(4, StDL, MVT::i32));
26607 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
26608 St->getPointerInfo(),
26609 St->isVolatile(), St->isNonTemporal(),
26610 St->getAlignment());
26611 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
26612 St->getPointerInfo().getWithOffset(4),
26614 St->isNonTemporal(),
26615 MinAlign(St->getAlignment(), 4));
26616 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
26619 // This is similar to the above case, but here we handle a scalar 64-bit
26620 // integer store that is extracted from a vector on a 32-bit target.
26621 // If we have SSE2, then we can treat it like a floating-point double
26622 // to get past legalization. The execution dependencies fixup pass will
26623 // choose the optimal machine instruction for the store if this really is
26624 // an integer or v2f32 rather than an f64.
26625 if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
26626 St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
26627 SDValue OldExtract = St->getOperand(1);
26628 SDValue ExtOp0 = OldExtract.getOperand(0);
26629 unsigned VecSize = ExtOp0.getValueSizeInBits();
26630 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
26631 SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
26632 SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
26633 BitCast, OldExtract.getOperand(1));
26634 return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
26635 St->getPointerInfo(), St->isVolatile(),
26636 St->isNonTemporal(), St->getAlignment());
26642 /// Return 'true' if this vector operation is "horizontal"
26643 /// and return the operands for the horizontal operation in LHS and RHS. A
26644 /// horizontal operation performs the binary operation on successive elements
26645 /// of its first operand, then on successive elements of its second operand,
26646 /// returning the resulting values in a vector. For example, if
26647 /// A = < float a0, float a1, float a2, float a3 >
26649 /// B = < float b0, float b1, float b2, float b3 >
26650 /// then the result of doing a horizontal operation on A and B is
26651 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
26652 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
26653 /// A horizontal-op B, for some already available A and B, and if so then LHS is
26654 /// set to A, RHS to B, and the routine returns 'true'.
26655 /// Note that the binary operation should have the property that if one of the
26656 /// operands is UNDEF then the result is UNDEF.
26657 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
26658 // Look for the following pattern: if
26659 // A = < float a0, float a1, float a2, float a3 >
26660 // B = < float b0, float b1, float b2, float b3 >
26662 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
26663 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
26664 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
26665 // which is A horizontal-op B.
26667 // At least one of the operands should be a vector shuffle.
26668 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
26669 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
26672 MVT VT = LHS.getSimpleValueType();
26674 assert((VT.is128BitVector() || VT.is256BitVector()) &&
26675 "Unsupported vector type for horizontal add/sub");
26677 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
26678 // operate independently on 128-bit lanes.
26679 unsigned NumElts = VT.getVectorNumElements();
26680 unsigned NumLanes = VT.getSizeInBits()/128;
26681 unsigned NumLaneElts = NumElts / NumLanes;
26682 assert((NumLaneElts % 2 == 0) &&
26683 "Vector type should have an even number of elements in each lane");
26684 unsigned HalfLaneElts = NumLaneElts/2;
26686 // View LHS in the form
26687 // LHS = VECTOR_SHUFFLE A, B, LMask
26688 // If LHS is not a shuffle then pretend it is the shuffle
26689 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
26690 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
26693 SmallVector<int, 16> LMask(NumElts);
26694 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
26695 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
26696 A = LHS.getOperand(0);
26697 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
26698 B = LHS.getOperand(1);
26699 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
26700 std::copy(Mask.begin(), Mask.end(), LMask.begin());
26702 if (LHS.getOpcode() != ISD::UNDEF)
26704 for (unsigned i = 0; i != NumElts; ++i)
26708 // Likewise, view RHS in the form
26709 // RHS = VECTOR_SHUFFLE C, D, RMask
26711 SmallVector<int, 16> RMask(NumElts);
26712 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
26713 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
26714 C = RHS.getOperand(0);
26715 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
26716 D = RHS.getOperand(1);
26717 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
26718 std::copy(Mask.begin(), Mask.end(), RMask.begin());
26720 if (RHS.getOpcode() != ISD::UNDEF)
26722 for (unsigned i = 0; i != NumElts; ++i)
26726 // Check that the shuffles are both shuffling the same vectors.
26727 if (!(A == C && B == D) && !(A == D && B == C))
26730 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
26731 if (!A.getNode() && !B.getNode())
26734 // If A and B occur in reverse order in RHS, then "swap" them (which means
26735 // rewriting the mask).
26737 ShuffleVectorSDNode::commuteMask(RMask);
26739 // At this point LHS and RHS are equivalent to
26740 // LHS = VECTOR_SHUFFLE A, B, LMask
26741 // RHS = VECTOR_SHUFFLE A, B, RMask
26742 // Check that the masks correspond to performing a horizontal operation.
26743 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
26744 for (unsigned i = 0; i != NumLaneElts; ++i) {
26745 int LIdx = LMask[i+l], RIdx = RMask[i+l];
26747 // Ignore any UNDEF components.
26748 if (LIdx < 0 || RIdx < 0 ||
26749 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
26750 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
26753 // Check that successive elements are being operated on. If not, this is
26754 // not a horizontal operation.
26755 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
26756 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
26757 if (!(LIdx == Index && RIdx == Index + 1) &&
26758 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
26763 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
26764 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
26768 /// Do target-specific dag combines on floating point adds.
26769 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
26770 const X86Subtarget *Subtarget) {
26771 EVT VT = N->getValueType(0);
26772 SDValue LHS = N->getOperand(0);
26773 SDValue RHS = N->getOperand(1);
26775 // Try to synthesize horizontal adds from adds of shuffles.
26776 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
26777 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
26778 isHorizontalBinOp(LHS, RHS, true))
26779 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
26783 /// Do target-specific dag combines on floating point subs.
26784 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
26785 const X86Subtarget *Subtarget) {
26786 EVT VT = N->getValueType(0);
26787 SDValue LHS = N->getOperand(0);
26788 SDValue RHS = N->getOperand(1);
26790 // Try to synthesize horizontal subs from subs of shuffles.
26791 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
26792 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
26793 isHorizontalBinOp(LHS, RHS, false))
26794 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
26798 /// Truncate a group of v4i32 into v16i8/v8i16 using X86ISD::PACKUS.
26800 combineVectorTruncationWithPACKUS(SDNode *N, SelectionDAG &DAG,
26801 SmallVector<SDValue, 8> &Regs) {
26802 assert(Regs.size() > 0 && (Regs[0].getValueType() == MVT::v4i32 ||
26803 Regs[0].getValueType() == MVT::v2i64));
26804 EVT OutVT = N->getValueType(0);
26805 EVT OutSVT = OutVT.getVectorElementType();
26806 EVT InVT = Regs[0].getValueType();
26807 EVT InSVT = InVT.getVectorElementType();
26810 // First, use mask to unset all bits that won't appear in the result.
26811 assert((OutSVT == MVT::i8 || OutSVT == MVT::i16) &&
26812 "OutSVT can only be either i8 or i16.");
26814 DAG.getConstant(OutSVT == MVT::i8 ? 0xFF : 0xFFFF, DL, InSVT);
26815 SDValue MaskVec = DAG.getNode(
26816 ISD::BUILD_VECTOR, DL, InVT,
26817 SmallVector<SDValue, 8>(InVT.getVectorNumElements(), MaskVal));
26818 for (auto &Reg : Regs)
26819 Reg = DAG.getNode(ISD::AND, DL, InVT, MaskVec, Reg);
26821 MVT UnpackedVT, PackedVT;
26822 if (OutSVT == MVT::i8) {
26823 UnpackedVT = MVT::v8i16;
26824 PackedVT = MVT::v16i8;
26826 UnpackedVT = MVT::v4i32;
26827 PackedVT = MVT::v8i16;
26830 // In each iteration, truncate the type by a half size.
26831 auto RegNum = Regs.size();
26832 for (unsigned j = 1, e = InSVT.getSizeInBits() / OutSVT.getSizeInBits();
26833 j < e; j *= 2, RegNum /= 2) {
26834 for (unsigned i = 0; i < RegNum; i++)
26835 Regs[i] = DAG.getNode(ISD::BITCAST, DL, UnpackedVT, Regs[i]);
26836 for (unsigned i = 0; i < RegNum / 2; i++)
26837 Regs[i] = DAG.getNode(X86ISD::PACKUS, DL, PackedVT, Regs[i * 2],
26841 // If the type of the result is v8i8, we need do one more X86ISD::PACKUS, and
26842 // then extract a subvector as the result since v8i8 is not a legal type.
26843 if (OutVT == MVT::v8i8) {
26844 Regs[0] = DAG.getNode(X86ISD::PACKUS, DL, PackedVT, Regs[0], Regs[0]);
26845 Regs[0] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, Regs[0],
26846 DAG.getIntPtrConstant(0, DL));
26848 } else if (RegNum > 1) {
26849 Regs.resize(RegNum);
26850 return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Regs);
26855 /// Truncate a group of v4i32 into v8i16 using X86ISD::PACKSS.
26857 combineVectorTruncationWithPACKSS(SDNode *N, SelectionDAG &DAG,
26858 SmallVector<SDValue, 8> &Regs) {
26859 assert(Regs.size() > 0 && Regs[0].getValueType() == MVT::v4i32);
26860 EVT OutVT = N->getValueType(0);
26863 // Shift left by 16 bits, then arithmetic-shift right by 16 bits.
26864 SDValue ShAmt = DAG.getConstant(16, DL, MVT::i32);
26865 for (auto &Reg : Regs) {
26866 Reg = getTargetVShiftNode(X86ISD::VSHLI, DL, MVT::v4i32, Reg, ShAmt, DAG);
26867 Reg = getTargetVShiftNode(X86ISD::VSRAI, DL, MVT::v4i32, Reg, ShAmt, DAG);
26870 for (unsigned i = 0, e = Regs.size() / 2; i < e; i++)
26871 Regs[i] = DAG.getNode(X86ISD::PACKSS, DL, MVT::v8i16, Regs[i * 2],
26874 if (Regs.size() > 2) {
26875 Regs.resize(Regs.size() / 2);
26876 return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Regs);
26881 /// This function transforms truncation from vXi32/vXi64 to vXi8/vXi16 into
26882 /// X86ISD::PACKUS/X86ISD::PACKSS operations. We do it here because after type
26883 /// legalization the truncation will be translated into a BUILD_VECTOR with each
26884 /// element that is extracted from a vector and then truncated, and it is
26885 /// diffcult to do this optimization based on them.
26886 static SDValue combineVectorTruncation(SDNode *N, SelectionDAG &DAG,
26887 const X86Subtarget *Subtarget) {
26888 EVT OutVT = N->getValueType(0);
26889 if (!OutVT.isVector())
26892 SDValue In = N->getOperand(0);
26893 if (!In.getValueType().isSimple())
26896 EVT InVT = In.getValueType();
26897 unsigned NumElems = OutVT.getVectorNumElements();
26899 // TODO: On AVX2, the behavior of X86ISD::PACKUS is different from that on
26900 // SSE2, and we need to take care of it specially.
26901 // AVX512 provides vpmovdb.
26902 if (!Subtarget->hasSSE2() || Subtarget->hasAVX2())
26905 EVT OutSVT = OutVT.getVectorElementType();
26906 EVT InSVT = InVT.getVectorElementType();
26907 if (!((InSVT == MVT::i32 || InSVT == MVT::i64) &&
26908 (OutSVT == MVT::i8 || OutSVT == MVT::i16) && isPowerOf2_32(NumElems) &&
26912 // SSSE3's pshufb results in less instructions in the cases below.
26913 if (Subtarget->hasSSSE3() && NumElems == 8 &&
26914 ((OutSVT == MVT::i8 && InSVT != MVT::i64) ||
26915 (InSVT == MVT::i32 && OutSVT == MVT::i16)))
26920 // Split a long vector into vectors of legal type.
26921 unsigned RegNum = InVT.getSizeInBits() / 128;
26922 SmallVector<SDValue, 8> SubVec(RegNum);
26923 if (InSVT == MVT::i32) {
26924 for (unsigned i = 0; i < RegNum; i++)
26925 SubVec[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
26926 DAG.getIntPtrConstant(i * 4, DL));
26928 for (unsigned i = 0; i < RegNum; i++)
26929 SubVec[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
26930 DAG.getIntPtrConstant(i * 2, DL));
26933 // SSE2 provides PACKUS for only 2 x v8i16 -> v16i8 and SSE4.1 provides PAKCUS
26934 // for 2 x v4i32 -> v8i16. For SSSE3 and below, we need to use PACKSS to
26935 // truncate 2 x v4i32 to v8i16.
26936 if (Subtarget->hasSSE41() || OutSVT == MVT::i8)
26937 return combineVectorTruncationWithPACKUS(N, DAG, SubVec);
26938 else if (InSVT == MVT::i32)
26939 return combineVectorTruncationWithPACKSS(N, DAG, SubVec);
26944 static SDValue PerformTRUNCATECombine(SDNode *N, SelectionDAG &DAG,
26945 const X86Subtarget *Subtarget) {
26946 // Try to detect AVG pattern first.
26947 SDValue Avg = detectAVGPattern(N->getOperand(0), N->getValueType(0), DAG,
26948 Subtarget, SDLoc(N));
26952 return combineVectorTruncation(N, DAG, Subtarget);
26955 /// Do target-specific dag combines on floating point negations.
26956 static SDValue PerformFNEGCombine(SDNode *N, SelectionDAG &DAG,
26957 const X86Subtarget *Subtarget) {
26958 EVT VT = N->getValueType(0);
26959 EVT SVT = VT.getScalarType();
26960 SDValue Arg = N->getOperand(0);
26963 // Let legalize expand this if it isn't a legal type yet.
26964 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
26967 // If we're negating a FMUL node on a target with FMA, then we can avoid the
26968 // use of a constant by performing (-0 - A*B) instead.
26969 // FIXME: Check rounding control flags as well once it becomes available.
26970 if (Arg.getOpcode() == ISD::FMUL && (SVT == MVT::f32 || SVT == MVT::f64) &&
26971 Arg->getFlags()->hasNoSignedZeros() && Subtarget->hasAnyFMA()) {
26972 SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
26973 return DAG.getNode(X86ISD::FNMSUB, DL, VT, Arg.getOperand(0),
26974 Arg.getOperand(1), Zero);
26977 // If we're negating a FMA node, then we can adjust the
26978 // instruction to include the extra negation.
26979 if (Arg.hasOneUse()) {
26980 switch (Arg.getOpcode()) {
26981 case X86ISD::FMADD:
26982 return DAG.getNode(X86ISD::FNMSUB, DL, VT, Arg.getOperand(0),
26983 Arg.getOperand(1), Arg.getOperand(2));
26984 case X86ISD::FMSUB:
26985 return DAG.getNode(X86ISD::FNMADD, DL, VT, Arg.getOperand(0),
26986 Arg.getOperand(1), Arg.getOperand(2));
26987 case X86ISD::FNMADD:
26988 return DAG.getNode(X86ISD::FMSUB, DL, VT, Arg.getOperand(0),
26989 Arg.getOperand(1), Arg.getOperand(2));
26990 case X86ISD::FNMSUB:
26991 return DAG.getNode(X86ISD::FMADD, DL, VT, Arg.getOperand(0),
26992 Arg.getOperand(1), Arg.getOperand(2));
26998 static SDValue lowerX86FPLogicOp(SDNode *N, SelectionDAG &DAG,
26999 const X86Subtarget *Subtarget) {
27000 EVT VT = N->getValueType(0);
27001 if (VT.is512BitVector() && !Subtarget->hasDQI()) {
27002 // VXORPS, VORPS, VANDPS, VANDNPS are supported only under DQ extention.
27003 // These logic operations may be executed in the integer domain.
27005 MVT IntScalar = MVT::getIntegerVT(VT.getScalarSizeInBits());
27006 MVT IntVT = MVT::getVectorVT(IntScalar, VT.getVectorNumElements());
27008 SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(0));
27009 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(1));
27010 unsigned IntOpcode = 0;
27011 switch (N->getOpcode()) {
27012 default: llvm_unreachable("Unexpected FP logic op");
27013 case X86ISD::FOR: IntOpcode = ISD::OR; break;
27014 case X86ISD::FXOR: IntOpcode = ISD::XOR; break;
27015 case X86ISD::FAND: IntOpcode = ISD::AND; break;
27016 case X86ISD::FANDN: IntOpcode = X86ISD::ANDNP; break;
27018 SDValue IntOp = DAG.getNode(IntOpcode, dl, IntVT, Op0, Op1);
27019 return DAG.getNode(ISD::BITCAST, dl, VT, IntOp);
27023 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
27024 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG,
27025 const X86Subtarget *Subtarget) {
27026 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
27028 // F[X]OR(0.0, x) -> x
27029 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
27030 if (C->getValueAPF().isPosZero())
27031 return N->getOperand(1);
27033 // F[X]OR(x, 0.0) -> x
27034 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
27035 if (C->getValueAPF().isPosZero())
27036 return N->getOperand(0);
27038 return lowerX86FPLogicOp(N, DAG, Subtarget);
27041 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
27042 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
27043 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
27045 // Only perform optimizations if UnsafeMath is used.
27046 if (!DAG.getTarget().Options.UnsafeFPMath)
27049 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
27050 // into FMINC and FMAXC, which are Commutative operations.
27051 unsigned NewOp = 0;
27052 switch (N->getOpcode()) {
27053 default: llvm_unreachable("unknown opcode");
27054 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
27055 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
27058 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
27059 N->getOperand(0), N->getOperand(1));
27062 static SDValue performFMinNumFMaxNumCombine(SDNode *N, SelectionDAG &DAG,
27063 const X86Subtarget *Subtarget) {
27064 if (Subtarget->useSoftFloat())
27067 // TODO: Check for global or instruction-level "nnan". In that case, we
27068 // should be able to lower to FMAX/FMIN alone.
27069 // TODO: If an operand is already known to be a NaN or not a NaN, this
27070 // should be an optional swap and FMAX/FMIN.
27072 EVT VT = N->getValueType(0);
27073 if (!((Subtarget->hasSSE1() && (VT == MVT::f32 || VT == MVT::v4f32)) ||
27074 (Subtarget->hasSSE2() && (VT == MVT::f64 || VT == MVT::v2f64)) ||
27075 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))))
27078 // This takes at least 3 instructions, so favor a library call when operating
27079 // on a scalar and minimizing code size.
27080 if (!VT.isVector() && DAG.getMachineFunction().getFunction()->optForMinSize())
27083 SDValue Op0 = N->getOperand(0);
27084 SDValue Op1 = N->getOperand(1);
27086 EVT SetCCType = DAG.getTargetLoweringInfo().getSetCCResultType(
27087 DAG.getDataLayout(), *DAG.getContext(), VT);
27089 // There are 4 possibilities involving NaN inputs, and these are the required
27093 // ----------------
27094 // Num | Max | Op0 |
27095 // Op0 ----------------
27096 // NaN | Op1 | NaN |
27097 // ----------------
27099 // The SSE FP max/min instructions were not designed for this case, but rather
27101 // Min = Op1 < Op0 ? Op1 : Op0
27102 // Max = Op1 > Op0 ? Op1 : Op0
27104 // So they always return Op0 if either input is a NaN. However, we can still
27105 // use those instructions for fmaxnum by selecting away a NaN input.
27107 // If either operand is NaN, the 2nd source operand (Op0) is passed through.
27108 auto MinMaxOp = N->getOpcode() == ISD::FMAXNUM ? X86ISD::FMAX : X86ISD::FMIN;
27109 SDValue MinOrMax = DAG.getNode(MinMaxOp, DL, VT, Op1, Op0);
27110 SDValue IsOp0Nan = DAG.getSetCC(DL, SetCCType , Op0, Op0, ISD::SETUO);
27112 // If Op0 is a NaN, select Op1. Otherwise, select the max. If both operands
27113 // are NaN, the NaN value of Op1 is the result.
27114 auto SelectOpcode = VT.isVector() ? ISD::VSELECT : ISD::SELECT;
27115 return DAG.getNode(SelectOpcode, DL, VT, IsOp0Nan, Op1, MinOrMax);
27118 /// Do target-specific dag combines on X86ISD::FAND nodes.
27119 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG,
27120 const X86Subtarget *Subtarget) {
27121 // FAND(0.0, x) -> 0.0
27122 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
27123 if (C->getValueAPF().isPosZero())
27124 return N->getOperand(0);
27126 // FAND(x, 0.0) -> 0.0
27127 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
27128 if (C->getValueAPF().isPosZero())
27129 return N->getOperand(1);
27131 return lowerX86FPLogicOp(N, DAG, Subtarget);
27134 /// Do target-specific dag combines on X86ISD::FANDN nodes
27135 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG,
27136 const X86Subtarget *Subtarget) {
27137 // FANDN(0.0, x) -> x
27138 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
27139 if (C->getValueAPF().isPosZero())
27140 return N->getOperand(1);
27142 // FANDN(x, 0.0) -> 0.0
27143 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
27144 if (C->getValueAPF().isPosZero())
27145 return N->getOperand(1);
27147 return lowerX86FPLogicOp(N, DAG, Subtarget);
27150 static SDValue PerformBTCombine(SDNode *N,
27152 TargetLowering::DAGCombinerInfo &DCI) {
27153 // BT ignores high bits in the bit index operand.
27154 SDValue Op1 = N->getOperand(1);
27155 if (Op1.hasOneUse()) {
27156 unsigned BitWidth = Op1.getValueSizeInBits();
27157 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
27158 APInt KnownZero, KnownOne;
27159 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
27160 !DCI.isBeforeLegalizeOps());
27161 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
27162 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
27163 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
27164 DCI.CommitTargetLoweringOpt(TLO);
27169 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
27170 SDValue Op = N->getOperand(0);
27171 if (Op.getOpcode() == ISD::BITCAST)
27172 Op = Op.getOperand(0);
27173 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
27174 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
27175 VT.getVectorElementType().getSizeInBits() ==
27176 OpVT.getVectorElementType().getSizeInBits()) {
27177 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
27182 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
27183 const X86Subtarget *Subtarget) {
27184 EVT VT = N->getValueType(0);
27185 if (!VT.isVector())
27188 SDValue N0 = N->getOperand(0);
27189 SDValue N1 = N->getOperand(1);
27190 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
27193 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
27194 // both SSE and AVX2 since there is no sign-extended shift right
27195 // operation on a vector with 64-bit elements.
27196 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
27197 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
27198 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
27199 N0.getOpcode() == ISD::SIGN_EXTEND)) {
27200 SDValue N00 = N0.getOperand(0);
27202 // EXTLOAD has a better solution on AVX2,
27203 // it may be replaced with X86ISD::VSEXT node.
27204 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
27205 if (!ISD::isNormalLoad(N00.getNode()))
27208 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
27209 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
27211 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
27217 /// sext(add_nsw(x, C)) --> add(sext(x), C_sext)
27218 /// Promoting a sign extension ahead of an 'add nsw' exposes opportunities
27219 /// to combine math ops, use an LEA, or use a complex addressing mode. This can
27220 /// eliminate extend, add, and shift instructions.
27221 static SDValue promoteSextBeforeAddNSW(SDNode *Sext, SelectionDAG &DAG,
27222 const X86Subtarget *Subtarget) {
27223 // TODO: This should be valid for other integer types.
27224 EVT VT = Sext->getValueType(0);
27225 if (VT != MVT::i64)
27228 // We need an 'add nsw' feeding into the 'sext'.
27229 SDValue Add = Sext->getOperand(0);
27230 if (Add.getOpcode() != ISD::ADD || !Add->getFlags()->hasNoSignedWrap())
27233 // Having a constant operand to the 'add' ensures that we are not increasing
27234 // the instruction count because the constant is extended for free below.
27235 // A constant operand can also become the displacement field of an LEA.
27236 auto *AddOp1 = dyn_cast<ConstantSDNode>(Add.getOperand(1));
27240 // Don't make the 'add' bigger if there's no hope of combining it with some
27241 // other 'add' or 'shl' instruction.
27242 // TODO: It may be profitable to generate simpler LEA instructions in place
27243 // of single 'add' instructions, but the cost model for selecting an LEA
27244 // currently has a high threshold.
27245 bool HasLEAPotential = false;
27246 for (auto *User : Sext->uses()) {
27247 if (User->getOpcode() == ISD::ADD || User->getOpcode() == ISD::SHL) {
27248 HasLEAPotential = true;
27252 if (!HasLEAPotential)
27255 // Everything looks good, so pull the 'sext' ahead of the 'add'.
27256 int64_t AddConstant = AddOp1->getSExtValue();
27257 SDValue AddOp0 = Add.getOperand(0);
27258 SDValue NewSext = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(Sext), VT, AddOp0);
27259 SDValue NewConstant = DAG.getConstant(AddConstant, SDLoc(Add), VT);
27261 // The wider add is guaranteed to not wrap because both operands are
27264 Flags.setNoSignedWrap(true);
27265 return DAG.getNode(ISD::ADD, SDLoc(Add), VT, NewSext, NewConstant, &Flags);
27268 /// (i8,i32 {s/z}ext ({s/u}divrem (i8 x, i8 y)) ->
27269 /// (i8,i32 ({s/u}divrem_sext_hreg (i8 x, i8 y)
27270 /// This exposes the {s/z}ext to the sdivrem lowering, so that it directly
27271 /// extends from AH (which we otherwise need to do contortions to access).
27272 static SDValue getDivRem8(SDNode *N, SelectionDAG &DAG) {
27273 SDValue N0 = N->getOperand(0);
27274 auto OpcodeN = N->getOpcode();
27275 auto OpcodeN0 = N0.getOpcode();
27276 if (!((OpcodeN == ISD::SIGN_EXTEND && OpcodeN0 == ISD::SDIVREM) ||
27277 (OpcodeN == ISD::ZERO_EXTEND && OpcodeN0 == ISD::UDIVREM)))
27280 EVT VT = N->getValueType(0);
27281 EVT InVT = N0.getValueType();
27282 if (N0.getResNo() != 1 || InVT != MVT::i8 || VT != MVT::i32)
27285 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
27286 auto DivRemOpcode = OpcodeN0 == ISD::SDIVREM ? X86ISD::SDIVREM8_SEXT_HREG
27287 : X86ISD::UDIVREM8_ZEXT_HREG;
27288 SDValue R = DAG.getNode(DivRemOpcode, SDLoc(N), NodeTys, N0.getOperand(0),
27290 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
27291 return R.getValue(1);
27294 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
27295 TargetLowering::DAGCombinerInfo &DCI,
27296 const X86Subtarget *Subtarget) {
27297 SDValue N0 = N->getOperand(0);
27298 EVT VT = N->getValueType(0);
27299 EVT SVT = VT.getScalarType();
27300 EVT InVT = N0.getValueType();
27301 EVT InSVT = InVT.getScalarType();
27304 if (SDValue DivRem8 = getDivRem8(N, DAG))
27307 if (!DCI.isBeforeLegalizeOps()) {
27308 if (InVT == MVT::i1) {
27309 SDValue Zero = DAG.getConstant(0, DL, VT);
27311 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
27312 return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
27317 if (VT.isVector() && Subtarget->hasSSE2()) {
27318 auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
27319 EVT InVT = N.getValueType();
27320 EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
27321 Size / InVT.getScalarSizeInBits());
27322 SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
27323 DAG.getUNDEF(InVT));
27325 return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
27328 // If target-size is less than 128-bits, extend to a type that would extend
27329 // to 128 bits, extend that and extract the original target vector.
27330 if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
27331 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
27332 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
27333 unsigned Scale = 128 / VT.getSizeInBits();
27335 EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
27336 SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
27337 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
27338 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
27339 DAG.getIntPtrConstant(0, DL));
27342 // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
27343 // which ensures lowering to X86ISD::VSEXT (pmovsx*).
27344 if (VT.getSizeInBits() == 128 &&
27345 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
27346 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
27347 SDValue ExOp = ExtendVecSize(DL, N0, 128);
27348 return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
27351 // On pre-AVX2 targets, split into 128-bit nodes of
27352 // ISD::SIGN_EXTEND_VECTOR_INREG.
27353 if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
27354 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
27355 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
27356 unsigned NumVecs = VT.getSizeInBits() / 128;
27357 unsigned NumSubElts = 128 / SVT.getSizeInBits();
27358 EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
27359 EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
27361 SmallVector<SDValue, 8> Opnds;
27362 for (unsigned i = 0, Offset = 0; i != NumVecs;
27363 ++i, Offset += NumSubElts) {
27364 SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
27365 DAG.getIntPtrConstant(Offset, DL));
27366 SrcVec = ExtendVecSize(DL, SrcVec, 128);
27367 SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
27368 Opnds.push_back(SrcVec);
27370 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
27374 if (Subtarget->hasAVX() && VT.is256BitVector())
27375 if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
27378 if (SDValue NewAdd = promoteSextBeforeAddNSW(N, DAG, Subtarget))
27384 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
27385 const X86Subtarget* Subtarget) {
27387 EVT VT = N->getValueType(0);
27389 // Let legalize expand this if it isn't a legal type yet.
27390 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
27393 EVT ScalarVT = VT.getScalarType();
27394 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) || !Subtarget->hasAnyFMA())
27397 SDValue A = N->getOperand(0);
27398 SDValue B = N->getOperand(1);
27399 SDValue C = N->getOperand(2);
27401 bool NegA = (A.getOpcode() == ISD::FNEG);
27402 bool NegB = (B.getOpcode() == ISD::FNEG);
27403 bool NegC = (C.getOpcode() == ISD::FNEG);
27405 // Negative multiplication when NegA xor NegB
27406 bool NegMul = (NegA != NegB);
27408 A = A.getOperand(0);
27410 B = B.getOperand(0);
27412 C = C.getOperand(0);
27416 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
27418 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
27420 return DAG.getNode(Opcode, dl, VT, A, B, C);
27423 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
27424 TargetLowering::DAGCombinerInfo &DCI,
27425 const X86Subtarget *Subtarget) {
27426 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
27427 // (and (i32 x86isd::setcc_carry), 1)
27428 // This eliminates the zext. This transformation is necessary because
27429 // ISD::SETCC is always legalized to i8.
27431 SDValue N0 = N->getOperand(0);
27432 EVT VT = N->getValueType(0);
27434 if (N0.getOpcode() == ISD::AND &&
27436 N0.getOperand(0).hasOneUse()) {
27437 SDValue N00 = N0.getOperand(0);
27438 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
27439 if (!isOneConstant(N0.getOperand(1)))
27441 return DAG.getNode(ISD::AND, dl, VT,
27442 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
27443 N00.getOperand(0), N00.getOperand(1)),
27444 DAG.getConstant(1, dl, VT));
27448 if (N0.getOpcode() == ISD::TRUNCATE &&
27450 N0.getOperand(0).hasOneUse()) {
27451 SDValue N00 = N0.getOperand(0);
27452 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
27453 return DAG.getNode(ISD::AND, dl, VT,
27454 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
27455 N00.getOperand(0), N00.getOperand(1)),
27456 DAG.getConstant(1, dl, VT));
27460 if (VT.is256BitVector())
27461 if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
27464 if (SDValue DivRem8 = getDivRem8(N, DAG))
27470 // Optimize x == -y --> x+y == 0
27471 // x != -y --> x+y != 0
27472 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
27473 const X86Subtarget* Subtarget) {
27474 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
27475 SDValue LHS = N->getOperand(0);
27476 SDValue RHS = N->getOperand(1);
27477 EVT VT = N->getValueType(0);
27480 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
27481 if (isNullConstant(LHS.getOperand(0)) && LHS.hasOneUse()) {
27482 SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
27483 LHS.getOperand(1));
27484 return DAG.getSetCC(DL, N->getValueType(0), addV,
27485 DAG.getConstant(0, DL, addV.getValueType()), CC);
27487 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
27488 if (isNullConstant(RHS.getOperand(0)) && RHS.hasOneUse()) {
27489 SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
27490 RHS.getOperand(1));
27491 return DAG.getSetCC(DL, N->getValueType(0), addV,
27492 DAG.getConstant(0, DL, addV.getValueType()), CC);
27495 if (VT.getScalarType() == MVT::i1 &&
27496 (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
27498 (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
27499 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
27500 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
27502 if (!IsSEXT0 || !IsVZero1) {
27503 // Swap the operands and update the condition code.
27504 std::swap(LHS, RHS);
27505 CC = ISD::getSetCCSwappedOperands(CC);
27507 IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
27508 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
27509 IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
27512 if (IsSEXT0 && IsVZero1) {
27513 assert(VT == LHS.getOperand(0).getValueType() &&
27514 "Uexpected operand type");
27515 if (CC == ISD::SETGT)
27516 return DAG.getConstant(0, DL, VT);
27517 if (CC == ISD::SETLE)
27518 return DAG.getConstant(1, DL, VT);
27519 if (CC == ISD::SETEQ || CC == ISD::SETGE)
27520 return DAG.getNOT(DL, LHS.getOperand(0), VT);
27522 assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
27523 "Unexpected condition code!");
27524 return LHS.getOperand(0);
27531 static SDValue PerformGatherScatterCombine(SDNode *N, SelectionDAG &DAG) {
27533 // Gather and Scatter instructions use k-registers for masks. The type of
27534 // the masks is v*i1. So the mask will be truncated anyway.
27535 // The SIGN_EXTEND_INREG my be dropped.
27536 SDValue Mask = N->getOperand(2);
27537 if (Mask.getOpcode() == ISD::SIGN_EXTEND_INREG) {
27538 SmallVector<SDValue, 5> NewOps(N->op_begin(), N->op_end());
27539 NewOps[2] = Mask.getOperand(0);
27540 DAG.UpdateNodeOperands(N, NewOps);
27545 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
27546 // as "sbb reg,reg", since it can be extended without zext and produces
27547 // an all-ones bit which is more useful than 0/1 in some cases.
27548 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
27551 return DAG.getNode(ISD::AND, DL, VT,
27552 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
27553 DAG.getConstant(X86::COND_B, DL, MVT::i8),
27555 DAG.getConstant(1, DL, VT));
27556 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
27557 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
27558 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
27559 DAG.getConstant(X86::COND_B, DL, MVT::i8),
27563 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
27564 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
27565 TargetLowering::DAGCombinerInfo &DCI,
27566 const X86Subtarget *Subtarget) {
27568 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
27569 SDValue EFLAGS = N->getOperand(1);
27571 if (CC == X86::COND_A) {
27572 // Try to convert COND_A into COND_B in an attempt to facilitate
27573 // materializing "setb reg".
27575 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
27576 // cannot take an immediate as its first operand.
27578 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
27579 EFLAGS.getValueType().isInteger() &&
27580 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
27581 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
27582 EFLAGS.getNode()->getVTList(),
27583 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
27584 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
27585 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
27589 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
27590 // a zext and produces an all-ones bit which is more useful than 0/1 in some
27592 if (CC == X86::COND_B)
27593 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
27595 if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
27596 SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
27597 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
27603 // Optimize branch condition evaluation.
27605 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
27606 TargetLowering::DAGCombinerInfo &DCI,
27607 const X86Subtarget *Subtarget) {
27609 SDValue Chain = N->getOperand(0);
27610 SDValue Dest = N->getOperand(1);
27611 SDValue EFLAGS = N->getOperand(3);
27612 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
27614 if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
27615 SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
27616 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
27623 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
27624 SelectionDAG &DAG) {
27625 // Take advantage of vector comparisons producing 0 or -1 in each lane to
27626 // optimize away operation when it's from a constant.
27628 // The general transformation is:
27629 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
27630 // AND(VECTOR_CMP(x,y), constant2)
27631 // constant2 = UNARYOP(constant)
27633 // Early exit if this isn't a vector operation, the operand of the
27634 // unary operation isn't a bitwise AND, or if the sizes of the operations
27635 // aren't the same.
27636 EVT VT = N->getValueType(0);
27637 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
27638 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
27639 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
27642 // Now check that the other operand of the AND is a constant. We could
27643 // make the transformation for non-constant splats as well, but it's unclear
27644 // that would be a benefit as it would not eliminate any operations, just
27645 // perform one more step in scalar code before moving to the vector unit.
27646 if (BuildVectorSDNode *BV =
27647 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
27648 // Bail out if the vector isn't a constant.
27649 if (!BV->isConstant())
27652 // Everything checks out. Build up the new and improved node.
27654 EVT IntVT = BV->getValueType(0);
27655 // Create a new constant of the appropriate type for the transformed
27657 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
27658 // The AND node needs bitcasts to/from an integer vector type around it.
27659 SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
27660 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
27661 N->getOperand(0)->getOperand(0), MaskConst);
27662 SDValue Res = DAG.getBitcast(VT, NewAnd);
27669 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
27670 const X86Subtarget *Subtarget) {
27671 SDValue Op0 = N->getOperand(0);
27672 EVT VT = N->getValueType(0);
27673 EVT InVT = Op0.getValueType();
27674 EVT InSVT = InVT.getScalarType();
27675 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
27677 // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
27678 // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
27679 if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
27681 EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
27682 InVT.getVectorNumElements());
27683 SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
27685 if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
27686 return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
27688 return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
27694 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
27695 const X86Subtarget *Subtarget) {
27696 // First try to optimize away the conversion entirely when it's
27697 // conditionally from a constant. Vectors only.
27698 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
27701 // Now move on to more general possibilities.
27702 SDValue Op0 = N->getOperand(0);
27703 EVT VT = N->getValueType(0);
27704 EVT InVT = Op0.getValueType();
27705 EVT InSVT = InVT.getScalarType();
27707 // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
27708 // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
27709 if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
27711 EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
27712 InVT.getVectorNumElements());
27713 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
27714 return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
27717 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
27718 // a 32-bit target where SSE doesn't support i64->FP operations.
27719 if (!Subtarget->useSoftFloat() && Op0.getOpcode() == ISD::LOAD) {
27720 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
27721 EVT LdVT = Ld->getValueType(0);
27723 // This transformation is not supported if the result type is f16
27724 if (VT == MVT::f16)
27727 if (!Ld->isVolatile() && !VT.isVector() &&
27728 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
27729 !Subtarget->is64Bit() && LdVT == MVT::i64) {
27730 SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
27731 SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
27732 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
27739 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
27740 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
27741 X86TargetLowering::DAGCombinerInfo &DCI) {
27742 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
27743 // the result is either zero or one (depending on the input carry bit).
27744 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
27745 if (X86::isZeroNode(N->getOperand(0)) &&
27746 X86::isZeroNode(N->getOperand(1)) &&
27747 // We don't have a good way to replace an EFLAGS use, so only do this when
27749 SDValue(N, 1).use_empty()) {
27751 EVT VT = N->getValueType(0);
27752 SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
27753 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
27754 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
27755 DAG.getConstant(X86::COND_B, DL,
27758 DAG.getConstant(1, DL, VT));
27759 return DCI.CombineTo(N, Res1, CarryOut);
27765 // fold (add Y, (sete X, 0)) -> adc 0, Y
27766 // (add Y, (setne X, 0)) -> sbb -1, Y
27767 // (sub (sete X, 0), Y) -> sbb 0, Y
27768 // (sub (setne X, 0), Y) -> adc -1, Y
27769 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
27772 // Look through ZExts.
27773 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
27774 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
27777 SDValue SetCC = Ext.getOperand(0);
27778 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
27781 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
27782 if (CC != X86::COND_E && CC != X86::COND_NE)
27785 SDValue Cmp = SetCC.getOperand(1);
27786 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
27787 !X86::isZeroNode(Cmp.getOperand(1)) ||
27788 !Cmp.getOperand(0).getValueType().isInteger())
27791 SDValue CmpOp0 = Cmp.getOperand(0);
27792 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
27793 DAG.getConstant(1, DL, CmpOp0.getValueType()));
27795 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
27796 if (CC == X86::COND_NE)
27797 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
27798 DL, OtherVal.getValueType(), OtherVal,
27799 DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
27801 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
27802 DL, OtherVal.getValueType(), OtherVal,
27803 DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
27806 /// PerformADDCombine - Do target-specific dag combines on integer adds.
27807 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
27808 const X86Subtarget *Subtarget) {
27809 EVT VT = N->getValueType(0);
27810 SDValue Op0 = N->getOperand(0);
27811 SDValue Op1 = N->getOperand(1);
27813 // Try to synthesize horizontal adds from adds of shuffles.
27814 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
27815 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
27816 isHorizontalBinOp(Op0, Op1, true))
27817 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
27819 return OptimizeConditionalInDecrement(N, DAG);
27822 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
27823 const X86Subtarget *Subtarget) {
27824 SDValue Op0 = N->getOperand(0);
27825 SDValue Op1 = N->getOperand(1);
27827 // X86 can't encode an immediate LHS of a sub. See if we can push the
27828 // negation into a preceding instruction.
27829 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
27830 // If the RHS of the sub is a XOR with one use and a constant, invert the
27831 // immediate. Then add one to the LHS of the sub so we can turn
27832 // X-Y -> X+~Y+1, saving one register.
27833 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
27834 isa<ConstantSDNode>(Op1.getOperand(1))) {
27835 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
27836 EVT VT = Op0.getValueType();
27837 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
27839 DAG.getConstant(~XorC, SDLoc(Op1), VT));
27840 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
27841 DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
27845 // Try to synthesize horizontal adds from adds of shuffles.
27846 EVT VT = N->getValueType(0);
27847 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
27848 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
27849 isHorizontalBinOp(Op0, Op1, true))
27850 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
27852 return OptimizeConditionalInDecrement(N, DAG);
27855 /// performVZEXTCombine - Performs build vector combines
27856 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
27857 TargetLowering::DAGCombinerInfo &DCI,
27858 const X86Subtarget *Subtarget) {
27860 MVT VT = N->getSimpleValueType(0);
27861 SDValue Op = N->getOperand(0);
27862 MVT OpVT = Op.getSimpleValueType();
27863 MVT OpEltVT = OpVT.getVectorElementType();
27864 unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
27866 // (vzext (bitcast (vzext (x)) -> (vzext x)
27868 while (V.getOpcode() == ISD::BITCAST)
27869 V = V.getOperand(0);
27871 if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
27872 MVT InnerVT = V.getSimpleValueType();
27873 MVT InnerEltVT = InnerVT.getVectorElementType();
27875 // If the element sizes match exactly, we can just do one larger vzext. This
27876 // is always an exact type match as vzext operates on integer types.
27877 if (OpEltVT == InnerEltVT) {
27878 assert(OpVT == InnerVT && "Types must match for vzext!");
27879 return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
27882 // The only other way we can combine them is if only a single element of the
27883 // inner vzext is used in the input to the outer vzext.
27884 if (InnerEltVT.getSizeInBits() < InputBits)
27887 // In this case, the inner vzext is completely dead because we're going to
27888 // only look at bits inside of the low element. Just do the outer vzext on
27889 // a bitcast of the input to the inner.
27890 return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
27893 // Check if we can bypass extracting and re-inserting an element of an input
27894 // vector. Essentially:
27895 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
27896 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
27897 V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
27898 V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
27899 SDValue ExtractedV = V.getOperand(0);
27900 SDValue OrigV = ExtractedV.getOperand(0);
27901 if (isNullConstant(ExtractedV.getOperand(1))) {
27902 MVT OrigVT = OrigV.getSimpleValueType();
27903 // Extract a subvector if necessary...
27904 if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
27905 int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
27906 OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
27907 OrigVT.getVectorNumElements() / Ratio);
27908 OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
27909 DAG.getIntPtrConstant(0, DL));
27911 Op = DAG.getBitcast(OpVT, OrigV);
27912 return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
27919 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
27920 DAGCombinerInfo &DCI) const {
27921 SelectionDAG &DAG = DCI.DAG;
27922 switch (N->getOpcode()) {
27924 case ISD::EXTRACT_VECTOR_ELT:
27925 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
27928 case X86ISD::SHRUNKBLEND:
27929 return PerformSELECTCombine(N, DAG, DCI, Subtarget);
27930 case ISD::BITCAST: return PerformBITCASTCombine(N, DAG, Subtarget);
27931 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
27932 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
27933 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
27934 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
27935 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
27938 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
27939 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
27940 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
27941 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
27942 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
27943 case ISD::MLOAD: return PerformMLOADCombine(N, DAG, DCI, Subtarget);
27944 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
27945 case ISD::MSTORE: return PerformMSTORECombine(N, DAG, Subtarget);
27946 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
27947 case ISD::UINT_TO_FP: return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
27948 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
27949 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
27950 case ISD::FNEG: return PerformFNEGCombine(N, DAG, Subtarget);
27951 case ISD::TRUNCATE: return PerformTRUNCATECombine(N, DAG, Subtarget);
27953 case X86ISD::FOR: return PerformFORCombine(N, DAG, Subtarget);
27955 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
27957 case ISD::FMAXNUM: return performFMinNumFMaxNumCombine(N, DAG,
27959 case X86ISD::FAND: return PerformFANDCombine(N, DAG, Subtarget);
27960 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG, Subtarget);
27961 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
27962 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
27963 case ISD::ANY_EXTEND:
27964 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
27965 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
27966 case ISD::SIGN_EXTEND_INREG:
27967 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
27968 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
27969 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
27970 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
27971 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
27972 case X86ISD::SHUFP: // Handle all target specific shuffles
27973 case X86ISD::PALIGNR:
27974 case X86ISD::BLENDI:
27975 case X86ISD::UNPCKH:
27976 case X86ISD::UNPCKL:
27977 case X86ISD::MOVHLPS:
27978 case X86ISD::MOVLHPS:
27979 case X86ISD::PSHUFB:
27980 case X86ISD::PSHUFD:
27981 case X86ISD::PSHUFHW:
27982 case X86ISD::PSHUFLW:
27983 case X86ISD::MOVSS:
27984 case X86ISD::MOVSD:
27985 case X86ISD::VPERMILPI:
27986 case X86ISD::VPERM2X128:
27987 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
27988 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
27990 case ISD::MSCATTER: return PerformGatherScatterCombine(N, DAG);
27996 /// isTypeDesirableForOp - Return true if the target has native support for
27997 /// the specified value type and it is 'desirable' to use the type for the
27998 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
27999 /// instruction encodings are longer and some i16 instructions are slow.
28000 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
28001 if (!isTypeLegal(VT))
28003 if (VT != MVT::i16)
28010 case ISD::SIGN_EXTEND:
28011 case ISD::ZERO_EXTEND:
28012 case ISD::ANY_EXTEND:
28025 /// This function checks if any of the users of EFLAGS copies the EFLAGS. We
28026 /// know that the code that lowers COPY of EFLAGS has to use the stack, and if
28027 /// we don't adjust the stack we clobber the first frame index.
28028 /// See X86InstrInfo::copyPhysReg.
28029 bool X86TargetLowering::hasCopyImplyingStackAdjustment(
28030 MachineFunction *MF) const {
28031 const MachineRegisterInfo &MRI = MF->getRegInfo();
28033 return any_of(MRI.reg_instructions(X86::EFLAGS),
28034 [](const MachineInstr &RI) { return RI.isCopy(); });
28037 /// IsDesirableToPromoteOp - This method query the target whether it is
28038 /// beneficial for dag combiner to promote the specified node. If true, it
28039 /// should return the desired promotion type by reference.
28040 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
28041 EVT VT = Op.getValueType();
28042 if (VT != MVT::i16)
28045 bool Promote = false;
28046 bool Commute = false;
28047 switch (Op.getOpcode()) {
28050 LoadSDNode *LD = cast<LoadSDNode>(Op);
28051 // If the non-extending load has a single use and it's not live out, then it
28052 // might be folded.
28053 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
28054 Op.hasOneUse()*/) {
28055 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
28056 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
28057 // The only case where we'd want to promote LOAD (rather then it being
28058 // promoted as an operand is when it's only use is liveout.
28059 if (UI->getOpcode() != ISD::CopyToReg)
28066 case ISD::SIGN_EXTEND:
28067 case ISD::ZERO_EXTEND:
28068 case ISD::ANY_EXTEND:
28073 SDValue N0 = Op.getOperand(0);
28074 // Look out for (store (shl (load), x)).
28075 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
28088 SDValue N0 = Op.getOperand(0);
28089 SDValue N1 = Op.getOperand(1);
28090 if (!Commute && MayFoldLoad(N1))
28092 // Avoid disabling potential load folding opportunities.
28093 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
28095 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
28105 //===----------------------------------------------------------------------===//
28106 // X86 Inline Assembly Support
28107 //===----------------------------------------------------------------------===//
28109 // Helper to match a string separated by whitespace.
28110 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
28111 S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
28113 for (StringRef Piece : Pieces) {
28114 if (!S.startswith(Piece)) // Check if the piece matches.
28117 S = S.substr(Piece.size());
28118 StringRef::size_type Pos = S.find_first_not_of(" \t");
28119 if (Pos == 0) // We matched a prefix.
28128 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
28130 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
28131 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
28132 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
28133 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
28135 if (AsmPieces.size() == 3)
28137 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
28144 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
28145 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
28147 std::string AsmStr = IA->getAsmString();
28149 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
28150 if (!Ty || Ty->getBitWidth() % 16 != 0)
28153 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
28154 SmallVector<StringRef, 4> AsmPieces;
28155 SplitString(AsmStr, AsmPieces, ";\n");
28157 switch (AsmPieces.size()) {
28158 default: return false;
28160 // FIXME: this should verify that we are targeting a 486 or better. If not,
28161 // we will turn this bswap into something that will be lowered to logical
28162 // ops instead of emitting the bswap asm. For now, we don't support 486 or
28163 // lower so don't worry about this.
28165 if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
28166 matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
28167 matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
28168 matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
28169 matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
28170 matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
28171 // No need to check constraints, nothing other than the equivalent of
28172 // "=r,0" would be valid here.
28173 return IntrinsicLowering::LowerToByteSwap(CI);
28176 // rorw $$8, ${0:w} --> llvm.bswap.i16
28177 if (CI->getType()->isIntegerTy(16) &&
28178 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
28179 (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
28180 matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
28182 StringRef ConstraintsStr = IA->getConstraintString();
28183 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
28184 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
28185 if (clobbersFlagRegisters(AsmPieces))
28186 return IntrinsicLowering::LowerToByteSwap(CI);
28190 if (CI->getType()->isIntegerTy(32) &&
28191 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
28192 matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
28193 matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
28194 matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
28196 StringRef ConstraintsStr = IA->getConstraintString();
28197 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
28198 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
28199 if (clobbersFlagRegisters(AsmPieces))
28200 return IntrinsicLowering::LowerToByteSwap(CI);
28203 if (CI->getType()->isIntegerTy(64)) {
28204 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
28205 if (Constraints.size() >= 2 &&
28206 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
28207 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
28208 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
28209 if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
28210 matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
28211 matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
28212 return IntrinsicLowering::LowerToByteSwap(CI);
28220 /// getConstraintType - Given a constraint letter, return the type of
28221 /// constraint it is for this target.
28222 X86TargetLowering::ConstraintType
28223 X86TargetLowering::getConstraintType(StringRef Constraint) const {
28224 if (Constraint.size() == 1) {
28225 switch (Constraint[0]) {
28236 return C_RegisterClass;
28260 return TargetLowering::getConstraintType(Constraint);
28263 /// Examine constraint type and operand type and determine a weight value.
28264 /// This object must already have been set up with the operand type
28265 /// and the current alternative constraint selected.
28266 TargetLowering::ConstraintWeight
28267 X86TargetLowering::getSingleConstraintMatchWeight(
28268 AsmOperandInfo &info, const char *constraint) const {
28269 ConstraintWeight weight = CW_Invalid;
28270 Value *CallOperandVal = info.CallOperandVal;
28271 // If we don't have a value, we can't do a match,
28272 // but allow it at the lowest weight.
28273 if (!CallOperandVal)
28275 Type *type = CallOperandVal->getType();
28276 // Look at the constraint type.
28277 switch (*constraint) {
28279 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
28290 if (CallOperandVal->getType()->isIntegerTy())
28291 weight = CW_SpecificReg;
28296 if (type->isFloatingPointTy())
28297 weight = CW_SpecificReg;
28300 if (type->isX86_MMXTy() && Subtarget->hasMMX())
28301 weight = CW_SpecificReg;
28305 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
28306 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
28307 weight = CW_Register;
28310 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
28311 if (C->getZExtValue() <= 31)
28312 weight = CW_Constant;
28316 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28317 if (C->getZExtValue() <= 63)
28318 weight = CW_Constant;
28322 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28323 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
28324 weight = CW_Constant;
28328 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28329 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
28330 weight = CW_Constant;
28334 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28335 if (C->getZExtValue() <= 3)
28336 weight = CW_Constant;
28340 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28341 if (C->getZExtValue() <= 0xff)
28342 weight = CW_Constant;
28347 if (isa<ConstantFP>(CallOperandVal)) {
28348 weight = CW_Constant;
28352 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28353 if ((C->getSExtValue() >= -0x80000000LL) &&
28354 (C->getSExtValue() <= 0x7fffffffLL))
28355 weight = CW_Constant;
28359 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
28360 if (C->getZExtValue() <= 0xffffffff)
28361 weight = CW_Constant;
28368 /// LowerXConstraint - try to replace an X constraint, which matches anything,
28369 /// with another that has more specific requirements based on the type of the
28370 /// corresponding operand.
28371 const char *X86TargetLowering::
28372 LowerXConstraint(EVT ConstraintVT) const {
28373 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
28374 // 'f' like normal targets.
28375 if (ConstraintVT.isFloatingPoint()) {
28376 if (Subtarget->hasSSE2())
28378 if (Subtarget->hasSSE1())
28382 return TargetLowering::LowerXConstraint(ConstraintVT);
28385 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
28386 /// vector. If it is invalid, don't add anything to Ops.
28387 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
28388 std::string &Constraint,
28389 std::vector<SDValue>&Ops,
28390 SelectionDAG &DAG) const {
28393 // Only support length 1 constraints for now.
28394 if (Constraint.length() > 1) return;
28396 char ConstraintLetter = Constraint[0];
28397 switch (ConstraintLetter) {
28400 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28401 if (C->getZExtValue() <= 31) {
28402 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28403 Op.getValueType());
28409 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28410 if (C->getZExtValue() <= 63) {
28411 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28412 Op.getValueType());
28418 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28419 if (isInt<8>(C->getSExtValue())) {
28420 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28421 Op.getValueType());
28427 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28428 if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
28429 (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
28430 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
28431 Op.getValueType());
28437 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28438 if (C->getZExtValue() <= 3) {
28439 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28440 Op.getValueType());
28446 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28447 if (C->getZExtValue() <= 255) {
28448 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28449 Op.getValueType());
28455 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28456 if (C->getZExtValue() <= 127) {
28457 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28458 Op.getValueType());
28464 // 32-bit signed value
28465 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28466 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
28467 C->getSExtValue())) {
28468 // Widen to 64 bits here to get it sign extended.
28469 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
28472 // FIXME gcc accepts some relocatable values here too, but only in certain
28473 // memory models; it's complicated.
28478 // 32-bit unsigned value
28479 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
28480 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
28481 C->getZExtValue())) {
28482 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
28483 Op.getValueType());
28487 // FIXME gcc accepts some relocatable values here too, but only in certain
28488 // memory models; it's complicated.
28492 // Literal immediates are always ok.
28493 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
28494 // Widen to 64 bits here to get it sign extended.
28495 Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
28499 // In any sort of PIC mode addresses need to be computed at runtime by
28500 // adding in a register or some sort of table lookup. These can't
28501 // be used as immediates.
28502 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
28505 // If we are in non-pic codegen mode, we allow the address of a global (with
28506 // an optional displacement) to be used with 'i'.
28507 GlobalAddressSDNode *GA = nullptr;
28508 int64_t Offset = 0;
28510 // Match either (GA), (GA+C), (GA+C1+C2), etc.
28512 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
28513 Offset += GA->getOffset();
28515 } else if (Op.getOpcode() == ISD::ADD) {
28516 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
28517 Offset += C->getZExtValue();
28518 Op = Op.getOperand(0);
28521 } else if (Op.getOpcode() == ISD::SUB) {
28522 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
28523 Offset += -C->getZExtValue();
28524 Op = Op.getOperand(0);
28529 // Otherwise, this isn't something we can handle, reject it.
28533 const GlobalValue *GV = GA->getGlobal();
28534 // If we require an extra load to get this address, as in PIC mode, we
28535 // can't accept it.
28536 if (isGlobalStubReference(
28537 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
28540 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
28541 GA->getValueType(0), Offset);
28546 if (Result.getNode()) {
28547 Ops.push_back(Result);
28550 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
28553 std::pair<unsigned, const TargetRegisterClass *>
28554 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
28555 StringRef Constraint,
28557 // First, see if this is a constraint that directly corresponds to an LLVM
28559 if (Constraint.size() == 1) {
28560 // GCC Constraint Letters
28561 switch (Constraint[0]) {
28563 // TODO: Slight differences here in allocation order and leaving
28564 // RIP in the class. Do they matter any more here than they do
28565 // in the normal allocation?
28566 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
28567 if (Subtarget->is64Bit()) {
28568 if (VT == MVT::i32 || VT == MVT::f32)
28569 return std::make_pair(0U, &X86::GR32RegClass);
28570 if (VT == MVT::i16)
28571 return std::make_pair(0U, &X86::GR16RegClass);
28572 if (VT == MVT::i8 || VT == MVT::i1)
28573 return std::make_pair(0U, &X86::GR8RegClass);
28574 if (VT == MVT::i64 || VT == MVT::f64)
28575 return std::make_pair(0U, &X86::GR64RegClass);
28578 // 32-bit fallthrough
28579 case 'Q': // Q_REGS
28580 if (VT == MVT::i32 || VT == MVT::f32)
28581 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
28582 if (VT == MVT::i16)
28583 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
28584 if (VT == MVT::i8 || VT == MVT::i1)
28585 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
28586 if (VT == MVT::i64)
28587 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
28589 case 'r': // GENERAL_REGS
28590 case 'l': // INDEX_REGS
28591 if (VT == MVT::i8 || VT == MVT::i1)
28592 return std::make_pair(0U, &X86::GR8RegClass);
28593 if (VT == MVT::i16)
28594 return std::make_pair(0U, &X86::GR16RegClass);
28595 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
28596 return std::make_pair(0U, &X86::GR32RegClass);
28597 return std::make_pair(0U, &X86::GR64RegClass);
28598 case 'R': // LEGACY_REGS
28599 if (VT == MVT::i8 || VT == MVT::i1)
28600 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
28601 if (VT == MVT::i16)
28602 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
28603 if (VT == MVT::i32 || !Subtarget->is64Bit())
28604 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
28605 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
28606 case 'f': // FP Stack registers.
28607 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
28608 // value to the correct fpstack register class.
28609 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
28610 return std::make_pair(0U, &X86::RFP32RegClass);
28611 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
28612 return std::make_pair(0U, &X86::RFP64RegClass);
28613 return std::make_pair(0U, &X86::RFP80RegClass);
28614 case 'y': // MMX_REGS if MMX allowed.
28615 if (!Subtarget->hasMMX()) break;
28616 return std::make_pair(0U, &X86::VR64RegClass);
28617 case 'Y': // SSE_REGS if SSE2 allowed
28618 if (!Subtarget->hasSSE2()) break;
28620 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
28621 if (!Subtarget->hasSSE1()) break;
28623 switch (VT.SimpleTy) {
28625 // Scalar SSE types.
28628 return std::make_pair(0U, &X86::FR32RegClass);
28631 return std::make_pair(0U, &X86::FR64RegClass);
28632 // TODO: Handle f128 and i128 in FR128RegClass after it is tested well.
28640 return std::make_pair(0U, &X86::VR128RegClass);
28648 return std::make_pair(0U, &X86::VR256RegClass);
28653 return std::make_pair(0U, &X86::VR512RegClass);
28659 // Use the default implementation in TargetLowering to convert the register
28660 // constraint into a member of a register class.
28661 std::pair<unsigned, const TargetRegisterClass*> Res;
28662 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
28664 // Not found as a standard register?
28666 // Map st(0) -> st(7) -> ST0
28667 if (Constraint.size() == 7 && Constraint[0] == '{' &&
28668 tolower(Constraint[1]) == 's' &&
28669 tolower(Constraint[2]) == 't' &&
28670 Constraint[3] == '(' &&
28671 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
28672 Constraint[5] == ')' &&
28673 Constraint[6] == '}') {
28675 Res.first = X86::FP0+Constraint[4]-'0';
28676 Res.second = &X86::RFP80RegClass;
28680 // GCC allows "st(0)" to be called just plain "st".
28681 if (StringRef("{st}").equals_lower(Constraint)) {
28682 Res.first = X86::FP0;
28683 Res.second = &X86::RFP80RegClass;
28688 if (StringRef("{flags}").equals_lower(Constraint)) {
28689 Res.first = X86::EFLAGS;
28690 Res.second = &X86::CCRRegClass;
28694 // 'A' means EAX + EDX.
28695 if (Constraint == "A") {
28696 Res.first = X86::EAX;
28697 Res.second = &X86::GR32_ADRegClass;
28703 // Otherwise, check to see if this is a register class of the wrong value
28704 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
28705 // turn into {ax},{dx}.
28706 // MVT::Other is used to specify clobber names.
28707 if (Res.second->hasType(VT) || VT == MVT::Other)
28708 return Res; // Correct type already, nothing to do.
28710 // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
28711 // return "eax". This should even work for things like getting 64bit integer
28712 // registers when given an f64 type.
28713 const TargetRegisterClass *Class = Res.second;
28714 if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
28715 Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
28716 unsigned Size = VT.getSizeInBits();
28717 if (Size == 1) Size = 8;
28718 unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, Size);
28720 Res.first = DestReg;
28721 Res.second = Size == 8 ? &X86::GR8RegClass
28722 : Size == 16 ? &X86::GR16RegClass
28723 : Size == 32 ? &X86::GR32RegClass
28724 : &X86::GR64RegClass;
28725 assert(Res.second->contains(Res.first) && "Register in register class");
28727 // No register found/type mismatch.
28729 Res.second = nullptr;
28731 } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
28732 Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
28733 Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
28734 Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
28735 Class == &X86::VR512RegClass) {
28736 // Handle references to XMM physical registers that got mapped into the
28737 // wrong class. This can happen with constraints like {xmm0} where the
28738 // target independent register mapper will just pick the first match it can
28739 // find, ignoring the required type.
28741 // TODO: Handle f128 and i128 in FR128RegClass after it is tested well.
28742 if (VT == MVT::f32 || VT == MVT::i32)
28743 Res.second = &X86::FR32RegClass;
28744 else if (VT == MVT::f64 || VT == MVT::i64)
28745 Res.second = &X86::FR64RegClass;
28746 else if (X86::VR128RegClass.hasType(VT))
28747 Res.second = &X86::VR128RegClass;
28748 else if (X86::VR256RegClass.hasType(VT))
28749 Res.second = &X86::VR256RegClass;
28750 else if (X86::VR512RegClass.hasType(VT))
28751 Res.second = &X86::VR512RegClass;
28753 // Type mismatch and not a clobber: Return an error;
28755 Res.second = nullptr;
28762 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
28763 const AddrMode &AM, Type *Ty,
28764 unsigned AS) const {
28765 // Scaling factors are not free at all.
28766 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
28767 // will take 2 allocations in the out of order engine instead of 1
28768 // for plain addressing mode, i.e. inst (reg1).
28770 // vaddps (%rsi,%drx), %ymm0, %ymm1
28771 // Requires two allocations (one for the load, one for the computation)
28773 // vaddps (%rsi), %ymm0, %ymm1
28774 // Requires just 1 allocation, i.e., freeing allocations for other operations
28775 // and having less micro operations to execute.
28777 // For some X86 architectures, this is even worse because for instance for
28778 // stores, the complex addressing mode forces the instruction to use the
28779 // "load" ports instead of the dedicated "store" port.
28780 // E.g., on Haswell:
28781 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
28782 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
28783 if (isLegalAddressingMode(DL, AM, Ty, AS))
28784 // Scale represents reg2 * scale, thus account for 1
28785 // as soon as we use a second register.
28786 return AM.Scale != 0;
28790 bool X86TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const {
28791 // Integer division on x86 is expensive. However, when aggressively optimizing
28792 // for code size, we prefer to use a div instruction, as it is usually smaller
28793 // than the alternative sequence.
28794 // The exception to this is vector division. Since x86 doesn't have vector
28795 // integer division, leaving the division as-is is a loss even in terms of
28796 // size, because it will have to be scalarized, while the alternative code
28797 // sequence can be performed in vector form.
28798 bool OptSize = Attr.hasAttribute(AttributeSet::FunctionIndex,
28799 Attribute::MinSize);
28800 return OptSize && !VT.isVector();