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 "X86TargetMachine.h"
22 #include "X86TargetObjectFile.h"
23 #include "llvm/ADT/SmallBitVector.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/Analysis/EHPersonalities.h"
29 #include "llvm/CodeGen/IntrinsicLowering.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/WinEHFuncInfo.h"
37 #include "llvm/IR/CallSite.h"
38 #include "llvm/IR/CallingConv.h"
39 #include "llvm/IR/Constants.h"
40 #include "llvm/IR/DerivedTypes.h"
41 #include "llvm/IR/Function.h"
42 #include "llvm/IR/GlobalAlias.h"
43 #include "llvm/IR/GlobalVariable.h"
44 #include "llvm/IR/Instructions.h"
45 #include "llvm/IR/Intrinsics.h"
46 #include "llvm/MC/MCAsmInfo.h"
47 #include "llvm/MC/MCContext.h"
48 #include "llvm/MC/MCExpr.h"
49 #include "llvm/MC/MCSymbol.h"
50 #include "llvm/Support/CommandLine.h"
51 #include "llvm/Support/Debug.h"
52 #include "llvm/Support/ErrorHandling.h"
53 #include "llvm/Support/MathExtras.h"
54 #include "llvm/Target/TargetOptions.h"
55 #include "X86IntrinsicsInfo.h"
61 #define DEBUG_TYPE "x86-isel"
63 STATISTIC(NumTailCalls, "Number of tail calls");
65 static cl::opt<bool> ExperimentalVectorWideningLegalization(
66 "x86-experimental-vector-widening-legalization", cl::init(false),
67 cl::desc("Enable an experimental vector type legalization through widening "
68 "rather than promotion."),
71 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
72 const X86Subtarget &STI)
73 : TargetLowering(TM), Subtarget(&STI) {
74 X86ScalarSSEf64 = Subtarget->hasSSE2();
75 X86ScalarSSEf32 = Subtarget->hasSSE1();
76 MVT PtrVT = MVT::getIntegerVT(8 * TM.getPointerSize());
78 // Set up the TargetLowering object.
80 // X86 is weird. It always uses i8 for shift amounts and setcc results.
81 setBooleanContents(ZeroOrOneBooleanContent);
82 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
83 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
85 // For 64-bit, since we have so many registers, use the ILP scheduler.
86 // For 32-bit, use the register pressure specific scheduling.
87 // For Atom, always use ILP scheduling.
88 if (Subtarget->isAtom())
89 setSchedulingPreference(Sched::ILP);
90 else if (Subtarget->is64Bit())
91 setSchedulingPreference(Sched::ILP);
93 setSchedulingPreference(Sched::RegPressure);
94 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
95 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
97 // Bypass expensive divides on Atom when compiling with O2.
98 if (TM.getOptLevel() >= CodeGenOpt::Default) {
99 if (Subtarget->hasSlowDivide32())
100 addBypassSlowDiv(32, 8);
101 if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
102 addBypassSlowDiv(64, 16);
105 if (Subtarget->isTargetKnownWindowsMSVC()) {
106 // Setup Windows compiler runtime calls.
107 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
108 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
109 setLibcallName(RTLIB::SREM_I64, "_allrem");
110 setLibcallName(RTLIB::UREM_I64, "_aullrem");
111 setLibcallName(RTLIB::MUL_I64, "_allmul");
112 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
113 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
114 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
115 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
116 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
119 if (Subtarget->isTargetDarwin()) {
120 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
121 setUseUnderscoreSetJmp(false);
122 setUseUnderscoreLongJmp(false);
123 } else if (Subtarget->isTargetWindowsGNU()) {
124 // MS runtime is weird: it exports _setjmp, but longjmp!
125 setUseUnderscoreSetJmp(true);
126 setUseUnderscoreLongJmp(false);
128 setUseUnderscoreSetJmp(true);
129 setUseUnderscoreLongJmp(true);
132 // Set up the register classes.
133 addRegisterClass(MVT::i8, &X86::GR8RegClass);
134 addRegisterClass(MVT::i16, &X86::GR16RegClass);
135 addRegisterClass(MVT::i32, &X86::GR32RegClass);
136 if (Subtarget->is64Bit())
137 addRegisterClass(MVT::i64, &X86::GR64RegClass);
139 for (MVT VT : MVT::integer_valuetypes())
140 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
142 // We don't accept any truncstore of integer registers.
143 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
144 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
145 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
146 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
147 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
148 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
150 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
152 // SETOEQ and SETUNE require checking two conditions.
153 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
154 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
155 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
156 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
157 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
158 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
160 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
162 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
163 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
164 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
166 if (Subtarget->is64Bit()) {
167 if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512())
168 // f32/f64 are legal, f80 is custom.
169 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
171 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
172 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
173 } else if (!Subtarget->useSoftFloat()) {
174 // We have an algorithm for SSE2->double, and we turn this into a
175 // 64-bit FILD followed by conditional FADD for other targets.
176 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
177 // We have an algorithm for SSE2, and we turn this into a 64-bit
178 // FILD or VCVTUSI2SS/SD for other targets.
179 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
182 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
184 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
185 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
187 if (!Subtarget->useSoftFloat()) {
188 // SSE has no i16 to fp conversion, only i32
189 if (X86ScalarSSEf32) {
190 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
191 // f32 and f64 cases are Legal, f80 case is not
192 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
194 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
195 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
198 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
199 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
202 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
204 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
205 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
207 if (!Subtarget->useSoftFloat()) {
208 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
209 // are Legal, f80 is custom lowered.
210 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
211 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
213 if (X86ScalarSSEf32) {
214 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
215 // f32 and f64 cases are Legal, f80 case is not
216 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
218 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
219 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
222 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
223 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Expand);
224 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Expand);
227 // Handle FP_TO_UINT by promoting the destination to a larger signed
229 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
230 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
231 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
233 if (Subtarget->is64Bit()) {
234 if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
235 // FP_TO_UINT-i32/i64 is legal for f32/f64, but custom for f80.
236 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
237 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
239 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
240 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
242 } else if (!Subtarget->useSoftFloat()) {
243 // Since AVX is a superset of SSE3, only check for SSE here.
244 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
245 // Expand FP_TO_UINT into a select.
246 // FIXME: We would like to use a Custom expander here eventually to do
247 // the optimal thing for SSE vs. the default expansion in the legalizer.
248 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
250 // With AVX512 we can use vcvts[ds]2usi for f32/f64->i32, f80 is custom.
251 // With SSE3 we can use fisttpll to convert to a signed i64; without
252 // SSE, we're stuck with a fistpll.
253 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
255 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
258 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
259 if (!X86ScalarSSEf64) {
260 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
261 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
262 if (Subtarget->is64Bit()) {
263 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
264 // Without SSE, i64->f64 goes through memory.
265 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
269 // Scalar integer divide and remainder are lowered to use operations that
270 // produce two results, to match the available instructions. This exposes
271 // the two-result form to trivial CSE, which is able to combine x/y and x%y
272 // into a single instruction.
274 // Scalar integer multiply-high is also lowered to use two-result
275 // operations, to match the available instructions. However, plain multiply
276 // (low) operations are left as Legal, as there are single-result
277 // instructions for this in x86. Using the two-result multiply instructions
278 // when both high and low results are needed must be arranged by dagcombine.
279 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
280 setOperationAction(ISD::MULHS, VT, Expand);
281 setOperationAction(ISD::MULHU, VT, Expand);
282 setOperationAction(ISD::SDIV, VT, Expand);
283 setOperationAction(ISD::UDIV, VT, Expand);
284 setOperationAction(ISD::SREM, VT, Expand);
285 setOperationAction(ISD::UREM, VT, Expand);
287 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
288 setOperationAction(ISD::ADDC, VT, Custom);
289 setOperationAction(ISD::ADDE, VT, Custom);
290 setOperationAction(ISD::SUBC, VT, Custom);
291 setOperationAction(ISD::SUBE, VT, Custom);
294 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
295 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
296 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
297 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
298 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
299 setOperationAction(ISD::BR_CC , MVT::f128, Expand);
300 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
301 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
302 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
303 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
304 setOperationAction(ISD::SELECT_CC , MVT::f32, Expand);
305 setOperationAction(ISD::SELECT_CC , MVT::f64, Expand);
306 setOperationAction(ISD::SELECT_CC , MVT::f80, Expand);
307 setOperationAction(ISD::SELECT_CC , MVT::f128, Expand);
308 setOperationAction(ISD::SELECT_CC , MVT::i8, Expand);
309 setOperationAction(ISD::SELECT_CC , MVT::i16, Expand);
310 setOperationAction(ISD::SELECT_CC , MVT::i32, Expand);
311 setOperationAction(ISD::SELECT_CC , MVT::i64, Expand);
312 if (Subtarget->is64Bit())
313 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
314 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
315 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
316 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
317 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
319 if (Subtarget->is32Bit() && Subtarget->isTargetKnownWindowsMSVC()) {
320 // On 32 bit MSVC, `fmodf(f32)` is not defined - only `fmod(f64)`
321 // is. We should promote the value to 64-bits to solve this.
322 // This is what the CRT headers do - `fmodf` is an inline header
323 // function casting to f64 and calling `fmod`.
324 setOperationAction(ISD::FREM , MVT::f32 , Promote);
326 setOperationAction(ISD::FREM , MVT::f32 , Expand);
329 setOperationAction(ISD::FREM , MVT::f64 , Expand);
330 setOperationAction(ISD::FREM , MVT::f80 , Expand);
331 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
333 // Promote the i8 variants and force them on up to i32 which has a shorter
335 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
336 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
337 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
338 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
339 if (Subtarget->hasBMI()) {
340 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
341 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
342 if (Subtarget->is64Bit())
343 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
345 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
346 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
347 if (Subtarget->is64Bit())
348 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
351 if (Subtarget->hasLZCNT()) {
352 // When promoting the i8 variants, force them to i32 for a shorter
354 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
355 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
356 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
357 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
358 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
359 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
360 if (Subtarget->is64Bit())
361 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
363 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
364 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
365 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
366 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
367 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
368 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
369 if (Subtarget->is64Bit()) {
370 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
371 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
375 // Special handling for half-precision floating point conversions.
376 // If we don't have F16C support, then lower half float conversions
377 // into library calls.
378 if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) {
379 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
380 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
383 // There's never any support for operations beyond MVT::f32.
384 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
385 setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
386 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
387 setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
389 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
390 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
391 setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
392 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
393 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
394 setTruncStoreAction(MVT::f80, MVT::f16, Expand);
396 if (Subtarget->hasPOPCNT()) {
397 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
399 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
400 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
401 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
402 if (Subtarget->is64Bit())
403 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
406 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
408 if (!Subtarget->hasMOVBE())
409 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
411 // These should be promoted to a larger select which is supported.
412 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
413 // X86 wants to expand cmov itself.
414 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
415 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
416 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
417 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
418 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
419 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
420 setOperationAction(ISD::SELECT , MVT::f128 , Custom);
421 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
422 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
423 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
424 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
425 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
426 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
427 setOperationAction(ISD::SETCC , MVT::f128 , Custom);
428 setOperationAction(ISD::SETCCE , MVT::i8 , Custom);
429 setOperationAction(ISD::SETCCE , MVT::i16 , Custom);
430 setOperationAction(ISD::SETCCE , MVT::i32 , Custom);
431 if (Subtarget->is64Bit()) {
432 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
433 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
434 setOperationAction(ISD::SETCCE , MVT::i64 , Custom);
436 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
437 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
438 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
439 // support continuation, user-level threading, and etc.. As a result, no
440 // other SjLj exception interfaces are implemented and please don't build
441 // your own exception handling based on them.
442 // LLVM/Clang supports zero-cost DWARF exception handling.
443 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
444 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
447 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
448 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
449 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
450 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
451 if (Subtarget->is64Bit())
452 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
453 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
454 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
455 if (Subtarget->is64Bit()) {
456 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
457 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
458 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
459 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
460 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
462 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
463 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
464 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
465 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
466 if (Subtarget->is64Bit()) {
467 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
468 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
469 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
472 if (Subtarget->hasSSE1())
473 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
475 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
477 // Expand certain atomics
478 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
479 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
480 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
481 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
484 if (Subtarget->hasCmpxchg16b()) {
485 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
488 // FIXME - use subtarget debug flags
489 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
490 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
491 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
494 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
495 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
497 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
498 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
500 setOperationAction(ISD::TRAP, MVT::Other, Legal);
501 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
503 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
504 setOperationAction(ISD::VASTART , MVT::Other, Custom);
505 setOperationAction(ISD::VAEND , MVT::Other, Expand);
506 if (Subtarget->is64Bit()) {
507 setOperationAction(ISD::VAARG , MVT::Other, Custom);
508 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
510 // TargetInfo::CharPtrBuiltinVaList
511 setOperationAction(ISD::VAARG , MVT::Other, Expand);
512 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
515 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
516 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
518 setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
520 // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
521 setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
522 setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
524 if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
525 // f32 and f64 use SSE.
526 // Set up the FP register classes.
527 addRegisterClass(MVT::f32, &X86::FR32RegClass);
528 addRegisterClass(MVT::f64, &X86::FR64RegClass);
530 // Use ANDPD to simulate FABS.
531 setOperationAction(ISD::FABS , MVT::f64, Custom);
532 setOperationAction(ISD::FABS , MVT::f32, Custom);
534 // Use XORP to simulate FNEG.
535 setOperationAction(ISD::FNEG , MVT::f64, Custom);
536 setOperationAction(ISD::FNEG , MVT::f32, Custom);
538 // Use ANDPD and ORPD to simulate FCOPYSIGN.
539 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
540 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
542 // Lower this to FGETSIGNx86 plus an AND.
543 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
544 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
546 // We don't support sin/cos/fmod
547 setOperationAction(ISD::FSIN , MVT::f64, Expand);
548 setOperationAction(ISD::FCOS , MVT::f64, Expand);
549 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
550 setOperationAction(ISD::FSIN , MVT::f32, Expand);
551 setOperationAction(ISD::FCOS , MVT::f32, Expand);
552 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
554 // Expand FP immediates into loads from the stack, except for the special
556 addLegalFPImmediate(APFloat(+0.0)); // xorpd
557 addLegalFPImmediate(APFloat(+0.0f)); // xorps
558 } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
559 // Use SSE for f32, x87 for f64.
560 // Set up the FP register classes.
561 addRegisterClass(MVT::f32, &X86::FR32RegClass);
562 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
564 // Use ANDPS to simulate FABS.
565 setOperationAction(ISD::FABS , MVT::f32, Custom);
567 // Use XORP to simulate FNEG.
568 setOperationAction(ISD::FNEG , MVT::f32, Custom);
570 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
572 // Use ANDPS and ORPS to simulate FCOPYSIGN.
573 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
574 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
576 // We don't support sin/cos/fmod
577 setOperationAction(ISD::FSIN , MVT::f32, Expand);
578 setOperationAction(ISD::FCOS , MVT::f32, Expand);
579 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
581 // Special cases we handle for FP constants.
582 addLegalFPImmediate(APFloat(+0.0f)); // xorps
583 addLegalFPImmediate(APFloat(+0.0)); // FLD0
584 addLegalFPImmediate(APFloat(+1.0)); // FLD1
585 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
586 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
588 if (!TM.Options.UnsafeFPMath) {
589 setOperationAction(ISD::FSIN , MVT::f64, Expand);
590 setOperationAction(ISD::FCOS , MVT::f64, Expand);
591 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
593 } else if (!Subtarget->useSoftFloat()) {
594 // f32 and f64 in x87.
595 // Set up the FP register classes.
596 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
597 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
599 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
600 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
601 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
602 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
604 if (!TM.Options.UnsafeFPMath) {
605 setOperationAction(ISD::FSIN , MVT::f64, Expand);
606 setOperationAction(ISD::FSIN , MVT::f32, Expand);
607 setOperationAction(ISD::FCOS , MVT::f64, Expand);
608 setOperationAction(ISD::FCOS , MVT::f32, Expand);
609 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
610 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
612 addLegalFPImmediate(APFloat(+0.0)); // FLD0
613 addLegalFPImmediate(APFloat(+1.0)); // FLD1
614 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
615 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
616 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
617 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
618 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
619 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
622 // We don't support FMA.
623 setOperationAction(ISD::FMA, MVT::f64, Expand);
624 setOperationAction(ISD::FMA, MVT::f32, Expand);
626 // Long double always uses X87, except f128 in MMX.
627 if (!Subtarget->useSoftFloat()) {
628 if (Subtarget->is64Bit() && Subtarget->hasMMX()) {
629 addRegisterClass(MVT::f128, &X86::FR128RegClass);
630 ValueTypeActions.setTypeAction(MVT::f128, TypeSoftenFloat);
631 setOperationAction(ISD::FABS , MVT::f128, Custom);
632 setOperationAction(ISD::FNEG , MVT::f128, Custom);
633 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Custom);
636 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
637 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
638 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
640 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
641 addLegalFPImmediate(TmpFlt); // FLD0
643 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
646 APFloat TmpFlt2(+1.0);
647 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
649 addLegalFPImmediate(TmpFlt2); // FLD1
650 TmpFlt2.changeSign();
651 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
654 if (!TM.Options.UnsafeFPMath) {
655 setOperationAction(ISD::FSIN , MVT::f80, Expand);
656 setOperationAction(ISD::FCOS , MVT::f80, Expand);
657 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
660 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
661 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
662 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
663 setOperationAction(ISD::FRINT, MVT::f80, Expand);
664 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
665 setOperationAction(ISD::FMA, MVT::f80, Expand);
668 // Always use a library call for pow.
669 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
670 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
671 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
673 setOperationAction(ISD::FLOG, MVT::f80, Expand);
674 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
675 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
676 setOperationAction(ISD::FEXP, MVT::f80, Expand);
677 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
678 setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
679 setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
681 // First set operation action for all vector types to either promote
682 // (for widening) or expand (for scalarization). Then we will selectively
683 // turn on ones that can be effectively codegen'd.
684 for (MVT VT : MVT::vector_valuetypes()) {
685 setOperationAction(ISD::ADD , VT, Expand);
686 setOperationAction(ISD::SUB , VT, Expand);
687 setOperationAction(ISD::FADD, VT, Expand);
688 setOperationAction(ISD::FNEG, VT, Expand);
689 setOperationAction(ISD::FSUB, VT, Expand);
690 setOperationAction(ISD::MUL , VT, Expand);
691 setOperationAction(ISD::FMUL, VT, Expand);
692 setOperationAction(ISD::SDIV, VT, Expand);
693 setOperationAction(ISD::UDIV, VT, Expand);
694 setOperationAction(ISD::FDIV, VT, Expand);
695 setOperationAction(ISD::SREM, VT, Expand);
696 setOperationAction(ISD::UREM, VT, Expand);
697 setOperationAction(ISD::LOAD, VT, Expand);
698 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
699 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
700 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
701 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
702 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
703 setOperationAction(ISD::FABS, VT, Expand);
704 setOperationAction(ISD::FSIN, VT, Expand);
705 setOperationAction(ISD::FSINCOS, VT, Expand);
706 setOperationAction(ISD::FCOS, VT, Expand);
707 setOperationAction(ISD::FSINCOS, VT, Expand);
708 setOperationAction(ISD::FREM, VT, Expand);
709 setOperationAction(ISD::FMA, VT, Expand);
710 setOperationAction(ISD::FPOWI, VT, Expand);
711 setOperationAction(ISD::FSQRT, VT, Expand);
712 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
713 setOperationAction(ISD::FFLOOR, VT, Expand);
714 setOperationAction(ISD::FCEIL, VT, Expand);
715 setOperationAction(ISD::FTRUNC, VT, Expand);
716 setOperationAction(ISD::FRINT, VT, Expand);
717 setOperationAction(ISD::FNEARBYINT, VT, Expand);
718 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
719 setOperationAction(ISD::MULHS, VT, Expand);
720 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
721 setOperationAction(ISD::MULHU, VT, Expand);
722 setOperationAction(ISD::SDIVREM, VT, Expand);
723 setOperationAction(ISD::UDIVREM, VT, Expand);
724 setOperationAction(ISD::FPOW, VT, Expand);
725 setOperationAction(ISD::CTPOP, VT, Expand);
726 setOperationAction(ISD::CTTZ, VT, Expand);
727 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
728 setOperationAction(ISD::CTLZ, VT, Expand);
729 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
730 setOperationAction(ISD::SHL, VT, Expand);
731 setOperationAction(ISD::SRA, VT, Expand);
732 setOperationAction(ISD::SRL, VT, Expand);
733 setOperationAction(ISD::ROTL, VT, Expand);
734 setOperationAction(ISD::ROTR, VT, Expand);
735 setOperationAction(ISD::BSWAP, VT, Expand);
736 setOperationAction(ISD::SETCC, VT, Expand);
737 setOperationAction(ISD::FLOG, VT, Expand);
738 setOperationAction(ISD::FLOG2, VT, Expand);
739 setOperationAction(ISD::FLOG10, VT, Expand);
740 setOperationAction(ISD::FEXP, VT, Expand);
741 setOperationAction(ISD::FEXP2, VT, Expand);
742 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
743 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
744 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
745 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
746 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
747 setOperationAction(ISD::TRUNCATE, VT, Expand);
748 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
749 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
750 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
751 setOperationAction(ISD::VSELECT, VT, Expand);
752 setOperationAction(ISD::SELECT_CC, VT, Expand);
753 for (MVT InnerVT : MVT::vector_valuetypes()) {
754 setTruncStoreAction(InnerVT, VT, Expand);
756 setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
757 setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
759 // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
760 // types, we have to deal with them whether we ask for Expansion or not.
761 // Setting Expand causes its own optimisation problems though, so leave
763 if (VT.getVectorElementType() == MVT::i1)
764 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
766 // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
767 // split/scalarized right now.
768 if (VT.getVectorElementType() == MVT::f16)
769 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
773 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
774 // with -msoft-float, disable use of MMX as well.
775 if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
776 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
777 // No operations on x86mmx supported, everything uses intrinsics.
780 // MMX-sized vectors (other than x86mmx) are expected to be expanded
781 // into smaller operations.
782 for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
783 setOperationAction(ISD::MULHS, MMXTy, Expand);
784 setOperationAction(ISD::AND, MMXTy, Expand);
785 setOperationAction(ISD::OR, MMXTy, Expand);
786 setOperationAction(ISD::XOR, MMXTy, Expand);
787 setOperationAction(ISD::SCALAR_TO_VECTOR, MMXTy, Expand);
788 setOperationAction(ISD::SELECT, MMXTy, Expand);
789 setOperationAction(ISD::BITCAST, MMXTy, Expand);
791 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
793 if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
794 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
796 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
797 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
798 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
799 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
800 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
801 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
802 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
803 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
804 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
805 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
806 setOperationAction(ISD::VSELECT, MVT::v4f32, Custom);
807 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
808 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
809 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
812 if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
813 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
815 // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
816 // registers cannot be used even for integer operations.
817 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
818 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
819 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
820 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
822 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
823 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
824 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
825 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
826 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
827 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
828 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
829 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
830 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
831 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
832 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
833 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
834 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
835 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
836 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
837 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
838 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
839 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
840 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
841 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
842 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
843 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
844 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
846 setOperationAction(ISD::SMAX, MVT::v8i16, Legal);
847 setOperationAction(ISD::UMAX, MVT::v16i8, Legal);
848 setOperationAction(ISD::SMIN, MVT::v8i16, Legal);
849 setOperationAction(ISD::UMIN, MVT::v16i8, Legal);
851 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
852 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
853 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
854 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
856 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
857 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
858 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
859 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
860 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
862 setOperationAction(ISD::CTPOP, MVT::v16i8, Custom);
863 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
864 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
865 setOperationAction(ISD::CTPOP, MVT::v2i64, Custom);
867 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
868 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
869 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
870 // ISD::CTTZ v2i64 - scalarization is faster.
871 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
872 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
873 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
874 // ISD::CTTZ_ZERO_UNDEF v2i64 - scalarization is faster.
876 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
877 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
878 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
879 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
880 setOperationAction(ISD::VSELECT, VT, Custom);
881 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
884 // We support custom legalizing of sext and anyext loads for specific
885 // memory vector types which we can load as a scalar (or sequence of
886 // scalars) and extend in-register to a legal 128-bit vector type. For sext
887 // loads these must work with a single scalar load.
888 for (MVT VT : MVT::integer_vector_valuetypes()) {
889 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
890 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
891 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
892 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
893 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
894 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
895 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
896 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
897 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
900 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
901 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
902 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
903 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
904 setOperationAction(ISD::VSELECT, MVT::v2f64, Custom);
905 setOperationAction(ISD::VSELECT, MVT::v2i64, Custom);
906 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
907 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
909 if (Subtarget->is64Bit()) {
910 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
911 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
914 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
915 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
916 setOperationAction(ISD::AND, VT, Promote);
917 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
918 setOperationAction(ISD::OR, VT, Promote);
919 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
920 setOperationAction(ISD::XOR, VT, Promote);
921 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
922 setOperationAction(ISD::LOAD, VT, Promote);
923 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
924 setOperationAction(ISD::SELECT, VT, Promote);
925 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
928 // Custom lower v2i64 and v2f64 selects.
929 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
930 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
931 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
932 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
934 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
935 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
937 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
939 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
940 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
941 // As there is no 64-bit GPR available, we need build a special custom
942 // sequence to convert from v2i32 to v2f32.
943 if (!Subtarget->is64Bit())
944 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
946 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
947 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
949 for (MVT VT : MVT::fp_vector_valuetypes())
950 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
952 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
953 setOperationAction(ISD::BITCAST, MVT::v4i16, Custom);
954 setOperationAction(ISD::BITCAST, MVT::v8i8, Custom);
957 if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
958 for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
959 setOperationAction(ISD::FFLOOR, RoundedTy, Legal);
960 setOperationAction(ISD::FCEIL, RoundedTy, Legal);
961 setOperationAction(ISD::FTRUNC, RoundedTy, Legal);
962 setOperationAction(ISD::FRINT, RoundedTy, Legal);
963 setOperationAction(ISD::FNEARBYINT, RoundedTy, Legal);
966 setOperationAction(ISD::SMAX, MVT::v16i8, Legal);
967 setOperationAction(ISD::SMAX, MVT::v4i32, Legal);
968 setOperationAction(ISD::UMAX, MVT::v8i16, Legal);
969 setOperationAction(ISD::UMAX, MVT::v4i32, Legal);
970 setOperationAction(ISD::SMIN, MVT::v16i8, Legal);
971 setOperationAction(ISD::SMIN, MVT::v4i32, Legal);
972 setOperationAction(ISD::UMIN, MVT::v8i16, Legal);
973 setOperationAction(ISD::UMIN, MVT::v4i32, Legal);
975 // FIXME: Do we need to handle scalar-to-vector here?
976 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
978 // We directly match byte blends in the backend as they match the VSELECT
980 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
982 // SSE41 brings specific instructions for doing vector sign extend even in
983 // cases where we don't have SRA.
984 for (MVT VT : MVT::integer_vector_valuetypes()) {
985 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
986 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
987 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
990 // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
991 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8, Legal);
992 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8, Legal);
993 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8, Legal);
994 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
995 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
996 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
998 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8, Legal);
999 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8, Legal);
1000 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8, Legal);
1001 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
1002 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
1003 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
1005 // i8 and i16 vectors are custom because the source register and source
1006 // source memory operand types are not the same width. f32 vectors are
1007 // custom since the immediate controlling the insert encodes additional
1009 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1010 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1011 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1012 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1014 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1015 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1016 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1017 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1019 // FIXME: these should be Legal, but that's only for the case where
1020 // the index is constant. For now custom expand to deal with that.
1021 if (Subtarget->is64Bit()) {
1022 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1023 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1027 if (Subtarget->hasSSE2()) {
1028 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1029 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1030 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1032 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1033 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1035 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1036 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1038 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1039 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1041 // In the customized shift lowering, the legal cases in AVX2 will be
1043 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1044 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1046 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1047 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1049 setOperationAction(ISD::SRA, MVT::v2i64, Custom);
1050 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1053 if (Subtarget->hasXOP()) {
1054 setOperationAction(ISD::ROTL, MVT::v16i8, Custom);
1055 setOperationAction(ISD::ROTL, MVT::v8i16, Custom);
1056 setOperationAction(ISD::ROTL, MVT::v4i32, Custom);
1057 setOperationAction(ISD::ROTL, MVT::v2i64, Custom);
1058 setOperationAction(ISD::ROTL, MVT::v32i8, Custom);
1059 setOperationAction(ISD::ROTL, MVT::v16i16, Custom);
1060 setOperationAction(ISD::ROTL, MVT::v8i32, Custom);
1061 setOperationAction(ISD::ROTL, MVT::v4i64, Custom);
1064 if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1065 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1066 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1067 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1068 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1069 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1070 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1072 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1073 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1074 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1076 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1077 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1078 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1079 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1080 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1081 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1082 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1083 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1084 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1085 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1086 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1087 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1089 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1090 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1091 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1092 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1093 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1094 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1095 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1096 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1097 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1098 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1099 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1100 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1102 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1103 // even though v8i16 is a legal type.
1104 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1105 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1106 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1108 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1109 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1110 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1112 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1113 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1115 for (MVT VT : MVT::fp_vector_valuetypes())
1116 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1118 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1119 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1121 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1122 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1124 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1125 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1127 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1128 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1129 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1130 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1132 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1133 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1134 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1136 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1137 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1138 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1139 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1140 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1141 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1142 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1143 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1144 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1145 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1146 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1147 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1149 setOperationAction(ISD::CTPOP, MVT::v32i8, Custom);
1150 setOperationAction(ISD::CTPOP, MVT::v16i16, Custom);
1151 setOperationAction(ISD::CTPOP, MVT::v8i32, Custom);
1152 setOperationAction(ISD::CTPOP, MVT::v4i64, Custom);
1154 setOperationAction(ISD::CTTZ, MVT::v32i8, Custom);
1155 setOperationAction(ISD::CTTZ, MVT::v16i16, Custom);
1156 setOperationAction(ISD::CTTZ, MVT::v8i32, Custom);
1157 setOperationAction(ISD::CTTZ, MVT::v4i64, Custom);
1158 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v32i8, Custom);
1159 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i16, Custom);
1160 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i32, Custom);
1161 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i64, Custom);
1163 if (Subtarget->hasAnyFMA()) {
1164 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1165 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1166 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1167 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1168 setOperationAction(ISD::FMA, MVT::f32, Legal);
1169 setOperationAction(ISD::FMA, MVT::f64, Legal);
1172 if (Subtarget->hasInt256()) {
1173 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1174 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1175 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1176 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1178 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1179 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1180 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1181 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1183 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1184 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1185 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1186 setOperationAction(ISD::MUL, MVT::v32i8, Custom);
1188 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1189 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1190 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1191 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1193 setOperationAction(ISD::SMAX, MVT::v32i8, Legal);
1194 setOperationAction(ISD::SMAX, MVT::v16i16, Legal);
1195 setOperationAction(ISD::SMAX, MVT::v8i32, Legal);
1196 setOperationAction(ISD::UMAX, MVT::v32i8, Legal);
1197 setOperationAction(ISD::UMAX, MVT::v16i16, Legal);
1198 setOperationAction(ISD::UMAX, MVT::v8i32, Legal);
1199 setOperationAction(ISD::SMIN, MVT::v32i8, Legal);
1200 setOperationAction(ISD::SMIN, MVT::v16i16, Legal);
1201 setOperationAction(ISD::SMIN, MVT::v8i32, Legal);
1202 setOperationAction(ISD::UMIN, MVT::v32i8, Legal);
1203 setOperationAction(ISD::UMIN, MVT::v16i16, Legal);
1204 setOperationAction(ISD::UMIN, MVT::v8i32, Legal);
1206 // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1207 // when we have a 256bit-wide blend with immediate.
1208 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1210 // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1211 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1212 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1213 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1214 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1215 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1216 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1218 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1219 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1220 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1221 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1222 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1223 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1225 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1226 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1227 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1228 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1230 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1231 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1232 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1233 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1235 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1236 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1237 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1238 setOperationAction(ISD::MUL, MVT::v32i8, Custom);
1240 setOperationAction(ISD::SMAX, MVT::v32i8, Custom);
1241 setOperationAction(ISD::SMAX, MVT::v16i16, Custom);
1242 setOperationAction(ISD::SMAX, MVT::v8i32, Custom);
1243 setOperationAction(ISD::UMAX, MVT::v32i8, Custom);
1244 setOperationAction(ISD::UMAX, MVT::v16i16, Custom);
1245 setOperationAction(ISD::UMAX, MVT::v8i32, Custom);
1246 setOperationAction(ISD::SMIN, MVT::v32i8, Custom);
1247 setOperationAction(ISD::SMIN, MVT::v16i16, Custom);
1248 setOperationAction(ISD::SMIN, MVT::v8i32, Custom);
1249 setOperationAction(ISD::UMIN, MVT::v32i8, Custom);
1250 setOperationAction(ISD::UMIN, MVT::v16i16, Custom);
1251 setOperationAction(ISD::UMIN, MVT::v8i32, Custom);
1254 // In the customized shift lowering, the legal cases in AVX2 will be
1256 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1257 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1259 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1260 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1262 setOperationAction(ISD::SRA, MVT::v4i64, Custom);
1263 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1265 // Custom lower several nodes for 256-bit types.
1266 for (MVT VT : MVT::vector_valuetypes()) {
1267 if (VT.getScalarSizeInBits() >= 32) {
1268 setOperationAction(ISD::MLOAD, VT, Legal);
1269 setOperationAction(ISD::MSTORE, VT, Legal);
1271 // Extract subvector is special because the value type
1272 // (result) is 128-bit but the source is 256-bit wide.
1273 if (VT.is128BitVector()) {
1274 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1276 // Do not attempt to custom lower other non-256-bit vectors
1277 if (!VT.is256BitVector())
1280 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1281 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1282 setOperationAction(ISD::VSELECT, VT, Custom);
1283 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1284 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1285 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1286 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1287 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1290 if (Subtarget->hasInt256())
1291 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1293 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1294 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32 }) {
1295 setOperationAction(ISD::AND, VT, Promote);
1296 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1297 setOperationAction(ISD::OR, VT, Promote);
1298 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1299 setOperationAction(ISD::XOR, VT, Promote);
1300 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1301 setOperationAction(ISD::LOAD, VT, Promote);
1302 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1303 setOperationAction(ISD::SELECT, VT, Promote);
1304 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1308 if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1309 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1310 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1311 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1312 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1314 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1315 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1316 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1318 for (MVT VT : MVT::fp_vector_valuetypes())
1319 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1321 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1322 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1323 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1324 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1325 setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1326 setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1327 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64, MVT::v8i8, Legal);
1328 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64, MVT::v8i8, Legal);
1329 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64, MVT::v8i16, Legal);
1330 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64, MVT::v8i16, Legal);
1331 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64, MVT::v8i32, Legal);
1332 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64, MVT::v8i32, Legal);
1334 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1335 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1336 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
1337 setOperationAction(ISD::XOR, MVT::i1, Legal);
1338 setOperationAction(ISD::OR, MVT::i1, Legal);
1339 setOperationAction(ISD::AND, MVT::i1, Legal);
1340 setOperationAction(ISD::SUB, MVT::i1, Custom);
1341 setOperationAction(ISD::ADD, MVT::i1, Custom);
1342 setOperationAction(ISD::MUL, MVT::i1, Custom);
1343 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1344 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1345 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1346 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1347 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1349 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1350 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1351 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1352 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1353 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1354 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1355 setOperationAction(ISD::FABS, MVT::v16f32, Custom);
1357 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1358 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1359 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1360 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1361 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1362 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1363 setOperationAction(ISD::FABS, MVT::v8f64, Custom);
1364 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1365 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1367 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1368 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1369 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1370 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1371 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1372 setOperationAction(ISD::SINT_TO_FP, MVT::v8i1, Custom);
1373 setOperationAction(ISD::SINT_TO_FP, MVT::v16i1, Custom);
1374 setOperationAction(ISD::SINT_TO_FP, MVT::v16i8, Promote);
1375 setOperationAction(ISD::SINT_TO_FP, MVT::v16i16, Promote);
1376 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1377 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1378 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1379 setOperationAction(ISD::UINT_TO_FP, MVT::v16i8, Custom);
1380 setOperationAction(ISD::UINT_TO_FP, MVT::v16i16, Custom);
1381 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1382 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1384 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Legal);
1385 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Legal);
1386 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Legal);
1387 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Legal);
1388 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Legal);
1389 if (Subtarget->hasVLX()){
1390 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Legal);
1391 setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1392 setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1393 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Legal);
1394 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1396 setTruncStoreAction(MVT::v2i64, MVT::v2i8, Legal);
1397 setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1398 setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1399 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Legal);
1400 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1402 setOperationAction(ISD::MLOAD, MVT::v8i32, Custom);
1403 setOperationAction(ISD::MLOAD, MVT::v8f32, Custom);
1404 setOperationAction(ISD::MSTORE, MVT::v8i32, Custom);
1405 setOperationAction(ISD::MSTORE, MVT::v8f32, Custom);
1407 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1408 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1409 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1410 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i1, Custom);
1411 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i1, Custom);
1412 if (Subtarget->hasDQI()) {
1413 setOperationAction(ISD::TRUNCATE, MVT::v2i1, Custom);
1414 setOperationAction(ISD::TRUNCATE, MVT::v4i1, Custom);
1416 setOperationAction(ISD::SINT_TO_FP, MVT::v8i64, Legal);
1417 setOperationAction(ISD::UINT_TO_FP, MVT::v8i64, Legal);
1418 setOperationAction(ISD::FP_TO_SINT, MVT::v8i64, Legal);
1419 setOperationAction(ISD::FP_TO_UINT, MVT::v8i64, Legal);
1420 if (Subtarget->hasVLX()) {
1421 setOperationAction(ISD::SINT_TO_FP, MVT::v4i64, Legal);
1422 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
1423 setOperationAction(ISD::UINT_TO_FP, MVT::v4i64, Legal);
1424 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
1425 setOperationAction(ISD::FP_TO_SINT, MVT::v4i64, Legal);
1426 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
1427 setOperationAction(ISD::FP_TO_UINT, MVT::v4i64, Legal);
1428 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
1431 if (Subtarget->hasVLX()) {
1432 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1433 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1434 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1435 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1436 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1437 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1438 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1439 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1441 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1442 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1443 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1444 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1445 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1446 setOperationAction(ISD::ANY_EXTEND, MVT::v16i32, Custom);
1447 setOperationAction(ISD::ANY_EXTEND, MVT::v8i64, Custom);
1448 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1449 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1450 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1451 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1452 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1453 if (Subtarget->hasDQI()) {
1454 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Custom);
1455 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i64, Custom);
1457 setOperationAction(ISD::FFLOOR, MVT::v16f32, Legal);
1458 setOperationAction(ISD::FFLOOR, MVT::v8f64, Legal);
1459 setOperationAction(ISD::FCEIL, MVT::v16f32, Legal);
1460 setOperationAction(ISD::FCEIL, MVT::v8f64, Legal);
1461 setOperationAction(ISD::FTRUNC, MVT::v16f32, Legal);
1462 setOperationAction(ISD::FTRUNC, MVT::v8f64, Legal);
1463 setOperationAction(ISD::FRINT, MVT::v16f32, Legal);
1464 setOperationAction(ISD::FRINT, MVT::v8f64, Legal);
1465 setOperationAction(ISD::FNEARBYINT, MVT::v16f32, Legal);
1466 setOperationAction(ISD::FNEARBYINT, MVT::v8f64, Legal);
1468 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1469 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1470 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1471 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1472 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Custom);
1474 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1475 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1477 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1479 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1480 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1481 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v16i1, Custom);
1482 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1483 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1484 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1485 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1486 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1487 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1488 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1489 setOperationAction(ISD::SELECT, MVT::v16i1, Custom);
1490 setOperationAction(ISD::SELECT, MVT::v8i1, Custom);
1492 setOperationAction(ISD::SMAX, MVT::v16i32, Legal);
1493 setOperationAction(ISD::SMAX, MVT::v8i64, Legal);
1494 setOperationAction(ISD::UMAX, MVT::v16i32, Legal);
1495 setOperationAction(ISD::UMAX, MVT::v8i64, Legal);
1496 setOperationAction(ISD::SMIN, MVT::v16i32, Legal);
1497 setOperationAction(ISD::SMIN, MVT::v8i64, Legal);
1498 setOperationAction(ISD::UMIN, MVT::v16i32, Legal);
1499 setOperationAction(ISD::UMIN, MVT::v8i64, Legal);
1501 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1502 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1504 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1505 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1507 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1509 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1510 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1512 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1513 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1515 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1516 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1518 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1519 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1520 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1521 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1522 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1523 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1525 if (Subtarget->hasCDI()) {
1526 setOperationAction(ISD::CTLZ, MVT::v8i64, Legal);
1527 setOperationAction(ISD::CTLZ, MVT::v16i32, Legal);
1528 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v8i64, Legal);
1529 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v16i32, Legal);
1531 setOperationAction(ISD::CTLZ, MVT::v8i16, Custom);
1532 setOperationAction(ISD::CTLZ, MVT::v16i8, Custom);
1533 setOperationAction(ISD::CTLZ, MVT::v16i16, Custom);
1534 setOperationAction(ISD::CTLZ, MVT::v32i8, Custom);
1535 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v8i16, Custom);
1536 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v16i8, Custom);
1537 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v16i16, Custom);
1538 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v32i8, Custom);
1540 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i64, Custom);
1541 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i32, Custom);
1543 if (Subtarget->hasVLX()) {
1544 setOperationAction(ISD::CTLZ, MVT::v4i64, Legal);
1545 setOperationAction(ISD::CTLZ, MVT::v8i32, Legal);
1546 setOperationAction(ISD::CTLZ, MVT::v2i64, Legal);
1547 setOperationAction(ISD::CTLZ, MVT::v4i32, Legal);
1548 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v4i64, Legal);
1549 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v8i32, Legal);
1550 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v2i64, Legal);
1551 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v4i32, Legal);
1553 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i64, Custom);
1554 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i32, Custom);
1555 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
1556 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
1558 setOperationAction(ISD::CTLZ, MVT::v4i64, Custom);
1559 setOperationAction(ISD::CTLZ, MVT::v8i32, Custom);
1560 setOperationAction(ISD::CTLZ, MVT::v2i64, Custom);
1561 setOperationAction(ISD::CTLZ, MVT::v4i32, Custom);
1562 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v4i64, Custom);
1563 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v8i32, Custom);
1564 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v2i64, Custom);
1565 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v4i32, Custom);
1567 } // Subtarget->hasCDI()
1569 if (Subtarget->hasDQI()) {
1570 setOperationAction(ISD::MUL, MVT::v2i64, Legal);
1571 setOperationAction(ISD::MUL, MVT::v4i64, Legal);
1572 setOperationAction(ISD::MUL, MVT::v8i64, Legal);
1574 // Custom lower several nodes.
1575 for (MVT VT : MVT::vector_valuetypes()) {
1576 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1578 setOperationAction(ISD::AND, VT, Legal);
1579 setOperationAction(ISD::OR, VT, Legal);
1580 setOperationAction(ISD::XOR, VT, Legal);
1582 if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1583 setOperationAction(ISD::MGATHER, VT, Custom);
1584 setOperationAction(ISD::MSCATTER, VT, Custom);
1586 // Extract subvector is special because the value type
1587 // (result) is 256/128-bit but the source is 512-bit wide.
1588 if (VT.is128BitVector() || VT.is256BitVector()) {
1589 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1591 if (VT.getVectorElementType() == MVT::i1)
1592 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1594 // Do not attempt to custom lower other non-512-bit vectors
1595 if (!VT.is512BitVector())
1598 if (EltSize >= 32) {
1599 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1600 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1601 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1602 setOperationAction(ISD::VSELECT, VT, Legal);
1603 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1604 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1605 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1606 setOperationAction(ISD::MLOAD, VT, Legal);
1607 setOperationAction(ISD::MSTORE, VT, Legal);
1610 for (auto VT : { MVT::v64i8, MVT::v32i16, MVT::v16i32 }) {
1611 setOperationAction(ISD::SELECT, VT, Promote);
1612 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1616 if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1617 addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1618 addRegisterClass(MVT::v64i8, &X86::VR512RegClass);
1620 addRegisterClass(MVT::v32i1, &X86::VK32RegClass);
1621 addRegisterClass(MVT::v64i1, &X86::VK64RegClass);
1623 setOperationAction(ISD::LOAD, MVT::v32i16, Legal);
1624 setOperationAction(ISD::LOAD, MVT::v64i8, Legal);
1625 setOperationAction(ISD::SETCC, MVT::v32i1, Custom);
1626 setOperationAction(ISD::SETCC, MVT::v64i1, Custom);
1627 setOperationAction(ISD::ADD, MVT::v32i16, Legal);
1628 setOperationAction(ISD::ADD, MVT::v64i8, Legal);
1629 setOperationAction(ISD::SUB, MVT::v32i16, Legal);
1630 setOperationAction(ISD::SUB, MVT::v64i8, Legal);
1631 setOperationAction(ISD::MUL, MVT::v32i16, Legal);
1632 setOperationAction(ISD::MULHS, MVT::v32i16, Legal);
1633 setOperationAction(ISD::MULHU, MVT::v32i16, Legal);
1634 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i1, Custom);
1635 setOperationAction(ISD::CONCAT_VECTORS, MVT::v64i1, Custom);
1636 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i16, Custom);
1637 setOperationAction(ISD::CONCAT_VECTORS, MVT::v64i8, Custom);
1638 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v32i1, Custom);
1639 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v64i1, Custom);
1640 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v32i16, Custom);
1641 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v64i8, Custom);
1642 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v32i16, Custom);
1643 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v64i8, Custom);
1644 setOperationAction(ISD::SELECT, MVT::v32i1, Custom);
1645 setOperationAction(ISD::SELECT, MVT::v64i1, Custom);
1646 setOperationAction(ISD::SIGN_EXTEND, MVT::v32i8, Custom);
1647 setOperationAction(ISD::ZERO_EXTEND, MVT::v32i8, Custom);
1648 setOperationAction(ISD::SIGN_EXTEND, MVT::v32i16, Custom);
1649 setOperationAction(ISD::ZERO_EXTEND, MVT::v32i16, Custom);
1650 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v32i16, Custom);
1651 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v64i8, Custom);
1652 setOperationAction(ISD::SIGN_EXTEND, MVT::v64i8, Custom);
1653 setOperationAction(ISD::ZERO_EXTEND, MVT::v64i8, Custom);
1654 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v32i1, Custom);
1655 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v64i1, Custom);
1656 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v32i16, Custom);
1657 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v64i8, Custom);
1658 setOperationAction(ISD::VSELECT, MVT::v32i16, Legal);
1659 setOperationAction(ISD::VSELECT, MVT::v64i8, Legal);
1660 setOperationAction(ISD::TRUNCATE, MVT::v32i1, Custom);
1661 setOperationAction(ISD::TRUNCATE, MVT::v64i1, Custom);
1662 setOperationAction(ISD::TRUNCATE, MVT::v32i8, Custom);
1663 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v32i1, Custom);
1664 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v64i1, Custom);
1666 setOperationAction(ISD::SMAX, MVT::v64i8, Legal);
1667 setOperationAction(ISD::SMAX, MVT::v32i16, Legal);
1668 setOperationAction(ISD::UMAX, MVT::v64i8, Legal);
1669 setOperationAction(ISD::UMAX, MVT::v32i16, Legal);
1670 setOperationAction(ISD::SMIN, MVT::v64i8, Legal);
1671 setOperationAction(ISD::SMIN, MVT::v32i16, Legal);
1672 setOperationAction(ISD::UMIN, MVT::v64i8, Legal);
1673 setOperationAction(ISD::UMIN, MVT::v32i16, Legal);
1675 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Legal);
1676 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Legal);
1677 if (Subtarget->hasVLX())
1678 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Legal);
1680 if (Subtarget->hasCDI()) {
1681 setOperationAction(ISD::CTLZ, MVT::v32i16, Custom);
1682 setOperationAction(ISD::CTLZ, MVT::v64i8, Custom);
1683 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v32i16, Custom);
1684 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::v64i8, Custom);
1687 for (auto VT : { MVT::v64i8, MVT::v32i16 }) {
1688 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1689 setOperationAction(ISD::VSELECT, VT, Legal);
1693 if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1694 addRegisterClass(MVT::v4i1, &X86::VK4RegClass);
1695 addRegisterClass(MVT::v2i1, &X86::VK2RegClass);
1697 setOperationAction(ISD::SETCC, MVT::v4i1, Custom);
1698 setOperationAction(ISD::SETCC, MVT::v2i1, Custom);
1699 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i1, Custom);
1700 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1701 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i1, Custom);
1702 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i1, Custom);
1703 setOperationAction(ISD::SELECT, MVT::v4i1, Custom);
1704 setOperationAction(ISD::SELECT, MVT::v2i1, Custom);
1705 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
1706 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i1, Custom);
1707 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i1, Custom);
1708 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i1, Custom);
1710 setOperationAction(ISD::AND, MVT::v8i32, Legal);
1711 setOperationAction(ISD::OR, MVT::v8i32, Legal);
1712 setOperationAction(ISD::XOR, MVT::v8i32, Legal);
1713 setOperationAction(ISD::AND, MVT::v4i32, Legal);
1714 setOperationAction(ISD::OR, MVT::v4i32, Legal);
1715 setOperationAction(ISD::XOR, MVT::v4i32, Legal);
1716 setOperationAction(ISD::SRA, MVT::v2i64, Custom);
1717 setOperationAction(ISD::SRA, MVT::v4i64, Custom);
1719 setOperationAction(ISD::SMAX, MVT::v2i64, Legal);
1720 setOperationAction(ISD::SMAX, MVT::v4i64, Legal);
1721 setOperationAction(ISD::UMAX, MVT::v2i64, Legal);
1722 setOperationAction(ISD::UMAX, MVT::v4i64, Legal);
1723 setOperationAction(ISD::SMIN, MVT::v2i64, Legal);
1724 setOperationAction(ISD::SMIN, MVT::v4i64, Legal);
1725 setOperationAction(ISD::UMIN, MVT::v2i64, Legal);
1726 setOperationAction(ISD::UMIN, MVT::v4i64, Legal);
1729 // We want to custom lower some of our intrinsics.
1730 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1731 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1732 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1733 if (!Subtarget->is64Bit()) {
1734 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1735 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
1738 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1739 // handle type legalization for these operations here.
1741 // FIXME: We really should do custom legalization for addition and
1742 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1743 // than generic legalization for 64-bit multiplication-with-overflow, though.
1744 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
1745 if (VT == MVT::i64 && !Subtarget->is64Bit())
1747 // Add/Sub/Mul with overflow operations are custom lowered.
1748 setOperationAction(ISD::SADDO, VT, Custom);
1749 setOperationAction(ISD::UADDO, VT, Custom);
1750 setOperationAction(ISD::SSUBO, VT, Custom);
1751 setOperationAction(ISD::USUBO, VT, Custom);
1752 setOperationAction(ISD::SMULO, VT, Custom);
1753 setOperationAction(ISD::UMULO, VT, Custom);
1756 if (!Subtarget->is64Bit()) {
1757 // These libcalls are not available in 32-bit.
1758 setLibcallName(RTLIB::SHL_I128, nullptr);
1759 setLibcallName(RTLIB::SRL_I128, nullptr);
1760 setLibcallName(RTLIB::SRA_I128, nullptr);
1763 // Combine sin / cos into one node or libcall if possible.
1764 if (Subtarget->hasSinCos()) {
1765 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1766 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1767 if (Subtarget->isTargetDarwin()) {
1768 // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1769 // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1770 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1771 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1775 if (Subtarget->isTargetWin64()) {
1776 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1777 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1778 setOperationAction(ISD::SREM, MVT::i128, Custom);
1779 setOperationAction(ISD::UREM, MVT::i128, Custom);
1780 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1781 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1784 // We have target-specific dag combine patterns for the following nodes:
1785 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1786 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1787 setTargetDAGCombine(ISD::BITCAST);
1788 setTargetDAGCombine(ISD::VSELECT);
1789 setTargetDAGCombine(ISD::SELECT);
1790 setTargetDAGCombine(ISD::SHL);
1791 setTargetDAGCombine(ISD::SRA);
1792 setTargetDAGCombine(ISD::SRL);
1793 setTargetDAGCombine(ISD::OR);
1794 setTargetDAGCombine(ISD::AND);
1795 setTargetDAGCombine(ISD::ADD);
1796 setTargetDAGCombine(ISD::FADD);
1797 setTargetDAGCombine(ISD::FSUB);
1798 setTargetDAGCombine(ISD::FNEG);
1799 setTargetDAGCombine(ISD::FMA);
1800 setTargetDAGCombine(ISD::SUB);
1801 setTargetDAGCombine(ISD::LOAD);
1802 setTargetDAGCombine(ISD::MLOAD);
1803 setTargetDAGCombine(ISD::STORE);
1804 setTargetDAGCombine(ISD::MSTORE);
1805 setTargetDAGCombine(ISD::TRUNCATE);
1806 setTargetDAGCombine(ISD::ZERO_EXTEND);
1807 setTargetDAGCombine(ISD::ANY_EXTEND);
1808 setTargetDAGCombine(ISD::SIGN_EXTEND);
1809 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1810 setTargetDAGCombine(ISD::SINT_TO_FP);
1811 setTargetDAGCombine(ISD::UINT_TO_FP);
1812 setTargetDAGCombine(ISD::SETCC);
1813 setTargetDAGCombine(ISD::BUILD_VECTOR);
1814 setTargetDAGCombine(ISD::MUL);
1815 setTargetDAGCombine(ISD::XOR);
1817 computeRegisterProperties(Subtarget->getRegisterInfo());
1819 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1820 MaxStoresPerMemsetOptSize = 8;
1821 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1822 MaxStoresPerMemcpyOptSize = 4;
1823 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1824 MaxStoresPerMemmoveOptSize = 4;
1825 setPrefLoopAlignment(4); // 2^4 bytes.
1827 // A predictable cmov does not hurt on an in-order CPU.
1828 // FIXME: Use a CPU attribute to trigger this, not a CPU model.
1829 PredictableSelectIsExpensive = !Subtarget->isAtom();
1830 EnableExtLdPromotion = true;
1831 setPrefFunctionAlignment(4); // 2^4 bytes.
1833 verifyIntrinsicTables();
1836 // This has so far only been implemented for 64-bit MachO.
1837 bool X86TargetLowering::useLoadStackGuardNode() const {
1838 return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1841 TargetLoweringBase::LegalizeTypeAction
1842 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1843 if (ExperimentalVectorWideningLegalization &&
1844 VT.getVectorNumElements() != 1 &&
1845 VT.getVectorElementType().getSimpleVT() != MVT::i1)
1846 return TypeWidenVector;
1848 return TargetLoweringBase::getPreferredVectorAction(VT);
1851 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1854 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1856 if (VT.isSimple()) {
1857 MVT VVT = VT.getSimpleVT();
1858 const unsigned NumElts = VVT.getVectorNumElements();
1859 const MVT EltVT = VVT.getVectorElementType();
1860 if (VVT.is512BitVector()) {
1861 if (Subtarget->hasAVX512())
1862 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1863 EltVT == MVT::f32 || EltVT == MVT::f64)
1865 case 8: return MVT::v8i1;
1866 case 16: return MVT::v16i1;
1868 if (Subtarget->hasBWI())
1869 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1871 case 32: return MVT::v32i1;
1872 case 64: return MVT::v64i1;
1876 if (VVT.is256BitVector() || VVT.is128BitVector()) {
1877 if (Subtarget->hasVLX())
1878 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1879 EltVT == MVT::f32 || EltVT == MVT::f64)
1881 case 2: return MVT::v2i1;
1882 case 4: return MVT::v4i1;
1883 case 8: return MVT::v8i1;
1885 if (Subtarget->hasBWI() && Subtarget->hasVLX())
1886 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1888 case 8: return MVT::v8i1;
1889 case 16: return MVT::v16i1;
1890 case 32: return MVT::v32i1;
1895 return VT.changeVectorElementTypeToInteger();
1898 /// Helper for getByValTypeAlignment to determine
1899 /// the desired ByVal argument alignment.
1900 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1903 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1904 if (VTy->getBitWidth() == 128)
1906 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1907 unsigned EltAlign = 0;
1908 getMaxByValAlign(ATy->getElementType(), EltAlign);
1909 if (EltAlign > MaxAlign)
1910 MaxAlign = EltAlign;
1911 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1912 for (auto *EltTy : STy->elements()) {
1913 unsigned EltAlign = 0;
1914 getMaxByValAlign(EltTy, EltAlign);
1915 if (EltAlign > MaxAlign)
1916 MaxAlign = EltAlign;
1923 /// Return the desired alignment for ByVal aggregate
1924 /// function arguments in the caller parameter area. For X86, aggregates
1925 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1926 /// are at 4-byte boundaries.
1927 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1928 const DataLayout &DL) const {
1929 if (Subtarget->is64Bit()) {
1930 // Max of 8 and alignment of type.
1931 unsigned TyAlign = DL.getABITypeAlignment(Ty);
1938 if (Subtarget->hasSSE1())
1939 getMaxByValAlign(Ty, Align);
1943 /// Returns the target specific optimal type for load
1944 /// and store operations as a result of memset, memcpy, and memmove
1945 /// lowering. If DstAlign is zero that means it's safe to destination
1946 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1947 /// means there isn't a need to check it against alignment requirement,
1948 /// probably because the source does not need to be loaded. If 'IsMemset' is
1949 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1950 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1951 /// source is constant so it does not need to be loaded.
1952 /// It returns EVT::Other if the type should be determined using generic
1953 /// target-independent logic.
1955 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1956 unsigned DstAlign, unsigned SrcAlign,
1957 bool IsMemset, bool ZeroMemset,
1959 MachineFunction &MF) const {
1960 const Function *F = MF.getFunction();
1961 if ((!IsMemset || ZeroMemset) &&
1962 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1964 (!Subtarget->isUnalignedMem16Slow() ||
1965 ((DstAlign == 0 || DstAlign >= 16) &&
1966 (SrcAlign == 0 || SrcAlign >= 16)))) {
1968 // FIXME: Check if unaligned 32-byte accesses are slow.
1969 if (Subtarget->hasInt256())
1971 if (Subtarget->hasFp256())
1974 if (Subtarget->hasSSE2())
1976 if (Subtarget->hasSSE1())
1978 } else if (!MemcpyStrSrc && Size >= 8 &&
1979 !Subtarget->is64Bit() &&
1980 Subtarget->hasSSE2()) {
1981 // Do not use f64 to lower memcpy if source is string constant. It's
1982 // better to use i32 to avoid the loads.
1986 // This is a compromise. If we reach here, unaligned accesses may be slow on
1987 // this target. However, creating smaller, aligned accesses could be even
1988 // slower and would certainly be a lot more code.
1989 if (Subtarget->is64Bit() && Size >= 8)
1994 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1996 return X86ScalarSSEf32;
1997 else if (VT == MVT::f64)
1998 return X86ScalarSSEf64;
2003 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
2008 switch (VT.getSizeInBits()) {
2010 // 8-byte and under are always assumed to be fast.
2014 *Fast = !Subtarget->isUnalignedMem16Slow();
2017 *Fast = !Subtarget->isUnalignedMem32Slow();
2019 // TODO: What about AVX-512 (512-bit) accesses?
2022 // Misaligned accesses of any size are always allowed.
2026 /// Return the entry encoding for a jump table in the
2027 /// current function. The returned value is a member of the
2028 /// MachineJumpTableInfo::JTEntryKind enum.
2029 unsigned X86TargetLowering::getJumpTableEncoding() const {
2030 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
2032 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2033 Subtarget->isPICStyleGOT())
2034 return MachineJumpTableInfo::EK_Custom32;
2036 // Otherwise, use the normal jump table encoding heuristics.
2037 return TargetLowering::getJumpTableEncoding();
2040 bool X86TargetLowering::useSoftFloat() const {
2041 return Subtarget->useSoftFloat();
2045 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
2046 const MachineBasicBlock *MBB,
2047 unsigned uid,MCContext &Ctx) const{
2048 assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
2049 Subtarget->isPICStyleGOT());
2050 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
2052 return MCSymbolRefExpr::create(MBB->getSymbol(),
2053 MCSymbolRefExpr::VK_GOTOFF, Ctx);
2056 /// Returns relocation base for the given PIC jumptable.
2057 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
2058 SelectionDAG &DAG) const {
2059 if (!Subtarget->is64Bit())
2060 // This doesn't have SDLoc associated with it, but is not really the
2061 // same as a Register.
2062 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
2063 getPointerTy(DAG.getDataLayout()));
2067 /// This returns the relocation base for the given PIC jumptable,
2068 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
2069 const MCExpr *X86TargetLowering::
2070 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
2071 MCContext &Ctx) const {
2072 // X86-64 uses RIP relative addressing based on the jump table label.
2073 if (Subtarget->isPICStyleRIPRel())
2074 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2076 // Otherwise, the reference is relative to the PIC base.
2077 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2080 std::pair<const TargetRegisterClass *, uint8_t>
2081 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
2083 const TargetRegisterClass *RRC = nullptr;
2085 switch (VT.SimpleTy) {
2087 return TargetLowering::findRepresentativeClass(TRI, VT);
2088 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
2089 RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
2092 RRC = &X86::VR64RegClass;
2094 case MVT::f32: case MVT::f64:
2095 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
2096 case MVT::v4f32: case MVT::v2f64:
2097 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
2099 RRC = &X86::VR128RegClass;
2102 return std::make_pair(RRC, Cost);
2105 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
2106 unsigned &Offset) const {
2107 if (!Subtarget->isTargetLinux())
2110 if (Subtarget->is64Bit()) {
2111 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
2113 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2125 Value *X86TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
2126 if (!Subtarget->isTargetAndroid())
2127 return TargetLowering::getSafeStackPointerLocation(IRB);
2129 // Android provides a fixed TLS slot for the SafeStack pointer. See the
2130 // definition of TLS_SLOT_SAFESTACK in
2131 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
2132 unsigned AddressSpace, Offset;
2133 if (Subtarget->is64Bit()) {
2134 // %fs:0x48, unless we're using a Kernel code model, in which case it's %gs:
2136 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2146 return ConstantExpr::getIntToPtr(
2147 ConstantInt::get(Type::getInt32Ty(IRB.getContext()), Offset),
2148 Type::getInt8PtrTy(IRB.getContext())->getPointerTo(AddressSpace));
2151 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2152 unsigned DestAS) const {
2153 assert(SrcAS != DestAS && "Expected different address spaces!");
2155 return SrcAS < 256 && DestAS < 256;
2158 //===----------------------------------------------------------------------===//
2159 // Return Value Calling Convention Implementation
2160 //===----------------------------------------------------------------------===//
2162 #include "X86GenCallingConv.inc"
2164 bool X86TargetLowering::CanLowerReturn(
2165 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2166 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2167 SmallVector<CCValAssign, 16> RVLocs;
2168 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2169 return CCInfo.CheckReturn(Outs, RetCC_X86);
2172 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2173 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2178 X86TargetLowering::LowerReturn(SDValue Chain,
2179 CallingConv::ID CallConv, bool isVarArg,
2180 const SmallVectorImpl<ISD::OutputArg> &Outs,
2181 const SmallVectorImpl<SDValue> &OutVals,
2182 SDLoc dl, SelectionDAG &DAG) const {
2183 MachineFunction &MF = DAG.getMachineFunction();
2184 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2186 SmallVector<CCValAssign, 16> RVLocs;
2187 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2188 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2191 SmallVector<SDValue, 6> RetOps;
2192 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2193 // Operand #1 = Bytes To Pop
2194 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2197 // Copy the result values into the output registers.
2198 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2199 CCValAssign &VA = RVLocs[i];
2200 assert(VA.isRegLoc() && "Can only return in registers!");
2201 SDValue ValToCopy = OutVals[i];
2202 EVT ValVT = ValToCopy.getValueType();
2204 // Promote values to the appropriate types.
2205 if (VA.getLocInfo() == CCValAssign::SExt)
2206 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2207 else if (VA.getLocInfo() == CCValAssign::ZExt)
2208 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2209 else if (VA.getLocInfo() == CCValAssign::AExt) {
2210 if (ValVT.isVector() && ValVT.getVectorElementType() == MVT::i1)
2211 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2213 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2215 else if (VA.getLocInfo() == CCValAssign::BCvt)
2216 ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2218 assert(VA.getLocInfo() != CCValAssign::FPExt &&
2219 "Unexpected FP-extend for return value.");
2221 // If this is x86-64, and we disabled SSE, we can't return FP values,
2222 // or SSE or MMX vectors.
2223 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2224 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2225 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2226 report_fatal_error("SSE register return with SSE disabled");
2228 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
2229 // llvm-gcc has never done it right and no one has noticed, so this
2230 // should be OK for now.
2231 if (ValVT == MVT::f64 &&
2232 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2233 report_fatal_error("SSE2 register return with SSE2 disabled");
2235 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2236 // the RET instruction and handled by the FP Stackifier.
2237 if (VA.getLocReg() == X86::FP0 ||
2238 VA.getLocReg() == X86::FP1) {
2239 // If this is a copy from an xmm register to ST(0), use an FPExtend to
2240 // change the value to the FP stack register class.
2241 if (isScalarFPTypeInSSEReg(VA.getValVT()))
2242 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2243 RetOps.push_back(ValToCopy);
2244 // Don't emit a copytoreg.
2248 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2249 // which is returned in RAX / RDX.
2250 if (Subtarget->is64Bit()) {
2251 if (ValVT == MVT::x86mmx) {
2252 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2253 ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2254 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2256 // If we don't have SSE2 available, convert to v4f32 so the generated
2257 // register is legal.
2258 if (!Subtarget->hasSSE2())
2259 ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2264 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2265 Flag = Chain.getValue(1);
2266 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2269 // All x86 ABIs require that for returning structs by value we copy
2270 // the sret argument into %rax/%eax (depending on ABI) for the return.
2271 // We saved the argument into a virtual register in the entry block,
2272 // so now we copy the value out and into %rax/%eax.
2274 // Checking Function.hasStructRetAttr() here is insufficient because the IR
2275 // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2276 // false, then an sret argument may be implicitly inserted in the SelDAG. In
2277 // either case FuncInfo->setSRetReturnReg() will have been called.
2278 if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2279 SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2280 getPointerTy(MF.getDataLayout()));
2283 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2284 X86::RAX : X86::EAX;
2285 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2286 Flag = Chain.getValue(1);
2288 // RAX/EAX now acts like a return value.
2290 DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2293 RetOps[0] = Chain; // Update chain.
2295 // Add the flag if we have it.
2297 RetOps.push_back(Flag);
2299 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2302 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2303 if (N->getNumValues() != 1)
2305 if (!N->hasNUsesOfValue(1, 0))
2308 SDValue TCChain = Chain;
2309 SDNode *Copy = *N->use_begin();
2310 if (Copy->getOpcode() == ISD::CopyToReg) {
2311 // If the copy has a glue operand, we conservatively assume it isn't safe to
2312 // perform a tail call.
2313 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2315 TCChain = Copy->getOperand(0);
2316 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2319 bool HasRet = false;
2320 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2322 if (UI->getOpcode() != X86ISD::RET_FLAG)
2324 // If we are returning more than one value, we can definitely
2325 // not make a tail call see PR19530
2326 if (UI->getNumOperands() > 4)
2328 if (UI->getNumOperands() == 4 &&
2329 UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2342 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2343 ISD::NodeType ExtendKind) const {
2345 // TODO: Is this also valid on 32-bit?
2346 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2347 ReturnMVT = MVT::i8;
2349 ReturnMVT = MVT::i32;
2351 EVT MinVT = getRegisterType(Context, ReturnMVT);
2352 return VT.bitsLT(MinVT) ? MinVT : VT;
2355 /// Lower the result values of a call into the
2356 /// appropriate copies out of appropriate physical registers.
2359 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2360 CallingConv::ID CallConv, bool isVarArg,
2361 const SmallVectorImpl<ISD::InputArg> &Ins,
2362 SDLoc dl, SelectionDAG &DAG,
2363 SmallVectorImpl<SDValue> &InVals) const {
2365 // Assign locations to each value returned by this call.
2366 SmallVector<CCValAssign, 16> RVLocs;
2367 bool Is64Bit = Subtarget->is64Bit();
2368 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2370 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2372 // Copy all of the result registers out of their specified physreg.
2373 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2374 CCValAssign &VA = RVLocs[i];
2375 EVT CopyVT = VA.getLocVT();
2377 // If this is x86-64, and we disabled SSE, we can't return FP values
2378 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64 || CopyVT == MVT::f128) &&
2379 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2380 report_fatal_error("SSE register return with SSE disabled");
2383 // If we prefer to use the value in xmm registers, copy it out as f80 and
2384 // use a truncate to move it from fp stack reg to xmm reg.
2385 bool RoundAfterCopy = false;
2386 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2387 isScalarFPTypeInSSEReg(VA.getValVT())) {
2389 RoundAfterCopy = (CopyVT != VA.getLocVT());
2392 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2393 CopyVT, InFlag).getValue(1);
2394 SDValue Val = Chain.getValue(0);
2397 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2398 // This truncation won't change the value.
2399 DAG.getIntPtrConstant(1, dl));
2401 if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2402 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2404 InFlag = Chain.getValue(2);
2405 InVals.push_back(Val);
2411 //===----------------------------------------------------------------------===//
2412 // C & StdCall & Fast Calling Convention implementation
2413 //===----------------------------------------------------------------------===//
2414 // StdCall calling convention seems to be standard for many Windows' API
2415 // routines and around. It differs from C calling convention just a little:
2416 // callee should clean up the stack, not caller. Symbols should be also
2417 // decorated in some fancy way :) It doesn't support any vector arguments.
2418 // For info on fast calling convention see Fast Calling Convention (tail call)
2419 // implementation LowerX86_32FastCCCallTo.
2421 /// CallIsStructReturn - Determines whether a call uses struct return
2423 enum StructReturnType {
2428 static StructReturnType
2429 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2431 return NotStructReturn;
2433 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2434 if (!Flags.isSRet())
2435 return NotStructReturn;
2436 if (Flags.isInReg())
2437 return RegStructReturn;
2438 return StackStructReturn;
2441 /// Determines whether a function uses struct return semantics.
2442 static StructReturnType
2443 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2445 return NotStructReturn;
2447 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2448 if (!Flags.isSRet())
2449 return NotStructReturn;
2450 if (Flags.isInReg())
2451 return RegStructReturn;
2452 return StackStructReturn;
2455 /// Make a copy of an aggregate at address specified by "Src" to address
2456 /// "Dst" with size and alignment information specified by the specific
2457 /// parameter attribute. The copy will be passed as a byval function parameter.
2459 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2460 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2462 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2464 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2465 /*isVolatile*/false, /*AlwaysInline=*/true,
2466 /*isTailCall*/false,
2467 MachinePointerInfo(), MachinePointerInfo());
2470 /// Return true if the calling convention is one that we can guarantee TCO for.
2471 static bool canGuaranteeTCO(CallingConv::ID CC) {
2472 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2473 CC == CallingConv::HiPE || CC == CallingConv::HHVM);
2476 /// Return true if we might ever do TCO for calls with this calling convention.
2477 static bool mayTailCallThisCC(CallingConv::ID CC) {
2479 // C calling conventions:
2480 case CallingConv::C:
2481 case CallingConv::X86_64_Win64:
2482 case CallingConv::X86_64_SysV:
2483 // Callee pop conventions:
2484 case CallingConv::X86_ThisCall:
2485 case CallingConv::X86_StdCall:
2486 case CallingConv::X86_VectorCall:
2487 case CallingConv::X86_FastCall:
2490 return canGuaranteeTCO(CC);
2494 /// Return true if the function is being made into a tailcall target by
2495 /// changing its ABI.
2496 static bool shouldGuaranteeTCO(CallingConv::ID CC, bool GuaranteedTailCallOpt) {
2497 return GuaranteedTailCallOpt && canGuaranteeTCO(CC);
2500 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2502 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2503 if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2507 CallingConv::ID CalleeCC = CS.getCallingConv();
2508 if (!mayTailCallThisCC(CalleeCC))
2515 X86TargetLowering::LowerMemArgument(SDValue Chain,
2516 CallingConv::ID CallConv,
2517 const SmallVectorImpl<ISD::InputArg> &Ins,
2518 SDLoc dl, SelectionDAG &DAG,
2519 const CCValAssign &VA,
2520 MachineFrameInfo *MFI,
2522 // Create the nodes corresponding to a load from this parameter slot.
2523 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2524 bool AlwaysUseMutable = shouldGuaranteeTCO(
2525 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2526 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2529 // If value is passed by pointer we have address passed instead of the value
2531 bool ExtendedInMem = VA.isExtInLoc() &&
2532 VA.getValVT().getScalarType() == MVT::i1;
2534 if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2535 ValVT = VA.getLocVT();
2537 ValVT = VA.getValVT();
2539 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2540 // changed with more analysis.
2541 // In case of tail call optimization mark all arguments mutable. Since they
2542 // could be overwritten by lowering of arguments in case of a tail call.
2543 if (Flags.isByVal()) {
2544 unsigned Bytes = Flags.getByValSize();
2545 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2546 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2547 return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2549 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2550 VA.getLocMemOffset(), isImmutable);
2551 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2552 SDValue Val = DAG.getLoad(
2553 ValVT, dl, Chain, FIN,
2554 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false,
2556 return ExtendedInMem ?
2557 DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2561 // FIXME: Get this from tablegen.
2562 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2563 const X86Subtarget *Subtarget) {
2564 assert(Subtarget->is64Bit());
2566 if (Subtarget->isCallingConvWin64(CallConv)) {
2567 static const MCPhysReg GPR64ArgRegsWin64[] = {
2568 X86::RCX, X86::RDX, X86::R8, X86::R9
2570 return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2573 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2574 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2576 return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2579 // FIXME: Get this from tablegen.
2580 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2581 CallingConv::ID CallConv,
2582 const X86Subtarget *Subtarget) {
2583 assert(Subtarget->is64Bit());
2584 if (Subtarget->isCallingConvWin64(CallConv)) {
2585 // The XMM registers which might contain var arg parameters are shadowed
2586 // in their paired GPR. So we only need to save the GPR to their home
2588 // TODO: __vectorcall will change this.
2592 const Function *Fn = MF.getFunction();
2593 bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2594 bool isSoftFloat = Subtarget->useSoftFloat();
2595 assert(!(isSoftFloat && NoImplicitFloatOps) &&
2596 "SSE register cannot be used when SSE is disabled!");
2597 if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2598 // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2602 static const MCPhysReg XMMArgRegs64Bit[] = {
2603 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2604 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2606 return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2609 SDValue X86TargetLowering::LowerFormalArguments(
2610 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2611 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc dl, SelectionDAG &DAG,
2612 SmallVectorImpl<SDValue> &InVals) const {
2613 MachineFunction &MF = DAG.getMachineFunction();
2614 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2615 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2617 const Function* Fn = MF.getFunction();
2618 if (Fn->hasExternalLinkage() &&
2619 Subtarget->isTargetCygMing() &&
2620 Fn->getName() == "main")
2621 FuncInfo->setForceFramePointer(true);
2623 MachineFrameInfo *MFI = MF.getFrameInfo();
2624 bool Is64Bit = Subtarget->is64Bit();
2625 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2627 assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
2628 "Var args not supported with calling convention fastcc, ghc or hipe");
2630 // Assign locations to all of the incoming arguments.
2631 SmallVector<CCValAssign, 16> ArgLocs;
2632 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2634 // Allocate shadow area for Win64
2636 CCInfo.AllocateStack(32, 8);
2638 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2640 unsigned LastVal = ~0U;
2642 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2643 CCValAssign &VA = ArgLocs[i];
2644 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2646 assert(VA.getValNo() != LastVal &&
2647 "Don't support value assigned to multiple locs yet");
2649 LastVal = VA.getValNo();
2651 if (VA.isRegLoc()) {
2652 EVT RegVT = VA.getLocVT();
2653 const TargetRegisterClass *RC;
2654 if (RegVT == MVT::i32)
2655 RC = &X86::GR32RegClass;
2656 else if (Is64Bit && RegVT == MVT::i64)
2657 RC = &X86::GR64RegClass;
2658 else if (RegVT == MVT::f32)
2659 RC = &X86::FR32RegClass;
2660 else if (RegVT == MVT::f64)
2661 RC = &X86::FR64RegClass;
2662 else if (RegVT == MVT::f128)
2663 RC = &X86::FR128RegClass;
2664 else if (RegVT.is512BitVector())
2665 RC = &X86::VR512RegClass;
2666 else if (RegVT.is256BitVector())
2667 RC = &X86::VR256RegClass;
2668 else if (RegVT.is128BitVector())
2669 RC = &X86::VR128RegClass;
2670 else if (RegVT == MVT::x86mmx)
2671 RC = &X86::VR64RegClass;
2672 else if (RegVT == MVT::i1)
2673 RC = &X86::VK1RegClass;
2674 else if (RegVT == MVT::v8i1)
2675 RC = &X86::VK8RegClass;
2676 else if (RegVT == MVT::v16i1)
2677 RC = &X86::VK16RegClass;
2678 else if (RegVT == MVT::v32i1)
2679 RC = &X86::VK32RegClass;
2680 else if (RegVT == MVT::v64i1)
2681 RC = &X86::VK64RegClass;
2683 llvm_unreachable("Unknown argument type!");
2685 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2686 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2688 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2689 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2691 if (VA.getLocInfo() == CCValAssign::SExt)
2692 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2693 DAG.getValueType(VA.getValVT()));
2694 else if (VA.getLocInfo() == CCValAssign::ZExt)
2695 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2696 DAG.getValueType(VA.getValVT()));
2697 else if (VA.getLocInfo() == CCValAssign::BCvt)
2698 ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2700 if (VA.isExtInLoc()) {
2701 // Handle MMX values passed in XMM regs.
2702 if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2703 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2705 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2708 assert(VA.isMemLoc());
2709 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2712 // If value is passed via pointer - do a load.
2713 if (VA.getLocInfo() == CCValAssign::Indirect)
2714 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2715 MachinePointerInfo(), false, false, false, 0);
2717 InVals.push_back(ArgValue);
2720 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2721 // All x86 ABIs require that for returning structs by value we copy the
2722 // sret argument into %rax/%eax (depending on ABI) for the return. Save
2723 // the argument into a virtual register so that we can access it from the
2725 if (Ins[i].Flags.isSRet()) {
2726 unsigned Reg = FuncInfo->getSRetReturnReg();
2728 MVT PtrTy = getPointerTy(DAG.getDataLayout());
2729 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2730 FuncInfo->setSRetReturnReg(Reg);
2732 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2733 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2738 unsigned StackSize = CCInfo.getNextStackOffset();
2739 // Align stack specially for tail calls.
2740 if (shouldGuaranteeTCO(CallConv,
2741 MF.getTarget().Options.GuaranteedTailCallOpt))
2742 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2744 // If the function takes variable number of arguments, make a frame index for
2745 // the start of the first vararg value... for expansion of llvm.va_start. We
2746 // can skip this if there are no va_start calls.
2747 if (MFI->hasVAStart() &&
2748 (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2749 CallConv != CallingConv::X86_ThisCall))) {
2750 FuncInfo->setVarArgsFrameIndex(
2751 MFI->CreateFixedObject(1, StackSize, true));
2754 // Figure out if XMM registers are in use.
2755 assert(!(Subtarget->useSoftFloat() &&
2756 Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2757 "SSE register cannot be used when SSE is disabled!");
2759 // 64-bit calling conventions support varargs and register parameters, so we
2760 // have to do extra work to spill them in the prologue.
2761 if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2762 // Find the first unallocated argument registers.
2763 ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2764 ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2765 unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2766 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2767 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2768 "SSE register cannot be used when SSE is disabled!");
2770 // Gather all the live in physical registers.
2771 SmallVector<SDValue, 6> LiveGPRs;
2772 SmallVector<SDValue, 8> LiveXMMRegs;
2774 for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2775 unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2777 DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2779 if (!ArgXMMs.empty()) {
2780 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2781 ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2782 for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2783 unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2784 LiveXMMRegs.push_back(
2785 DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2790 // Get to the caller-allocated home save location. Add 8 to account
2791 // for the return address.
2792 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2793 FuncInfo->setRegSaveFrameIndex(
2794 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2795 // Fixup to set vararg frame on shadow area (4 x i64).
2797 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2799 // For X86-64, if there are vararg parameters that are passed via
2800 // registers, then we must store them to their spots on the stack so
2801 // they may be loaded by deferencing the result of va_next.
2802 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2803 FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2804 FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2805 ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2808 // Store the integer parameter registers.
2809 SmallVector<SDValue, 8> MemOps;
2810 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2811 getPointerTy(DAG.getDataLayout()));
2812 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2813 for (SDValue Val : LiveGPRs) {
2814 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2815 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2817 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2818 MachinePointerInfo::getFixedStack(
2819 DAG.getMachineFunction(),
2820 FuncInfo->getRegSaveFrameIndex(), Offset),
2822 MemOps.push_back(Store);
2826 if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2827 // Now store the XMM (fp + vector) parameter registers.
2828 SmallVector<SDValue, 12> SaveXMMOps;
2829 SaveXMMOps.push_back(Chain);
2830 SaveXMMOps.push_back(ALVal);
2831 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2832 FuncInfo->getRegSaveFrameIndex(), dl));
2833 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2834 FuncInfo->getVarArgsFPOffset(), dl));
2835 SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2837 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2838 MVT::Other, SaveXMMOps));
2841 if (!MemOps.empty())
2842 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2845 if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2846 // Find the largest legal vector type.
2847 MVT VecVT = MVT::Other;
2848 // FIXME: Only some x86_32 calling conventions support AVX512.
2849 if (Subtarget->hasAVX512() &&
2850 (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2851 CallConv == CallingConv::Intel_OCL_BI)))
2852 VecVT = MVT::v16f32;
2853 else if (Subtarget->hasAVX())
2855 else if (Subtarget->hasSSE2())
2858 // We forward some GPRs and some vector types.
2859 SmallVector<MVT, 2> RegParmTypes;
2860 MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2861 RegParmTypes.push_back(IntVT);
2862 if (VecVT != MVT::Other)
2863 RegParmTypes.push_back(VecVT);
2865 // Compute the set of forwarded registers. The rest are scratch.
2866 SmallVectorImpl<ForwardedRegister> &Forwards =
2867 FuncInfo->getForwardedMustTailRegParms();
2868 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2870 // Conservatively forward AL on x86_64, since it might be used for varargs.
2871 if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2872 unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2873 Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2876 // Copy all forwards from physical to virtual registers.
2877 for (ForwardedRegister &F : Forwards) {
2878 // FIXME: Can we use a less constrained schedule?
2879 SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2880 F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2881 Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2885 // Some CCs need callee pop.
2886 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2887 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2888 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2890 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2891 // If this is an sret function, the return should pop the hidden pointer.
2892 if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
2893 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2894 argsAreStructReturn(Ins) == StackStructReturn)
2895 FuncInfo->setBytesToPopOnReturn(4);
2899 // RegSaveFrameIndex is X86-64 only.
2900 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2901 if (CallConv == CallingConv::X86_FastCall ||
2902 CallConv == CallingConv::X86_ThisCall)
2903 // fastcc functions can't have varargs.
2904 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2907 FuncInfo->setArgumentStackSize(StackSize);
2909 if (WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo()) {
2910 EHPersonality Personality = classifyEHPersonality(Fn->getPersonalityFn());
2911 if (Personality == EHPersonality::CoreCLR) {
2913 // TODO: Add a mechanism to frame lowering that will allow us to indicate
2914 // that we'd prefer this slot be allocated towards the bottom of the frame
2915 // (i.e. near the stack pointer after allocating the frame). Every
2916 // funclet needs a copy of this slot in its (mostly empty) frame, and the
2917 // offset from the bottom of this and each funclet's frame must be the
2918 // same, so the size of funclets' (mostly empty) frames is dictated by
2919 // how far this slot is from the bottom (since they allocate just enough
2920 // space to accomodate holding this slot at the correct offset).
2921 int PSPSymFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2922 EHInfo->PSPSymFrameIdx = PSPSymFI;
2930 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2931 SDValue StackPtr, SDValue Arg,
2932 SDLoc dl, SelectionDAG &DAG,
2933 const CCValAssign &VA,
2934 ISD::ArgFlagsTy Flags) const {
2935 unsigned LocMemOffset = VA.getLocMemOffset();
2936 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2937 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2939 if (Flags.isByVal())
2940 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2942 return DAG.getStore(
2943 Chain, dl, Arg, PtrOff,
2944 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset),
2948 /// Emit a load of return address if tail call
2949 /// optimization is performed and it is required.
2951 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2952 SDValue &OutRetAddr, SDValue Chain,
2953 bool IsTailCall, bool Is64Bit,
2954 int FPDiff, SDLoc dl) const {
2955 // Adjust the Return address stack slot.
2956 EVT VT = getPointerTy(DAG.getDataLayout());
2957 OutRetAddr = getReturnAddressFrameIndex(DAG);
2959 // Load the "old" Return address.
2960 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2961 false, false, false, 0);
2962 return SDValue(OutRetAddr.getNode(), 1);
2965 /// Emit a store of the return address if tail call
2966 /// optimization is performed and it is required (FPDiff!=0).
2967 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2968 SDValue Chain, SDValue RetAddrFrIdx,
2969 EVT PtrVT, unsigned SlotSize,
2970 int FPDiff, SDLoc dl) {
2971 // Store the return address to the appropriate stack slot.
2972 if (!FPDiff) return Chain;
2973 // Calculate the new stack slot for the return address.
2974 int NewReturnAddrFI =
2975 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2977 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2978 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2979 MachinePointerInfo::getFixedStack(
2980 DAG.getMachineFunction(), NewReturnAddrFI),
2985 /// Returns a vector_shuffle mask for an movs{s|d}, movd
2986 /// operation of specified width.
2987 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
2989 unsigned NumElems = VT.getVectorNumElements();
2990 SmallVector<int, 8> Mask;
2991 Mask.push_back(NumElems);
2992 for (unsigned i = 1; i != NumElems; ++i)
2994 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2998 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2999 SmallVectorImpl<SDValue> &InVals) const {
3000 SelectionDAG &DAG = CLI.DAG;
3002 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3003 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
3004 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
3005 SDValue Chain = CLI.Chain;
3006 SDValue Callee = CLI.Callee;
3007 CallingConv::ID CallConv = CLI.CallConv;
3008 bool &isTailCall = CLI.IsTailCall;
3009 bool isVarArg = CLI.IsVarArg;
3011 MachineFunction &MF = DAG.getMachineFunction();
3012 bool Is64Bit = Subtarget->is64Bit();
3013 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
3014 StructReturnType SR = callIsStructReturn(Outs);
3015 bool IsSibcall = false;
3016 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
3017 auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
3019 if (Attr.getValueAsString() == "true")
3022 if (Subtarget->isPICStyleGOT() &&
3023 !MF.getTarget().Options.GuaranteedTailCallOpt) {
3024 // If we are using a GOT, disable tail calls to external symbols with
3025 // default visibility. Tail calling such a symbol requires using a GOT
3026 // relocation, which forces early binding of the symbol. This breaks code
3027 // that require lazy function symbol resolution. Using musttail or
3028 // GuaranteedTailCallOpt will override this.
3029 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3030 if (!G || (!G->getGlobal()->hasLocalLinkage() &&
3031 G->getGlobal()->hasDefaultVisibility()))
3035 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
3037 // Force this to be a tail call. The verifier rules are enough to ensure
3038 // that we can lower this successfully without moving the return address
3041 } else if (isTailCall) {
3042 // Check if it's really possible to do a tail call.
3043 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
3044 isVarArg, SR != NotStructReturn,
3045 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
3046 Outs, OutVals, Ins, DAG);
3048 // Sibcalls are automatically detected tailcalls which do not require
3050 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
3057 assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
3058 "Var args not supported with calling convention fastcc, ghc or hipe");
3060 // Analyze operands of the call, assigning locations to each operand.
3061 SmallVector<CCValAssign, 16> ArgLocs;
3062 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
3064 // Allocate shadow area for Win64
3066 CCInfo.AllocateStack(32, 8);
3068 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3070 // Get a count of how many bytes are to be pushed on the stack.
3071 unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
3073 // This is a sibcall. The memory operands are available in caller's
3074 // own caller's stack.
3076 else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
3077 canGuaranteeTCO(CallConv))
3078 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
3081 if (isTailCall && !IsSibcall && !IsMustTail) {
3082 // Lower arguments at fp - stackoffset + fpdiff.
3083 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
3085 FPDiff = NumBytesCallerPushed - NumBytes;
3087 // Set the delta of movement of the returnaddr stackslot.
3088 // But only set if delta is greater than previous delta.
3089 if (FPDiff < X86Info->getTCReturnAddrDelta())
3090 X86Info->setTCReturnAddrDelta(FPDiff);
3093 unsigned NumBytesToPush = NumBytes;
3094 unsigned NumBytesToPop = NumBytes;
3096 // If we have an inalloca argument, all stack space has already been allocated
3097 // for us and be right at the top of the stack. We don't support multiple
3098 // arguments passed in memory when using inalloca.
3099 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
3101 if (!ArgLocs.back().isMemLoc())
3102 report_fatal_error("cannot use inalloca attribute on a register "
3104 if (ArgLocs.back().getLocMemOffset() != 0)
3105 report_fatal_error("any parameter with the inalloca attribute must be "
3106 "the only memory argument");
3110 Chain = DAG.getCALLSEQ_START(
3111 Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
3113 SDValue RetAddrFrIdx;
3114 // Load return address for tail calls.
3115 if (isTailCall && FPDiff)
3116 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3117 Is64Bit, FPDiff, dl);
3119 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3120 SmallVector<SDValue, 8> MemOpChains;
3123 // Walk the register/memloc assignments, inserting copies/loads. In the case
3124 // of tail call optimization arguments are handle later.
3125 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3126 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3127 // Skip inalloca arguments, they have already been written.
3128 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3129 if (Flags.isInAlloca())
3132 CCValAssign &VA = ArgLocs[i];
3133 EVT RegVT = VA.getLocVT();
3134 SDValue Arg = OutVals[i];
3135 bool isByVal = Flags.isByVal();
3137 // Promote the value if needed.
3138 switch (VA.getLocInfo()) {
3139 default: llvm_unreachable("Unknown loc info!");
3140 case CCValAssign::Full: break;
3141 case CCValAssign::SExt:
3142 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3144 case CCValAssign::ZExt:
3145 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3147 case CCValAssign::AExt:
3148 if (Arg.getValueType().isVector() &&
3149 Arg.getValueType().getVectorElementType() == MVT::i1)
3150 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3151 else if (RegVT.is128BitVector()) {
3152 // Special case: passing MMX values in XMM registers.
3153 Arg = DAG.getBitcast(MVT::i64, Arg);
3154 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3155 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3157 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3159 case CCValAssign::BCvt:
3160 Arg = DAG.getBitcast(RegVT, Arg);
3162 case CCValAssign::Indirect: {
3163 // Store the argument.
3164 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3165 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3166 Chain = DAG.getStore(
3167 Chain, dl, Arg, SpillSlot,
3168 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3175 if (VA.isRegLoc()) {
3176 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3177 if (isVarArg && IsWin64) {
3178 // Win64 ABI requires argument XMM reg to be copied to the corresponding
3179 // shadow reg if callee is a varargs function.
3180 unsigned ShadowReg = 0;
3181 switch (VA.getLocReg()) {
3182 case X86::XMM0: ShadowReg = X86::RCX; break;
3183 case X86::XMM1: ShadowReg = X86::RDX; break;
3184 case X86::XMM2: ShadowReg = X86::R8; break;
3185 case X86::XMM3: ShadowReg = X86::R9; break;
3188 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3190 } else if (!IsSibcall && (!isTailCall || isByVal)) {
3191 assert(VA.isMemLoc());
3192 if (!StackPtr.getNode())
3193 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3194 getPointerTy(DAG.getDataLayout()));
3195 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3196 dl, DAG, VA, Flags));
3200 if (!MemOpChains.empty())
3201 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3203 if (Subtarget->isPICStyleGOT()) {
3204 // ELF / PIC requires GOT in the EBX register before function calls via PLT
3207 RegsToPass.push_back(std::make_pair(
3208 unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3209 getPointerTy(DAG.getDataLayout()))));
3211 // If we are tail calling and generating PIC/GOT style code load the
3212 // address of the callee into ECX. The value in ecx is used as target of
3213 // the tail jump. This is done to circumvent the ebx/callee-saved problem
3214 // for tail calls on PIC/GOT architectures. Normally we would just put the
3215 // address of GOT into ebx and then call target@PLT. But for tail calls
3216 // ebx would be restored (since ebx is callee saved) before jumping to the
3219 // Note: The actual moving to ECX is done further down.
3220 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3221 if (G && !G->getGlobal()->hasLocalLinkage() &&
3222 G->getGlobal()->hasDefaultVisibility())
3223 Callee = LowerGlobalAddress(Callee, DAG);
3224 else if (isa<ExternalSymbolSDNode>(Callee))
3225 Callee = LowerExternalSymbol(Callee, DAG);
3229 if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3230 // From AMD64 ABI document:
3231 // For calls that may call functions that use varargs or stdargs
3232 // (prototype-less calls or calls to functions containing ellipsis (...) in
3233 // the declaration) %al is used as hidden argument to specify the number
3234 // of SSE registers used. The contents of %al do not need to match exactly
3235 // the number of registers, but must be an ubound on the number of SSE
3236 // registers used and is in the range 0 - 8 inclusive.
3238 // Count the number of XMM registers allocated.
3239 static const MCPhysReg XMMArgRegs[] = {
3240 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3241 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3243 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3244 assert((Subtarget->hasSSE1() || !NumXMMRegs)
3245 && "SSE registers cannot be used when SSE is disabled");
3247 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3248 DAG.getConstant(NumXMMRegs, dl,
3252 if (isVarArg && IsMustTail) {
3253 const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3254 for (const auto &F : Forwards) {
3255 SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3256 RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3260 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
3261 // don't need this because the eligibility check rejects calls that require
3262 // shuffling arguments passed in memory.
3263 if (!IsSibcall && isTailCall) {
3264 // Force all the incoming stack arguments to be loaded from the stack
3265 // before any new outgoing arguments are stored to the stack, because the
3266 // outgoing stack slots may alias the incoming argument stack slots, and
3267 // the alias isn't otherwise explicit. This is slightly more conservative
3268 // than necessary, because it means that each store effectively depends
3269 // on every argument instead of just those arguments it would clobber.
3270 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3272 SmallVector<SDValue, 8> MemOpChains2;
3275 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3276 CCValAssign &VA = ArgLocs[i];
3279 assert(VA.isMemLoc());
3280 SDValue Arg = OutVals[i];
3281 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3282 // Skip inalloca arguments. They don't require any work.
3283 if (Flags.isInAlloca())
3285 // Create frame index.
3286 int32_t Offset = VA.getLocMemOffset()+FPDiff;
3287 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3288 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3289 FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3291 if (Flags.isByVal()) {
3292 // Copy relative to framepointer.
3293 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3294 if (!StackPtr.getNode())
3295 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3296 getPointerTy(DAG.getDataLayout()));
3297 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3300 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3304 // Store relative to framepointer.
3305 MemOpChains2.push_back(DAG.getStore(
3306 ArgChain, dl, Arg, FIN,
3307 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3312 if (!MemOpChains2.empty())
3313 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3315 // Store the return address to the appropriate stack slot.
3316 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3317 getPointerTy(DAG.getDataLayout()),
3318 RegInfo->getSlotSize(), FPDiff, dl);
3321 // Build a sequence of copy-to-reg nodes chained together with token chain
3322 // and flag operands which copy the outgoing args into registers.
3324 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3325 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3326 RegsToPass[i].second, InFlag);
3327 InFlag = Chain.getValue(1);
3330 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3331 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3332 // In the 64-bit large code model, we have to make all calls
3333 // through a register, since the call instruction's 32-bit
3334 // pc-relative offset may not be large enough to hold the whole
3336 } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3337 // If the callee is a GlobalAddress node (quite common, every direct call
3338 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3340 GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3342 // We should use extra load for direct calls to dllimported functions in
3344 const GlobalValue *GV = G->getGlobal();
3345 if (!GV->hasDLLImportStorageClass()) {
3346 unsigned char OpFlags = 0;
3347 bool ExtraLoad = false;
3348 unsigned WrapperKind = ISD::DELETED_NODE;
3350 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3351 // external symbols most go through the PLT in PIC mode. If the symbol
3352 // has hidden or protected visibility, or if it is static or local, then
3353 // we don't need to use the PLT - we can directly call it.
3354 if (Subtarget->isTargetELF() &&
3355 DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3356 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3357 OpFlags = X86II::MO_PLT;
3358 } else if (Subtarget->isPICStyleStubAny() &&
3359 !GV->isStrongDefinitionForLinker() &&
3360 (!Subtarget->getTargetTriple().isMacOSX() ||
3361 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3362 // PC-relative references to external symbols should go through $stub,
3363 // unless we're building with the leopard linker or later, which
3364 // automatically synthesizes these stubs.
3365 OpFlags = X86II::MO_DARWIN_STUB;
3366 } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3367 cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3368 // If the function is marked as non-lazy, generate an indirect call
3369 // which loads from the GOT directly. This avoids runtime overhead
3370 // at the cost of eager binding (and one extra byte of encoding).
3371 OpFlags = X86II::MO_GOTPCREL;
3372 WrapperKind = X86ISD::WrapperRIP;
3376 Callee = DAG.getTargetGlobalAddress(
3377 GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3379 // Add a wrapper if needed.
3380 if (WrapperKind != ISD::DELETED_NODE)
3381 Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3382 getPointerTy(DAG.getDataLayout()), Callee);
3383 // Add extra indirection if needed.
3385 Callee = DAG.getLoad(
3386 getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3387 MachinePointerInfo::getGOT(DAG.getMachineFunction()), false, false,
3390 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3391 unsigned char OpFlags = 0;
3393 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3394 // external symbols should go through the PLT.
3395 if (Subtarget->isTargetELF() &&
3396 DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3397 OpFlags = X86II::MO_PLT;
3398 } else if (Subtarget->isPICStyleStubAny() &&
3399 (!Subtarget->getTargetTriple().isMacOSX() ||
3400 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3401 // PC-relative references to external symbols should go through $stub,
3402 // unless we're building with the leopard linker or later, which
3403 // automatically synthesizes these stubs.
3404 OpFlags = X86II::MO_DARWIN_STUB;
3407 Callee = DAG.getTargetExternalSymbol(
3408 S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3409 } else if (Subtarget->isTarget64BitILP32() &&
3410 Callee->getValueType(0) == MVT::i32) {
3411 // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3412 Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3415 // Returns a chain & a flag for retval copy to use.
3416 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3417 SmallVector<SDValue, 8> Ops;
3419 if (!IsSibcall && isTailCall) {
3420 Chain = DAG.getCALLSEQ_END(Chain,
3421 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3422 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3423 InFlag = Chain.getValue(1);
3426 Ops.push_back(Chain);
3427 Ops.push_back(Callee);
3430 Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3432 // Add argument registers to the end of the list so that they are known live
3434 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3435 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3436 RegsToPass[i].second.getValueType()));
3438 // Add a register mask operand representing the call-preserved registers.
3439 const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3440 assert(Mask && "Missing call preserved mask for calling convention");
3442 // If this is an invoke in a 32-bit function using a funclet-based
3443 // personality, assume the function clobbers all registers. If an exception
3444 // is thrown, the runtime will not restore CSRs.
3445 // FIXME: Model this more precisely so that we can register allocate across
3446 // the normal edge and spill and fill across the exceptional edge.
3447 if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3448 const Function *CallerFn = MF.getFunction();
3449 EHPersonality Pers =
3450 CallerFn->hasPersonalityFn()
3451 ? classifyEHPersonality(CallerFn->getPersonalityFn())
3452 : EHPersonality::Unknown;
3453 if (isFuncletEHPersonality(Pers))
3454 Mask = RegInfo->getNoPreservedMask();
3457 Ops.push_back(DAG.getRegisterMask(Mask));
3459 if (InFlag.getNode())
3460 Ops.push_back(InFlag);
3464 //// If this is the first return lowered for this function, add the regs
3465 //// to the liveout set for the function.
3466 // This isn't right, although it's probably harmless on x86; liveouts
3467 // should be computed from returns not tail calls. Consider a void
3468 // function making a tail call to a function returning int.
3469 MF.getFrameInfo()->setHasTailCall();
3470 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3473 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3474 InFlag = Chain.getValue(1);
3476 // Create the CALLSEQ_END node.
3477 unsigned NumBytesForCalleeToPop;
3478 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3479 DAG.getTarget().Options.GuaranteedTailCallOpt))
3480 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
3481 else if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
3482 !Subtarget->getTargetTriple().isOSMSVCRT() &&
3483 SR == StackStructReturn)
3484 // If this is a call to a struct-return function, the callee
3485 // pops the hidden struct pointer, so we have to push it back.
3486 // This is common for Darwin/X86, Linux & Mingw32 targets.
3487 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3488 NumBytesForCalleeToPop = 4;
3490 NumBytesForCalleeToPop = 0; // Callee pops nothing.
3492 // Returns a flag for retval copy to use.
3494 Chain = DAG.getCALLSEQ_END(Chain,
3495 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3496 DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3499 InFlag = Chain.getValue(1);
3502 // Handle result values, copying them out of physregs into vregs that we
3504 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3505 Ins, dl, DAG, InVals);
3508 //===----------------------------------------------------------------------===//
3509 // Fast Calling Convention (tail call) implementation
3510 //===----------------------------------------------------------------------===//
3512 // Like std call, callee cleans arguments, convention except that ECX is
3513 // reserved for storing the tail called function address. Only 2 registers are
3514 // free for argument passing (inreg). Tail call optimization is performed
3516 // * tailcallopt is enabled
3517 // * caller/callee are fastcc
3518 // On X86_64 architecture with GOT-style position independent code only local
3519 // (within module) calls are supported at the moment.
3520 // To keep the stack aligned according to platform abi the function
3521 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3522 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3523 // If a tail called function callee has more arguments than the caller the
3524 // caller needs to make sure that there is room to move the RETADDR to. This is
3525 // achieved by reserving an area the size of the argument delta right after the
3526 // original RETADDR, but before the saved framepointer or the spilled registers
3527 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3539 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
3542 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3543 SelectionDAG& DAG) const {
3544 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3545 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3546 unsigned StackAlignment = TFI.getStackAlignment();
3547 uint64_t AlignMask = StackAlignment - 1;
3548 int64_t Offset = StackSize;
3549 unsigned SlotSize = RegInfo->getSlotSize();
3550 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3551 // Number smaller than 12 so just add the difference.
3552 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3554 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3555 Offset = ((~AlignMask) & Offset) + StackAlignment +
3556 (StackAlignment-SlotSize);
3561 /// Return true if the given stack call argument is already available in the
3562 /// same position (relatively) of the caller's incoming argument stack.
3564 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3565 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3566 const X86InstrInfo *TII) {
3567 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3569 if (Arg.getOpcode() == ISD::CopyFromReg) {
3570 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3571 if (!TargetRegisterInfo::isVirtualRegister(VR))
3573 MachineInstr *Def = MRI->getVRegDef(VR);
3576 if (!Flags.isByVal()) {
3577 if (!TII->isLoadFromStackSlot(Def, FI))
3580 unsigned Opcode = Def->getOpcode();
3581 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3582 Opcode == X86::LEA64_32r) &&
3583 Def->getOperand(1).isFI()) {
3584 FI = Def->getOperand(1).getIndex();
3585 Bytes = Flags.getByValSize();
3589 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3590 if (Flags.isByVal())
3591 // ByVal argument is passed in as a pointer but it's now being
3592 // dereferenced. e.g.
3593 // define @foo(%struct.X* %A) {
3594 // tail call @bar(%struct.X* byval %A)
3597 SDValue Ptr = Ld->getBasePtr();
3598 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3601 FI = FINode->getIndex();
3602 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3603 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3604 FI = FINode->getIndex();
3605 Bytes = Flags.getByValSize();
3609 assert(FI != INT_MAX);
3610 if (!MFI->isFixedObjectIndex(FI))
3612 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3615 /// Check whether the call is eligible for tail call optimization. Targets
3616 /// that want to do tail call optimization should implement this function.
3617 bool X86TargetLowering::IsEligibleForTailCallOptimization(
3618 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
3619 bool isCalleeStructRet, bool isCallerStructRet, Type *RetTy,
3620 const SmallVectorImpl<ISD::OutputArg> &Outs,
3621 const SmallVectorImpl<SDValue> &OutVals,
3622 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3623 if (!mayTailCallThisCC(CalleeCC))
3626 // If -tailcallopt is specified, make fastcc functions tail-callable.
3627 MachineFunction &MF = DAG.getMachineFunction();
3628 const Function *CallerF = MF.getFunction();
3630 // If the function return type is x86_fp80 and the callee return type is not,
3631 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3632 // perform a tailcall optimization here.
3633 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3636 CallingConv::ID CallerCC = CallerF->getCallingConv();
3637 bool CCMatch = CallerCC == CalleeCC;
3638 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3639 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3641 // Win64 functions have extra shadow space for argument homing. Don't do the
3642 // sibcall if the caller and callee have mismatched expectations for this
3644 if (IsCalleeWin64 != IsCallerWin64)
3647 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3648 if (canGuaranteeTCO(CalleeCC) && CCMatch)
3653 // Look for obvious safe cases to perform tail call optimization that do not
3654 // require ABI changes. This is what gcc calls sibcall.
3656 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3657 // emit a special epilogue.
3658 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3659 if (RegInfo->needsStackRealignment(MF))
3662 // Also avoid sibcall optimization if either caller or callee uses struct
3663 // return semantics.
3664 if (isCalleeStructRet || isCallerStructRet)
3667 // Do not sibcall optimize vararg calls unless all arguments are passed via
3669 if (isVarArg && !Outs.empty()) {
3670 // Optimizing for varargs on Win64 is unlikely to be safe without
3671 // additional testing.
3672 if (IsCalleeWin64 || IsCallerWin64)
3675 SmallVector<CCValAssign, 16> ArgLocs;
3676 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3679 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3680 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3681 if (!ArgLocs[i].isRegLoc())
3685 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3686 // stack. Therefore, if it's not used by the call it is not safe to optimize
3687 // this into a sibcall.
3688 bool Unused = false;
3689 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3696 SmallVector<CCValAssign, 16> RVLocs;
3697 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3699 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3700 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3701 CCValAssign &VA = RVLocs[i];
3702 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3707 // If the calling conventions do not match, then we'd better make sure the
3708 // results are returned in the same way as what the caller expects.
3710 SmallVector<CCValAssign, 16> RVLocs1;
3711 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3713 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3715 SmallVector<CCValAssign, 16> RVLocs2;
3716 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3718 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3720 if (RVLocs1.size() != RVLocs2.size())
3722 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3723 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3725 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3727 if (RVLocs1[i].isRegLoc()) {
3728 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3731 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3737 unsigned StackArgsSize = 0;
3739 // If the callee takes no arguments then go on to check the results of the
3741 if (!Outs.empty()) {
3742 // Check if stack adjustment is needed. For now, do not do this if any
3743 // argument is passed on the stack.
3744 SmallVector<CCValAssign, 16> ArgLocs;
3745 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3748 // Allocate shadow area for Win64
3750 CCInfo.AllocateStack(32, 8);
3752 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3753 StackArgsSize = CCInfo.getNextStackOffset();
3755 if (CCInfo.getNextStackOffset()) {
3756 // Check if the arguments are already laid out in the right way as
3757 // the caller's fixed stack objects.
3758 MachineFrameInfo *MFI = MF.getFrameInfo();
3759 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3760 const X86InstrInfo *TII = Subtarget->getInstrInfo();
3761 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3762 CCValAssign &VA = ArgLocs[i];
3763 SDValue Arg = OutVals[i];
3764 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3765 if (VA.getLocInfo() == CCValAssign::Indirect)
3767 if (!VA.isRegLoc()) {
3768 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3775 // If the tailcall address may be in a register, then make sure it's
3776 // possible to register allocate for it. In 32-bit, the call address can
3777 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3778 // callee-saved registers are restored. These happen to be the same
3779 // registers used to pass 'inreg' arguments so watch out for those.
3780 if (!Subtarget->is64Bit() &&
3781 ((!isa<GlobalAddressSDNode>(Callee) &&
3782 !isa<ExternalSymbolSDNode>(Callee)) ||
3783 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3784 unsigned NumInRegs = 0;
3785 // In PIC we need an extra register to formulate the address computation
3787 unsigned MaxInRegs =
3788 (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3790 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3791 CCValAssign &VA = ArgLocs[i];
3794 unsigned Reg = VA.getLocReg();
3797 case X86::EAX: case X86::EDX: case X86::ECX:
3798 if (++NumInRegs == MaxInRegs)
3806 bool CalleeWillPop =
3807 X86::isCalleePop(CalleeCC, Subtarget->is64Bit(), isVarArg,
3808 MF.getTarget().Options.GuaranteedTailCallOpt);
3810 if (unsigned BytesToPop =
3811 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn()) {
3812 // If we have bytes to pop, the callee must pop them.
3813 bool CalleePopMatches = CalleeWillPop && BytesToPop == StackArgsSize;
3814 if (!CalleePopMatches)
3816 } else if (CalleeWillPop && StackArgsSize > 0) {
3817 // If we don't have bytes to pop, make sure the callee doesn't pop any.
3825 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3826 const TargetLibraryInfo *libInfo) const {
3827 return X86::createFastISel(funcInfo, libInfo);
3830 //===----------------------------------------------------------------------===//
3831 // Other Lowering Hooks
3832 //===----------------------------------------------------------------------===//
3834 static bool MayFoldLoad(SDValue Op) {
3835 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3838 static bool MayFoldIntoStore(SDValue Op) {
3839 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3842 static bool isTargetShuffle(unsigned Opcode) {
3844 default: return false;
3845 case X86ISD::BLENDI:
3846 case X86ISD::PSHUFB:
3847 case X86ISD::PSHUFD:
3848 case X86ISD::PSHUFHW:
3849 case X86ISD::PSHUFLW:
3851 case X86ISD::PALIGNR:
3852 case X86ISD::MOVLHPS:
3853 case X86ISD::MOVLHPD:
3854 case X86ISD::MOVHLPS:
3855 case X86ISD::MOVLPS:
3856 case X86ISD::MOVLPD:
3857 case X86ISD::MOVSHDUP:
3858 case X86ISD::MOVSLDUP:
3859 case X86ISD::MOVDDUP:
3862 case X86ISD::UNPCKL:
3863 case X86ISD::UNPCKH:
3864 case X86ISD::VPERMILPI:
3865 case X86ISD::VPERM2X128:
3866 case X86ISD::VPERMI:
3867 case X86ISD::VPERMV:
3868 case X86ISD::VPERMV3:
3873 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, MVT VT,
3874 SDValue V1, unsigned TargetMask,
3875 SelectionDAG &DAG) {
3877 default: llvm_unreachable("Unknown x86 shuffle node");
3878 case X86ISD::PSHUFD:
3879 case X86ISD::PSHUFHW:
3880 case X86ISD::PSHUFLW:
3881 case X86ISD::VPERMILPI:
3882 case X86ISD::VPERMI:
3883 return DAG.getNode(Opc, dl, VT, V1,
3884 DAG.getConstant(TargetMask, dl, MVT::i8));
3888 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, MVT VT,
3889 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3891 default: llvm_unreachable("Unknown x86 shuffle node");
3892 case X86ISD::MOVLHPS:
3893 case X86ISD::MOVLHPD:
3894 case X86ISD::MOVHLPS:
3895 case X86ISD::MOVLPS:
3896 case X86ISD::MOVLPD:
3899 case X86ISD::UNPCKL:
3900 case X86ISD::UNPCKH:
3901 return DAG.getNode(Opc, dl, VT, V1, V2);
3905 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3906 MachineFunction &MF = DAG.getMachineFunction();
3907 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3908 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3909 int ReturnAddrIndex = FuncInfo->getRAIndex();
3911 if (ReturnAddrIndex == 0) {
3912 // Set up a frame object for the return address.
3913 unsigned SlotSize = RegInfo->getSlotSize();
3914 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3917 FuncInfo->setRAIndex(ReturnAddrIndex);
3920 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3923 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3924 bool hasSymbolicDisplacement) {
3925 // Offset should fit into 32 bit immediate field.
3926 if (!isInt<32>(Offset))
3929 // If we don't have a symbolic displacement - we don't have any extra
3931 if (!hasSymbolicDisplacement)
3934 // FIXME: Some tweaks might be needed for medium code model.
3935 if (M != CodeModel::Small && M != CodeModel::Kernel)
3938 // For small code model we assume that latest object is 16MB before end of 31
3939 // bits boundary. We may also accept pretty large negative constants knowing
3940 // that all objects are in the positive half of address space.
3941 if (M == CodeModel::Small && Offset < 16*1024*1024)
3944 // For kernel code model we know that all object resist in the negative half
3945 // of 32bits address space. We may not accept negative offsets, since they may
3946 // be just off and we may accept pretty large positive ones.
3947 if (M == CodeModel::Kernel && Offset >= 0)
3953 /// Determines whether the callee is required to pop its own arguments.
3954 /// Callee pop is necessary to support tail calls.
3955 bool X86::isCalleePop(CallingConv::ID CallingConv,
3956 bool is64Bit, bool IsVarArg, bool GuaranteeTCO) {
3957 // If GuaranteeTCO is true, we force some calls to be callee pop so that we
3958 // can guarantee TCO.
3959 if (!IsVarArg && shouldGuaranteeTCO(CallingConv, GuaranteeTCO))
3962 switch (CallingConv) {
3965 case CallingConv::X86_StdCall:
3966 case CallingConv::X86_FastCall:
3967 case CallingConv::X86_ThisCall:
3968 case CallingConv::X86_VectorCall:
3973 /// \brief Return true if the condition is an unsigned comparison operation.
3974 static bool isX86CCUnsigned(unsigned X86CC) {
3976 default: llvm_unreachable("Invalid integer condition!");
3977 case X86::COND_E: return true;
3978 case X86::COND_G: return false;
3979 case X86::COND_GE: return false;
3980 case X86::COND_L: return false;
3981 case X86::COND_LE: return false;
3982 case X86::COND_NE: return true;
3983 case X86::COND_B: return true;
3984 case X86::COND_A: return true;
3985 case X86::COND_BE: return true;
3986 case X86::COND_AE: return true;
3990 static X86::CondCode TranslateIntegerX86CC(ISD::CondCode SetCCOpcode) {
3991 switch (SetCCOpcode) {
3992 default: llvm_unreachable("Invalid integer condition!");
3993 case ISD::SETEQ: return X86::COND_E;
3994 case ISD::SETGT: return X86::COND_G;
3995 case ISD::SETGE: return X86::COND_GE;
3996 case ISD::SETLT: return X86::COND_L;
3997 case ISD::SETLE: return X86::COND_LE;
3998 case ISD::SETNE: return X86::COND_NE;
3999 case ISD::SETULT: return X86::COND_B;
4000 case ISD::SETUGT: return X86::COND_A;
4001 case ISD::SETULE: return X86::COND_BE;
4002 case ISD::SETUGE: return X86::COND_AE;
4006 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
4007 /// condition code, returning the condition code and the LHS/RHS of the
4008 /// comparison to make.
4009 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
4010 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
4012 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4013 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
4014 // X > -1 -> X == 0, jump !sign.
4015 RHS = DAG.getConstant(0, DL, RHS.getValueType());
4016 return X86::COND_NS;
4018 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
4019 // X < 0 -> X == 0, jump on sign.
4022 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
4024 RHS = DAG.getConstant(0, DL, RHS.getValueType());
4025 return X86::COND_LE;
4029 return TranslateIntegerX86CC(SetCCOpcode);
4032 // First determine if it is required or is profitable to flip the operands.
4034 // If LHS is a foldable load, but RHS is not, flip the condition.
4035 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
4036 !ISD::isNON_EXTLoad(RHS.getNode())) {
4037 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
4038 std::swap(LHS, RHS);
4041 switch (SetCCOpcode) {
4047 std::swap(LHS, RHS);
4051 // On a floating point condition, the flags are set as follows:
4053 // 0 | 0 | 0 | X > Y
4054 // 0 | 0 | 1 | X < Y
4055 // 1 | 0 | 0 | X == Y
4056 // 1 | 1 | 1 | unordered
4057 switch (SetCCOpcode) {
4058 default: llvm_unreachable("Condcode should be pre-legalized away");
4060 case ISD::SETEQ: return X86::COND_E;
4061 case ISD::SETOLT: // flipped
4063 case ISD::SETGT: return X86::COND_A;
4064 case ISD::SETOLE: // flipped
4066 case ISD::SETGE: return X86::COND_AE;
4067 case ISD::SETUGT: // flipped
4069 case ISD::SETLT: return X86::COND_B;
4070 case ISD::SETUGE: // flipped
4072 case ISD::SETLE: return X86::COND_BE;
4074 case ISD::SETNE: return X86::COND_NE;
4075 case ISD::SETUO: return X86::COND_P;
4076 case ISD::SETO: return X86::COND_NP;
4078 case ISD::SETUNE: return X86::COND_INVALID;
4082 /// Is there a floating point cmov for the specific X86 condition code?
4083 /// Current x86 isa includes the following FP cmov instructions:
4084 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
4085 static bool hasFPCMov(unsigned X86CC) {
4101 /// Returns true if the target can instruction select the
4102 /// specified FP immediate natively. If false, the legalizer will
4103 /// materialize the FP immediate as a load from a constant pool.
4104 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4105 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
4106 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
4112 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
4113 ISD::LoadExtType ExtTy,
4115 // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
4116 // relocation target a movq or addq instruction: don't let the load shrink.
4117 SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
4118 if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
4119 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
4120 return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
4124 /// \brief Returns true if it is beneficial to convert a load of a constant
4125 /// to just the constant itself.
4126 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
4128 assert(Ty->isIntegerTy());
4130 unsigned BitSize = Ty->getPrimitiveSizeInBits();
4131 if (BitSize == 0 || BitSize > 64)
4136 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
4137 unsigned Index) const {
4138 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4141 return (Index == 0 || Index == ResVT.getVectorNumElements());
4144 bool X86TargetLowering::isCheapToSpeculateCttz() const {
4145 // Speculate cttz only if we can directly use TZCNT.
4146 return Subtarget->hasBMI();
4149 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4150 // Speculate ctlz only if we can directly use LZCNT.
4151 return Subtarget->hasLZCNT();
4154 /// Return true if every element in Mask, beginning
4155 /// from position Pos and ending in Pos+Size is undef.
4156 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4157 for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4163 /// Return true if Val is undef or if its value falls within the
4164 /// specified range (L, H].
4165 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4166 return (Val < 0) || (Val >= Low && Val < Hi);
4169 /// Val is either less than zero (undef) or equal to the specified value.
4170 static bool isUndefOrEqual(int Val, int CmpVal) {
4171 return (Val < 0 || Val == CmpVal);
4174 /// Return true if every element in Mask, beginning
4175 /// from position Pos and ending in Pos+Size, falls within the specified
4176 /// sequential range (Low, Low+Size]. or is undef.
4177 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4178 unsigned Pos, unsigned Size, int Low) {
4179 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4180 if (!isUndefOrEqual(Mask[i], Low))
4185 /// Return true if the specified EXTRACT_SUBVECTOR operand specifies a vector
4186 /// extract that is suitable for instruction that extract 128 or 256 bit vectors
4187 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4188 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4189 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4192 // The index should be aligned on a vecWidth-bit boundary.
4194 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4196 MVT VT = N->getSimpleValueType(0);
4197 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4198 bool Result = (Index * ElSize) % vecWidth == 0;
4203 /// Return true if the specified INSERT_SUBVECTOR
4204 /// operand specifies a subvector insert that is suitable for input to
4205 /// insertion of 128 or 256-bit subvectors
4206 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4207 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4208 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4210 // The index should be aligned on a vecWidth-bit boundary.
4212 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4214 MVT VT = N->getSimpleValueType(0);
4215 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4216 bool Result = (Index * ElSize) % vecWidth == 0;
4221 bool X86::isVINSERT128Index(SDNode *N) {
4222 return isVINSERTIndex(N, 128);
4225 bool X86::isVINSERT256Index(SDNode *N) {
4226 return isVINSERTIndex(N, 256);
4229 bool X86::isVEXTRACT128Index(SDNode *N) {
4230 return isVEXTRACTIndex(N, 128);
4233 bool X86::isVEXTRACT256Index(SDNode *N) {
4234 return isVEXTRACTIndex(N, 256);
4237 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4238 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4239 assert(isa<ConstantSDNode>(N->getOperand(1).getNode()) &&
4240 "Illegal extract subvector for VEXTRACT");
4243 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4245 MVT VecVT = N->getOperand(0).getSimpleValueType();
4246 MVT ElVT = VecVT.getVectorElementType();
4248 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4249 return Index / NumElemsPerChunk;
4252 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4253 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4254 assert(isa<ConstantSDNode>(N->getOperand(2).getNode()) &&
4255 "Illegal insert subvector for VINSERT");
4258 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4260 MVT VecVT = N->getSimpleValueType(0);
4261 MVT ElVT = VecVT.getVectorElementType();
4263 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4264 return Index / NumElemsPerChunk;
4267 /// Return the appropriate immediate to extract the specified
4268 /// EXTRACT_SUBVECTOR index with VEXTRACTF128 and VINSERTI128 instructions.
4269 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4270 return getExtractVEXTRACTImmediate(N, 128);
4273 /// Return the appropriate immediate to extract the specified
4274 /// EXTRACT_SUBVECTOR index with VEXTRACTF64x4 and VINSERTI64x4 instructions.
4275 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4276 return getExtractVEXTRACTImmediate(N, 256);
4279 /// Return the appropriate immediate to insert at the specified
4280 /// INSERT_SUBVECTOR index with VINSERTF128 and VINSERTI128 instructions.
4281 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4282 return getInsertVINSERTImmediate(N, 128);
4285 /// Return the appropriate immediate to insert at the specified
4286 /// INSERT_SUBVECTOR index with VINSERTF46x4 and VINSERTI64x4 instructions.
4287 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4288 return getInsertVINSERTImmediate(N, 256);
4291 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
4292 bool X86::isZeroNode(SDValue Elt) {
4293 return isNullConstant(Elt) || isNullFPConstant(Elt);
4296 // Build a vector of constants
4297 // Use an UNDEF node if MaskElt == -1.
4298 // Spilt 64-bit constants in the 32-bit mode.
4299 static SDValue getConstVector(ArrayRef<int> Values, MVT VT,
4301 SDLoc dl, bool IsMask = false) {
4303 SmallVector<SDValue, 32> Ops;
4306 MVT ConstVecVT = VT;
4307 unsigned NumElts = VT.getVectorNumElements();
4308 bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
4309 if (!In64BitMode && VT.getVectorElementType() == MVT::i64) {
4310 ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
4314 MVT EltVT = ConstVecVT.getVectorElementType();
4315 for (unsigned i = 0; i < NumElts; ++i) {
4316 bool IsUndef = Values[i] < 0 && IsMask;
4317 SDValue OpNode = IsUndef ? DAG.getUNDEF(EltVT) :
4318 DAG.getConstant(Values[i], dl, EltVT);
4319 Ops.push_back(OpNode);
4321 Ops.push_back(IsUndef ? DAG.getUNDEF(EltVT) :
4322 DAG.getConstant(0, dl, EltVT));
4324 SDValue ConstsNode = DAG.getNode(ISD::BUILD_VECTOR, dl, ConstVecVT, Ops);
4326 ConstsNode = DAG.getBitcast(VT, ConstsNode);
4330 /// Returns a vector of specified type with all zero elements.
4331 static SDValue getZeroVector(MVT VT, const X86Subtarget *Subtarget,
4332 SelectionDAG &DAG, SDLoc dl) {
4333 assert(VT.isVector() && "Expected a vector type");
4335 // Always build SSE zero vectors as <4 x i32> bitcasted
4336 // to their dest type. This ensures they get CSE'd.
4338 if (VT.is128BitVector()) { // SSE
4339 if (Subtarget->hasSSE2()) { // SSE2
4340 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4341 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4343 SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4344 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4346 } else if (VT.is256BitVector()) { // AVX
4347 if (Subtarget->hasInt256()) { // AVX2
4348 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4349 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4350 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4352 // 256-bit logic and arithmetic instructions in AVX are all
4353 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4354 SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4355 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4356 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4358 } else if (VT.is512BitVector()) { // AVX-512
4359 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4360 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4361 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4362 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4363 } else if (VT.getVectorElementType() == MVT::i1) {
4365 assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4366 && "Unexpected vector type");
4367 assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4368 && "Unexpected vector type");
4369 SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4370 SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4371 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4373 llvm_unreachable("Unexpected vector type");
4375 return DAG.getBitcast(VT, Vec);
4378 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4379 SelectionDAG &DAG, SDLoc dl,
4380 unsigned vectorWidth) {
4381 assert((vectorWidth == 128 || vectorWidth == 256) &&
4382 "Unsupported vector width");
4383 EVT VT = Vec.getValueType();
4384 EVT ElVT = VT.getVectorElementType();
4385 unsigned Factor = VT.getSizeInBits()/vectorWidth;
4386 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4387 VT.getVectorNumElements()/Factor);
4389 // Extract from UNDEF is UNDEF.
4390 if (Vec.getOpcode() == ISD::UNDEF)
4391 return DAG.getUNDEF(ResultVT);
4393 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
4394 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4395 assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
4397 // This is the index of the first element of the vectorWidth-bit chunk
4398 // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
4399 IdxVal &= ~(ElemsPerChunk - 1);
4401 // If the input is a buildvector just emit a smaller one.
4402 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4403 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4404 makeArrayRef(Vec->op_begin() + IdxVal, ElemsPerChunk));
4406 SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
4407 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4410 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
4411 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4412 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4413 /// instructions or a simple subregister reference. Idx is an index in the
4414 /// 128 bits we want. It need not be aligned to a 128-bit boundary. That makes
4415 /// lowering EXTRACT_VECTOR_ELT operations easier.
4416 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4417 SelectionDAG &DAG, SDLoc dl) {
4418 assert((Vec.getValueType().is256BitVector() ||
4419 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4420 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4423 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4424 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4425 SelectionDAG &DAG, SDLoc dl) {
4426 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4427 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4430 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4431 unsigned IdxVal, SelectionDAG &DAG,
4432 SDLoc dl, unsigned vectorWidth) {
4433 assert((vectorWidth == 128 || vectorWidth == 256) &&
4434 "Unsupported vector width");
4435 // Inserting UNDEF is Result
4436 if (Vec.getOpcode() == ISD::UNDEF)
4438 EVT VT = Vec.getValueType();
4439 EVT ElVT = VT.getVectorElementType();
4440 EVT ResultVT = Result.getValueType();
4442 // Insert the relevant vectorWidth bits.
4443 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4444 assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
4446 // This is the index of the first element of the vectorWidth-bit chunk
4447 // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
4448 IdxVal &= ~(ElemsPerChunk - 1);
4450 SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
4451 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4454 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
4455 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4456 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4457 /// simple superregister reference. Idx is an index in the 128 bits
4458 /// we want. It need not be aligned to a 128-bit boundary. That makes
4459 /// lowering INSERT_VECTOR_ELT operations easier.
4460 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4461 SelectionDAG &DAG, SDLoc dl) {
4462 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4464 // For insertion into the zero index (low half) of a 256-bit vector, it is
4465 // more efficient to generate a blend with immediate instead of an insert*128.
4466 // We are still creating an INSERT_SUBVECTOR below with an undef node to
4467 // extend the subvector to the size of the result vector. Make sure that
4468 // we are not recursing on that node by checking for undef here.
4469 if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4470 Result.getOpcode() != ISD::UNDEF) {
4471 EVT ResultVT = Result.getValueType();
4472 SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4473 SDValue Undef = DAG.getUNDEF(ResultVT);
4474 SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4477 // The blend instruction, and therefore its mask, depend on the data type.
4478 MVT ScalarType = ResultVT.getVectorElementType().getSimpleVT();
4479 if (ScalarType.isFloatingPoint()) {
4480 // Choose either vblendps (float) or vblendpd (double).
4481 unsigned ScalarSize = ScalarType.getSizeInBits();
4482 assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4483 unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4484 SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4485 return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4488 const X86Subtarget &Subtarget =
4489 static_cast<const X86Subtarget &>(DAG.getSubtarget());
4491 // AVX2 is needed for 256-bit integer blend support.
4492 // Integers must be cast to 32-bit because there is only vpblendd;
4493 // vpblendw can't be used for this because it has a handicapped mask.
4495 // If we don't have AVX2, then cast to float. Using a wrong domain blend
4496 // is still more efficient than using the wrong domain vinsertf128 that
4497 // will be created by InsertSubVector().
4498 MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4500 SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4501 Vec256 = DAG.getBitcast(CastVT, Vec256);
4502 Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4503 return DAG.getBitcast(ResultVT, Vec256);
4506 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4509 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4510 SelectionDAG &DAG, SDLoc dl) {
4511 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4512 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4515 /// Insert i1-subvector to i1-vector.
4516 static SDValue Insert1BitVector(SDValue Op, SelectionDAG &DAG) {
4519 SDValue Vec = Op.getOperand(0);
4520 SDValue SubVec = Op.getOperand(1);
4521 SDValue Idx = Op.getOperand(2);
4523 if (!isa<ConstantSDNode>(Idx))
4526 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
4527 if (IdxVal == 0 && Vec.isUndef()) // the operation is legal
4530 MVT OpVT = Op.getSimpleValueType();
4531 MVT SubVecVT = SubVec.getSimpleValueType();
4532 unsigned NumElems = OpVT.getVectorNumElements();
4533 unsigned SubVecNumElems = SubVecVT.getVectorNumElements();
4535 assert(IdxVal + SubVecNumElems <= NumElems &&
4536 IdxVal % SubVecVT.getSizeInBits() == 0 &&
4537 "Unexpected index value in INSERT_SUBVECTOR");
4539 // There are 3 possible cases:
4540 // 1. Subvector should be inserted in the lower part (IdxVal == 0)
4541 // 2. Subvector should be inserted in the upper part
4542 // (IdxVal + SubVecNumElems == NumElems)
4543 // 3. Subvector should be inserted in the middle (for example v2i1
4544 // to v16i1, index 2)
4546 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
4547 SDValue Undef = DAG.getUNDEF(OpVT);
4548 SDValue WideSubVec =
4549 DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef, SubVec, ZeroIdx);
4551 return DAG.getNode(X86ISD::VSHLI, dl, OpVT, WideSubVec,
4552 DAG.getConstant(IdxVal, dl, MVT::i8));
4554 if (ISD::isBuildVectorAllZeros(Vec.getNode())) {
4555 unsigned ShiftLeft = NumElems - SubVecNumElems;
4556 unsigned ShiftRight = NumElems - SubVecNumElems - IdxVal;
4557 WideSubVec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, WideSubVec,
4558 DAG.getConstant(ShiftLeft, dl, MVT::i8));
4559 return ShiftRight ? DAG.getNode(X86ISD::VSRLI, dl, OpVT, WideSubVec,
4560 DAG.getConstant(ShiftRight, dl, MVT::i8)) : WideSubVec;
4564 // Zero lower bits of the Vec
4565 SDValue ShiftBits = DAG.getConstant(SubVecNumElems, dl, MVT::i8);
4566 Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
4567 Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
4568 // Merge them together
4569 return DAG.getNode(ISD::OR, dl, OpVT, Vec, WideSubVec);
4572 // Simple case when we put subvector in the upper part
4573 if (IdxVal + SubVecNumElems == NumElems) {
4574 // Zero upper bits of the Vec
4575 WideSubVec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec,
4576 DAG.getConstant(IdxVal, dl, MVT::i8));
4577 SDValue ShiftBits = DAG.getConstant(SubVecNumElems, dl, MVT::i8);
4578 Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
4579 Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
4580 return DAG.getNode(ISD::OR, dl, OpVT, Vec, WideSubVec);
4582 // Subvector should be inserted in the middle - use shuffle
4583 SmallVector<int, 64> Mask;
4584 for (unsigned i = 0; i < NumElems; ++i)
4585 Mask.push_back(i >= IdxVal && i < IdxVal + SubVecNumElems ?
4587 return DAG.getVectorShuffle(OpVT, dl, WideSubVec, Vec, Mask);
4590 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4591 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4592 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4593 /// large BUILD_VECTORS.
4594 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4595 unsigned NumElems, SelectionDAG &DAG,
4597 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4598 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4601 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4602 unsigned NumElems, SelectionDAG &DAG,
4604 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4605 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4608 /// Returns a vector of specified type with all bits set.
4609 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4610 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4611 /// Then bitcast to their original type, ensuring they get CSE'd.
4612 static SDValue getOnesVector(EVT VT, const X86Subtarget *Subtarget,
4613 SelectionDAG &DAG, SDLoc dl) {
4614 assert(VT.isVector() && "Expected a vector type");
4616 SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4618 if (VT.is512BitVector()) {
4619 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4620 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4621 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4622 } else if (VT.is256BitVector()) {
4623 if (Subtarget->hasInt256()) { // AVX2
4624 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4625 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4627 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4628 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4630 } else if (VT.is128BitVector()) {
4631 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4633 llvm_unreachable("Unexpected vector type");
4635 return DAG.getBitcast(VT, Vec);
4638 /// Returns a vector_shuffle node for an unpackl operation.
4639 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4641 unsigned NumElems = VT.getVectorNumElements();
4642 SmallVector<int, 8> Mask;
4643 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4645 Mask.push_back(i + NumElems);
4647 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4650 /// Returns a vector_shuffle node for an unpackh operation.
4651 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4653 unsigned NumElems = VT.getVectorNumElements();
4654 SmallVector<int, 8> Mask;
4655 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4656 Mask.push_back(i + Half);
4657 Mask.push_back(i + NumElems + Half);
4659 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4662 /// Return a vector_shuffle of the specified vector of zero or undef vector.
4663 /// This produces a shuffle where the low element of V2 is swizzled into the
4664 /// zero/undef vector, landing at element Idx.
4665 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4666 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4668 const X86Subtarget *Subtarget,
4669 SelectionDAG &DAG) {
4670 MVT VT = V2.getSimpleValueType();
4672 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4673 unsigned NumElems = VT.getVectorNumElements();
4674 SmallVector<int, 16> MaskVec;
4675 for (unsigned i = 0; i != NumElems; ++i)
4676 // If this is the insertion idx, put the low elt of V2 here.
4677 MaskVec.push_back(i == Idx ? NumElems : i);
4678 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4681 /// Calculates the shuffle mask corresponding to the target-specific opcode.
4682 /// Returns true if the Mask could be calculated. Sets IsUnary to true if only
4683 /// uses one source. Note that this will set IsUnary for shuffles which use a
4684 /// single input multiple times, and in those cases it will
4685 /// adjust the mask to only have indices within that single input.
4686 /// FIXME: Add support for Decode*Mask functions that return SM_SentinelZero.
4687 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4688 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4689 unsigned NumElems = VT.getVectorNumElements();
4693 bool IsFakeUnary = false;
4694 switch(N->getOpcode()) {
4695 case X86ISD::BLENDI:
4696 ImmN = N->getOperand(N->getNumOperands()-1);
4697 DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4700 ImmN = N->getOperand(N->getNumOperands()-1);
4701 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4702 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4704 case X86ISD::UNPCKH:
4705 DecodeUNPCKHMask(VT, Mask);
4706 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4708 case X86ISD::UNPCKL:
4709 DecodeUNPCKLMask(VT, Mask);
4710 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4712 case X86ISD::MOVHLPS:
4713 DecodeMOVHLPSMask(NumElems, Mask);
4714 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4716 case X86ISD::MOVLHPS:
4717 DecodeMOVLHPSMask(NumElems, Mask);
4718 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4720 case X86ISD::PALIGNR:
4721 ImmN = N->getOperand(N->getNumOperands()-1);
4722 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4724 case X86ISD::PSHUFD:
4725 case X86ISD::VPERMILPI:
4726 ImmN = N->getOperand(N->getNumOperands()-1);
4727 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4730 case X86ISD::PSHUFHW:
4731 ImmN = N->getOperand(N->getNumOperands()-1);
4732 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4735 case X86ISD::PSHUFLW:
4736 ImmN = N->getOperand(N->getNumOperands()-1);
4737 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4740 case X86ISD::PSHUFB: {
4742 SDValue MaskNode = N->getOperand(1);
4743 while (MaskNode->getOpcode() == ISD::BITCAST)
4744 MaskNode = MaskNode->getOperand(0);
4746 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4747 // If we have a build-vector, then things are easy.
4748 MVT VT = MaskNode.getSimpleValueType();
4749 assert(VT.isVector() &&
4750 "Can't produce a non-vector with a build_vector!");
4751 if (!VT.isInteger())
4754 int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4756 SmallVector<uint64_t, 32> RawMask;
4757 for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4758 SDValue Op = MaskNode->getOperand(i);
4759 if (Op->getOpcode() == ISD::UNDEF) {
4760 RawMask.push_back((uint64_t)SM_SentinelUndef);
4763 auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4766 APInt MaskElement = CN->getAPIntValue();
4768 // We now have to decode the element which could be any integer size and
4769 // extract each byte of it.
4770 for (int j = 0; j < NumBytesPerElement; ++j) {
4771 // Note that this is x86 and so always little endian: the low byte is
4772 // the first byte of the mask.
4773 RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4774 MaskElement = MaskElement.lshr(8);
4777 DecodePSHUFBMask(RawMask, Mask);
4781 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4785 SDValue Ptr = MaskLoad->getBasePtr();
4786 if (Ptr->getOpcode() == X86ISD::Wrapper ||
4787 Ptr->getOpcode() == X86ISD::WrapperRIP)
4788 Ptr = Ptr->getOperand(0);
4790 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4791 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4794 if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4795 DecodePSHUFBMask(C, Mask);
4803 case X86ISD::VPERMI:
4804 ImmN = N->getOperand(N->getNumOperands()-1);
4805 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4810 DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4812 case X86ISD::VPERM2X128:
4813 ImmN = N->getOperand(N->getNumOperands()-1);
4814 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4815 if (Mask.empty()) return false;
4816 // Mask only contains negative index if an element is zero.
4817 if (std::any_of(Mask.begin(), Mask.end(),
4818 [](int M){ return M == SM_SentinelZero; }))
4821 case X86ISD::MOVSLDUP:
4822 DecodeMOVSLDUPMask(VT, Mask);
4825 case X86ISD::MOVSHDUP:
4826 DecodeMOVSHDUPMask(VT, Mask);
4829 case X86ISD::MOVDDUP:
4830 DecodeMOVDDUPMask(VT, Mask);
4833 case X86ISD::MOVLHPD:
4834 case X86ISD::MOVLPD:
4835 case X86ISD::MOVLPS:
4836 // Not yet implemented
4838 case X86ISD::VPERMV: {
4840 SDValue MaskNode = N->getOperand(0);
4841 while (MaskNode->getOpcode() == ISD::BITCAST)
4842 MaskNode = MaskNode->getOperand(0);
4844 unsigned MaskLoBits = Log2_64(VT.getVectorNumElements());
4845 SmallVector<uint64_t, 32> RawMask;
4846 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4847 // If we have a build-vector, then things are easy.
4848 assert(MaskNode.getSimpleValueType().isInteger() &&
4849 MaskNode.getSimpleValueType().getVectorNumElements() ==
4850 VT.getVectorNumElements());
4852 for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4853 SDValue Op = MaskNode->getOperand(i);
4854 if (Op->getOpcode() == ISD::UNDEF)
4855 RawMask.push_back((uint64_t)SM_SentinelUndef);
4856 else if (isa<ConstantSDNode>(Op)) {
4857 APInt MaskElement = cast<ConstantSDNode>(Op)->getAPIntValue();
4858 RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4862 DecodeVPERMVMask(RawMask, Mask);
4865 if (MaskNode->getOpcode() == X86ISD::VBROADCAST) {
4866 unsigned NumEltsInMask = MaskNode->getNumOperands();
4867 MaskNode = MaskNode->getOperand(0);
4868 auto *CN = dyn_cast<ConstantSDNode>(MaskNode);
4870 APInt MaskEltValue = CN->getAPIntValue();
4871 for (unsigned i = 0; i < NumEltsInMask; ++i)
4872 RawMask.push_back(MaskEltValue.getLoBits(MaskLoBits).getZExtValue());
4873 DecodeVPERMVMask(RawMask, Mask);
4876 // It may be a scalar load
4879 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4883 SDValue Ptr = MaskLoad->getBasePtr();
4884 if (Ptr->getOpcode() == X86ISD::Wrapper ||
4885 Ptr->getOpcode() == X86ISD::WrapperRIP)
4886 Ptr = Ptr->getOperand(0);
4888 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4889 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4892 auto *C = dyn_cast<Constant>(MaskCP->getConstVal());
4894 DecodeVPERMVMask(C, VT, Mask);
4901 case X86ISD::VPERMV3: {
4903 SDValue MaskNode = N->getOperand(1);
4904 while (MaskNode->getOpcode() == ISD::BITCAST)
4905 MaskNode = MaskNode->getOperand(1);
4907 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4908 // If we have a build-vector, then things are easy.
4909 assert(MaskNode.getSimpleValueType().isInteger() &&
4910 MaskNode.getSimpleValueType().getVectorNumElements() ==
4911 VT.getVectorNumElements());
4913 SmallVector<uint64_t, 32> RawMask;
4914 unsigned MaskLoBits = Log2_64(VT.getVectorNumElements()*2);
4916 for (unsigned i = 0; i < MaskNode->getNumOperands(); ++i) {
4917 SDValue Op = MaskNode->getOperand(i);
4918 if (Op->getOpcode() == ISD::UNDEF)
4919 RawMask.push_back((uint64_t)SM_SentinelUndef);
4921 auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4924 APInt MaskElement = CN->getAPIntValue();
4925 RawMask.push_back(MaskElement.getLoBits(MaskLoBits).getZExtValue());
4928 DecodeVPERMV3Mask(RawMask, Mask);
4932 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4936 SDValue Ptr = MaskLoad->getBasePtr();
4937 if (Ptr->getOpcode() == X86ISD::Wrapper ||
4938 Ptr->getOpcode() == X86ISD::WrapperRIP)
4939 Ptr = Ptr->getOperand(0);
4941 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4942 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4945 auto *C = dyn_cast<Constant>(MaskCP->getConstVal());
4947 DecodeVPERMV3Mask(C, VT, Mask);
4954 default: llvm_unreachable("unknown target shuffle node");
4957 // If we have a fake unary shuffle, the shuffle mask is spread across two
4958 // inputs that are actually the same node. Re-map the mask to always point
4959 // into the first input.
4962 if (M >= (int)Mask.size())
4968 /// Returns the scalar element that will make up the ith
4969 /// element of the result of the vector shuffle.
4970 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4973 return SDValue(); // Limit search depth.
4975 SDValue V = SDValue(N, 0);
4976 EVT VT = V.getValueType();
4977 unsigned Opcode = V.getOpcode();
4979 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4980 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4981 int Elt = SV->getMaskElt(Index);
4984 return DAG.getUNDEF(VT.getVectorElementType());
4986 unsigned NumElems = VT.getVectorNumElements();
4987 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4988 : SV->getOperand(1);
4989 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4992 // Recurse into target specific vector shuffles to find scalars.
4993 if (isTargetShuffle(Opcode)) {
4994 MVT ShufVT = V.getSimpleValueType();
4995 unsigned NumElems = ShufVT.getVectorNumElements();
4996 SmallVector<int, 16> ShuffleMask;
4999 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5002 int Elt = ShuffleMask[Index];
5004 return DAG.getUNDEF(ShufVT.getVectorElementType());
5006 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5008 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5012 // Actual nodes that may contain scalar elements
5013 if (Opcode == ISD::BITCAST) {
5014 V = V.getOperand(0);
5015 EVT SrcVT = V.getValueType();
5016 unsigned NumElems = VT.getVectorNumElements();
5018 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5022 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5023 return (Index == 0) ? V.getOperand(0)
5024 : DAG.getUNDEF(VT.getVectorElementType());
5026 if (V.getOpcode() == ISD::BUILD_VECTOR)
5027 return V.getOperand(Index);
5032 /// Custom lower build_vector of v16i8.
5033 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5034 unsigned NumNonZero, unsigned NumZero,
5036 const X86Subtarget* Subtarget,
5037 const TargetLowering &TLI) {
5045 // SSE4.1 - use PINSRB to insert each byte directly.
5046 if (Subtarget->hasSSE41()) {
5047 for (unsigned i = 0; i < 16; ++i) {
5048 bool isNonZero = (NonZeros & (1 << i)) != 0;
5052 V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
5054 V = DAG.getUNDEF(MVT::v16i8);
5057 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5058 MVT::v16i8, V, Op.getOperand(i),
5059 DAG.getIntPtrConstant(i, dl));
5066 // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
5067 for (unsigned i = 0; i < 16; ++i) {
5068 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5069 if (ThisIsNonZero && First) {
5071 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5073 V = DAG.getUNDEF(MVT::v8i16);
5078 SDValue ThisElt, LastElt;
5079 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5080 if (LastIsNonZero) {
5081 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5082 MVT::i16, Op.getOperand(i-1));
5084 if (ThisIsNonZero) {
5085 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5086 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5087 ThisElt, DAG.getConstant(8, dl, MVT::i8));
5089 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5093 if (ThisElt.getNode())
5094 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5095 DAG.getIntPtrConstant(i/2, dl));
5099 return DAG.getBitcast(MVT::v16i8, V);
5102 /// Custom lower build_vector of v8i16.
5103 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5104 unsigned NumNonZero, unsigned NumZero,
5106 const X86Subtarget* Subtarget,
5107 const TargetLowering &TLI) {
5114 for (unsigned i = 0; i < 8; ++i) {
5115 bool isNonZero = (NonZeros & (1 << i)) != 0;
5119 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5121 V = DAG.getUNDEF(MVT::v8i16);
5124 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5125 MVT::v8i16, V, Op.getOperand(i),
5126 DAG.getIntPtrConstant(i, dl));
5133 /// Custom lower build_vector of v4i32 or v4f32.
5134 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
5135 const X86Subtarget *Subtarget,
5136 const TargetLowering &TLI) {
5137 // Find all zeroable elements.
5138 std::bitset<4> Zeroable;
5139 for (int i=0; i < 4; ++i) {
5140 SDValue Elt = Op->getOperand(i);
5141 Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
5143 assert(Zeroable.size() - Zeroable.count() > 1 &&
5144 "We expect at least two non-zero elements!");
5146 // We only know how to deal with build_vector nodes where elements are either
5147 // zeroable or extract_vector_elt with constant index.
5148 SDValue FirstNonZero;
5149 unsigned FirstNonZeroIdx;
5150 for (unsigned i=0; i < 4; ++i) {
5153 SDValue Elt = Op->getOperand(i);
5154 if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5155 !isa<ConstantSDNode>(Elt.getOperand(1)))
5157 // Make sure that this node is extracting from a 128-bit vector.
5158 MVT VT = Elt.getOperand(0).getSimpleValueType();
5159 if (!VT.is128BitVector())
5161 if (!FirstNonZero.getNode()) {
5163 FirstNonZeroIdx = i;
5167 assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
5168 SDValue V1 = FirstNonZero.getOperand(0);
5169 MVT VT = V1.getSimpleValueType();
5171 // See if this build_vector can be lowered as a blend with zero.
5173 unsigned EltMaskIdx, EltIdx;
5175 for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
5176 if (Zeroable[EltIdx]) {
5177 // The zero vector will be on the right hand side.
5178 Mask[EltIdx] = EltIdx+4;
5182 Elt = Op->getOperand(EltIdx);
5183 // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
5184 EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
5185 if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
5187 Mask[EltIdx] = EltIdx;
5191 // Let the shuffle legalizer deal with blend operations.
5192 SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
5193 if (V1.getSimpleValueType() != VT)
5194 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
5195 return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
5198 // See if we can lower this build_vector to a INSERTPS.
5199 if (!Subtarget->hasSSE41())
5202 SDValue V2 = Elt.getOperand(0);
5203 if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
5206 bool CanFold = true;
5207 for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
5211 SDValue Current = Op->getOperand(i);
5212 SDValue SrcVector = Current->getOperand(0);
5215 CanFold = SrcVector == V1 &&
5216 cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
5222 assert(V1.getNode() && "Expected at least two non-zero elements!");
5223 if (V1.getSimpleValueType() != MVT::v4f32)
5224 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
5225 if (V2.getSimpleValueType() != MVT::v4f32)
5226 V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
5228 // Ok, we can emit an INSERTPS instruction.
5229 unsigned ZMask = Zeroable.to_ulong();
5231 unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
5232 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
5234 SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
5235 DAG.getIntPtrConstant(InsertPSMask, DL));
5236 return DAG.getBitcast(VT, Result);
5239 /// Return a vector logical shift node.
5240 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5241 unsigned NumBits, SelectionDAG &DAG,
5242 const TargetLowering &TLI, SDLoc dl) {
5243 assert(VT.is128BitVector() && "Unknown type for VShift");
5244 MVT ShVT = MVT::v2i64;
5245 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5246 SrcOp = DAG.getBitcast(ShVT, SrcOp);
5247 MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
5248 assert(NumBits % 8 == 0 && "Only support byte sized shifts");
5249 SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
5250 return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
5254 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5256 // Check if the scalar load can be widened into a vector load. And if
5257 // the address is "base + cst" see if the cst can be "absorbed" into
5258 // the shuffle mask.
5259 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5260 SDValue Ptr = LD->getBasePtr();
5261 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5263 EVT PVT = LD->getValueType(0);
5264 if (PVT != MVT::i32 && PVT != MVT::f32)
5269 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5270 FI = FINode->getIndex();
5272 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5273 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5274 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5275 Offset = Ptr.getConstantOperandVal(1);
5276 Ptr = Ptr.getOperand(0);
5281 // FIXME: 256-bit vector instructions don't require a strict alignment,
5282 // improve this code to support it better.
5283 unsigned RequiredAlign = VT.getSizeInBits()/8;
5284 SDValue Chain = LD->getChain();
5285 // Make sure the stack object alignment is at least 16 or 32.
5286 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5287 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5288 if (MFI->isFixedObjectIndex(FI)) {
5289 // Can't change the alignment. FIXME: It's possible to compute
5290 // the exact stack offset and reference FI + adjust offset instead.
5291 // If someone *really* cares about this. That's the way to implement it.
5294 MFI->setObjectAlignment(FI, RequiredAlign);
5298 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5299 // Ptr + (Offset & ~15).
5302 if ((Offset % RequiredAlign) & 3)
5304 int64_t StartOffset = Offset & ~int64_t(RequiredAlign - 1);
5307 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5308 DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
5311 int EltNo = (Offset - StartOffset) >> 2;
5312 unsigned NumElems = VT.getVectorNumElements();
5314 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5315 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5316 LD->getPointerInfo().getWithOffset(StartOffset),
5317 false, false, false, 0);
5319 SmallVector<int, 8> Mask(NumElems, EltNo);
5321 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5327 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
5328 /// elements can be replaced by a single large load which has the same value as
5329 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
5331 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5333 /// FIXME: we'd also like to handle the case where the last elements are zero
5334 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5335 /// There's even a handy isZeroNode for that purpose.
5336 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
5337 SDLoc &DL, SelectionDAG &DAG,
5338 bool isAfterLegalize) {
5339 unsigned NumElems = Elts.size();
5341 LoadSDNode *LDBase = nullptr;
5342 unsigned LastLoadedElt = -1U;
5344 // For each element in the initializer, see if we've found a load or an undef.
5345 // If we don't find an initial load element, or later load elements are
5346 // non-consecutive, bail out.
5347 for (unsigned i = 0; i < NumElems; ++i) {
5348 SDValue Elt = Elts[i];
5349 // Look through a bitcast.
5350 if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
5351 Elt = Elt.getOperand(0);
5352 if (!Elt.getNode() ||
5353 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5356 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5358 LDBase = cast<LoadSDNode>(Elt.getNode());
5362 if (Elt.getOpcode() == ISD::UNDEF)
5365 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5366 EVT LdVT = Elt.getValueType();
5367 // Each loaded element must be the correct fractional portion of the
5368 // requested vector load.
5369 if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
5371 if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
5376 // If we have found an entire vector of loads and undefs, then return a large
5377 // load of the entire vector width starting at the base pointer. If we found
5378 // consecutive loads for the low half, generate a vzext_load node.
5379 if (LastLoadedElt == NumElems - 1) {
5380 assert(LDBase && "Did not find base load for merging consecutive loads");
5381 EVT EltVT = LDBase->getValueType(0);
5382 // Ensure that the input vector size for the merged loads matches the
5383 // cumulative size of the input elements.
5384 if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5387 if (isAfterLegalize &&
5388 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5391 SDValue NewLd = SDValue();
5393 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5394 LDBase->getPointerInfo(), LDBase->isVolatile(),
5395 LDBase->isNonTemporal(), LDBase->isInvariant(),
5396 LDBase->getAlignment());
5398 if (LDBase->hasAnyUseOfValue(1)) {
5399 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5401 SDValue(NewLd.getNode(), 1));
5402 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5403 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5404 SDValue(NewLd.getNode(), 1));
5410 //TODO: The code below fires only for for loading the low v2i32 / v2f32
5411 //of a v4i32 / v4f32. It's probably worth generalizing.
5412 EVT EltVT = VT.getVectorElementType();
5413 if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5414 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5415 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5416 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5418 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5419 LDBase->getPointerInfo(),
5420 LDBase->getAlignment(),
5421 false/*isVolatile*/, true/*ReadMem*/,
5424 // Make sure the newly-created LOAD is in the same position as LDBase in
5425 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5426 // update uses of LDBase's output chain to use the TokenFactor.
5427 if (LDBase->hasAnyUseOfValue(1)) {
5428 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5429 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5430 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5431 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5432 SDValue(ResNode.getNode(), 1));
5435 return DAG.getBitcast(VT, ResNode);
5440 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5441 /// to generate a splat value for the following cases:
5442 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5443 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5444 /// a scalar load, or a constant.
5445 /// The VBROADCAST node is returned when a pattern is found,
5446 /// or SDValue() otherwise.
5447 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5448 SelectionDAG &DAG) {
5449 // VBROADCAST requires AVX.
5450 // TODO: Splats could be generated for non-AVX CPUs using SSE
5451 // instructions, but there's less potential gain for only 128-bit vectors.
5452 if (!Subtarget->hasAVX())
5455 MVT VT = Op.getSimpleValueType();
5458 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5459 "Unsupported vector type for broadcast.");
5464 switch (Op.getOpcode()) {
5466 // Unknown pattern found.
5469 case ISD::BUILD_VECTOR: {
5470 auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5471 BitVector UndefElements;
5472 SDValue Splat = BVOp->getSplatValue(&UndefElements);
5474 // We need a splat of a single value to use broadcast, and it doesn't
5475 // make any sense if the value is only in one element of the vector.
5476 if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5480 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5481 Ld.getOpcode() == ISD::ConstantFP);
5483 // Make sure that all of the users of a non-constant load are from the
5484 // BUILD_VECTOR node.
5485 if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5490 case ISD::VECTOR_SHUFFLE: {
5491 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5493 // Shuffles must have a splat mask where the first element is
5495 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5498 SDValue Sc = Op.getOperand(0);
5499 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5500 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5502 if (!Subtarget->hasInt256())
5505 // Use the register form of the broadcast instruction available on AVX2.
5506 if (VT.getSizeInBits() >= 256)
5507 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5508 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5511 Ld = Sc.getOperand(0);
5512 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5513 Ld.getOpcode() == ISD::ConstantFP);
5515 // The scalar_to_vector node and the suspected
5516 // load node must have exactly one user.
5517 // Constants may have multiple users.
5519 // AVX-512 has register version of the broadcast
5520 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5521 Ld.getValueType().getSizeInBits() >= 32;
5522 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5529 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5530 bool IsGE256 = (VT.getSizeInBits() >= 256);
5532 // When optimizing for size, generate up to 5 extra bytes for a broadcast
5533 // instruction to save 8 or more bytes of constant pool data.
5534 // TODO: If multiple splats are generated to load the same constant,
5535 // it may be detrimental to overall size. There needs to be a way to detect
5536 // that condition to know if this is truly a size win.
5537 bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
5539 // Handle broadcasting a single constant scalar from the constant pool
5541 // On Sandybridge (no AVX2), it is still better to load a constant vector
5542 // from the constant pool and not to broadcast it from a scalar.
5543 // But override that restriction when optimizing for size.
5544 // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5545 if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5546 EVT CVT = Ld.getValueType();
5547 assert(!CVT.isVector() && "Must not broadcast a vector type");
5549 // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5550 // For size optimization, also splat v2f64 and v2i64, and for size opt
5551 // with AVX2, also splat i8 and i16.
5552 // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5553 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5554 (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5555 const Constant *C = nullptr;
5556 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5557 C = CI->getConstantIntValue();
5558 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5559 C = CF->getConstantFPValue();
5561 assert(C && "Invalid constant type");
5563 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5565 DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5566 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5568 CVT, dl, DAG.getEntryNode(), CP,
5569 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), false,
5570 false, false, Alignment);
5572 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5576 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5578 // Handle AVX2 in-register broadcasts.
5579 if (!IsLoad && Subtarget->hasInt256() &&
5580 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5581 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5583 // The scalar source must be a normal load.
5587 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5588 (Subtarget->hasVLX() && ScalarSize == 64))
5589 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5591 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5592 // double since there is no vbroadcastsd xmm
5593 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5594 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5595 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5598 // Unsupported broadcast.
5602 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5603 /// underlying vector and index.
5605 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5607 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5609 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5610 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5613 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5615 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5617 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5618 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5621 // In this case the vector is the extract_subvector expression and the index
5622 // is 2, as specified by the shuffle.
5623 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5624 SDValue ShuffleVec = SVOp->getOperand(0);
5625 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5626 assert(ShuffleVecVT.getVectorElementType() ==
5627 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5629 int ShuffleIdx = SVOp->getMaskElt(Idx);
5630 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5631 ExtractedFromVec = ShuffleVec;
5637 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5638 MVT VT = Op.getSimpleValueType();
5640 // Skip if insert_vec_elt is not supported.
5641 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5642 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5646 unsigned NumElems = Op.getNumOperands();
5650 SmallVector<unsigned, 4> InsertIndices;
5651 SmallVector<int, 8> Mask(NumElems, -1);
5653 for (unsigned i = 0; i != NumElems; ++i) {
5654 unsigned Opc = Op.getOperand(i).getOpcode();
5656 if (Opc == ISD::UNDEF)
5659 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5660 // Quit if more than 1 elements need inserting.
5661 if (InsertIndices.size() > 1)
5664 InsertIndices.push_back(i);
5668 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5669 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5670 // Quit if non-constant index.
5671 if (!isa<ConstantSDNode>(ExtIdx))
5673 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5675 // Quit if extracted from vector of different type.
5676 if (ExtractedFromVec.getValueType() != VT)
5679 if (!VecIn1.getNode())
5680 VecIn1 = ExtractedFromVec;
5681 else if (VecIn1 != ExtractedFromVec) {
5682 if (!VecIn2.getNode())
5683 VecIn2 = ExtractedFromVec;
5684 else if (VecIn2 != ExtractedFromVec)
5685 // Quit if more than 2 vectors to shuffle
5689 if (ExtractedFromVec == VecIn1)
5691 else if (ExtractedFromVec == VecIn2)
5692 Mask[i] = Idx + NumElems;
5695 if (!VecIn1.getNode())
5698 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5699 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5700 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5701 unsigned Idx = InsertIndices[i];
5702 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5703 DAG.getIntPtrConstant(Idx, DL));
5709 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
5710 assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5711 Op.getScalarValueSizeInBits() == 1 &&
5712 "Can not convert non-constant vector");
5713 uint64_t Immediate = 0;
5714 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5715 SDValue In = Op.getOperand(idx);
5716 if (In.getOpcode() != ISD::UNDEF)
5717 Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5721 MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5722 return DAG.getConstant(Immediate, dl, VT);
5724 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5726 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5728 MVT VT = Op.getSimpleValueType();
5729 assert((VT.getVectorElementType() == MVT::i1) &&
5730 "Unexpected type in LowerBUILD_VECTORvXi1!");
5733 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5734 SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5735 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5736 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5739 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5740 SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5741 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5742 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5745 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5746 SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
5747 if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5748 return DAG.getBitcast(VT, Imm);
5749 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5750 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5751 DAG.getIntPtrConstant(0, dl));
5754 // Vector has one or more non-const elements
5755 uint64_t Immediate = 0;
5756 SmallVector<unsigned, 16> NonConstIdx;
5757 bool IsSplat = true;
5758 bool HasConstElts = false;
5760 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5761 SDValue In = Op.getOperand(idx);
5762 if (In.getOpcode() == ISD::UNDEF)
5764 if (!isa<ConstantSDNode>(In))
5765 NonConstIdx.push_back(idx);
5767 Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5768 HasConstElts = true;
5772 else if (In != Op.getOperand(SplatIdx))
5776 // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5778 return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5779 DAG.getConstant(1, dl, VT),
5780 DAG.getConstant(0, dl, VT));
5782 // insert elements one by one
5786 MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5787 Imm = DAG.getConstant(Immediate, dl, ImmVT);
5789 else if (HasConstElts)
5790 Imm = DAG.getConstant(0, dl, VT);
5792 Imm = DAG.getUNDEF(VT);
5793 if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5794 DstVec = DAG.getBitcast(VT, Imm);
5796 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5797 DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5798 DAG.getIntPtrConstant(0, dl));
5801 for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5802 unsigned InsertIdx = NonConstIdx[i];
5803 DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5804 Op.getOperand(InsertIdx),
5805 DAG.getIntPtrConstant(InsertIdx, dl));
5810 /// \brief Return true if \p N implements a horizontal binop and return the
5811 /// operands for the horizontal binop into V0 and V1.
5813 /// This is a helper function of LowerToHorizontalOp().
5814 /// This function checks that the build_vector \p N in input implements a
5815 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5816 /// operation to match.
5817 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5818 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5819 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5822 /// This function only analyzes elements of \p N whose indices are
5823 /// in range [BaseIdx, LastIdx).
5824 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5826 unsigned BaseIdx, unsigned LastIdx,
5827 SDValue &V0, SDValue &V1) {
5828 EVT VT = N->getValueType(0);
5830 assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5831 assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5832 "Invalid Vector in input!");
5834 bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5835 bool CanFold = true;
5836 unsigned ExpectedVExtractIdx = BaseIdx;
5837 unsigned NumElts = LastIdx - BaseIdx;
5838 V0 = DAG.getUNDEF(VT);
5839 V1 = DAG.getUNDEF(VT);
5841 // Check if N implements a horizontal binop.
5842 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5843 SDValue Op = N->getOperand(i + BaseIdx);
5846 if (Op->getOpcode() == ISD::UNDEF) {
5847 // Update the expected vector extract index.
5848 if (i * 2 == NumElts)
5849 ExpectedVExtractIdx = BaseIdx;
5850 ExpectedVExtractIdx += 2;
5854 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5859 SDValue Op0 = Op.getOperand(0);
5860 SDValue Op1 = Op.getOperand(1);
5862 // Try to match the following pattern:
5863 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5864 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5865 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5866 Op0.getOperand(0) == Op1.getOperand(0) &&
5867 isa<ConstantSDNode>(Op0.getOperand(1)) &&
5868 isa<ConstantSDNode>(Op1.getOperand(1)));
5872 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5873 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5875 if (i * 2 < NumElts) {
5876 if (V0.getOpcode() == ISD::UNDEF) {
5877 V0 = Op0.getOperand(0);
5878 if (V0.getValueType() != VT)
5882 if (V1.getOpcode() == ISD::UNDEF) {
5883 V1 = Op0.getOperand(0);
5884 if (V1.getValueType() != VT)
5887 if (i * 2 == NumElts)
5888 ExpectedVExtractIdx = BaseIdx;
5891 SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5892 if (I0 == ExpectedVExtractIdx)
5893 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5894 else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5895 // Try to match the following dag sequence:
5896 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5897 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5901 ExpectedVExtractIdx += 2;
5907 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5908 /// a concat_vector.
5910 /// This is a helper function of LowerToHorizontalOp().
5911 /// This function expects two 256-bit vectors called V0 and V1.
5912 /// At first, each vector is split into two separate 128-bit vectors.
5913 /// Then, the resulting 128-bit vectors are used to implement two
5914 /// horizontal binary operations.
5916 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5918 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5919 /// the two new horizontal binop.
5920 /// When Mode is set, the first horizontal binop dag node would take as input
5921 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5922 /// horizontal binop dag node would take as input the lower 128-bit of V1
5923 /// and the upper 128-bit of V1.
5925 /// HADD V0_LO, V0_HI
5926 /// HADD V1_LO, V1_HI
5928 /// Otherwise, the first horizontal binop dag node takes as input the lower
5929 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5930 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5932 /// HADD V0_LO, V1_LO
5933 /// HADD V0_HI, V1_HI
5935 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5936 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5937 /// the upper 128-bits of the result.
5938 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5939 SDLoc DL, SelectionDAG &DAG,
5940 unsigned X86Opcode, bool Mode,
5941 bool isUndefLO, bool isUndefHI) {
5942 EVT VT = V0.getValueType();
5943 assert(VT.is256BitVector() && VT == V1.getValueType() &&
5944 "Invalid nodes in input!");
5946 unsigned NumElts = VT.getVectorNumElements();
5947 SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5948 SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5949 SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5950 SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5951 EVT NewVT = V0_LO.getValueType();
5953 SDValue LO = DAG.getUNDEF(NewVT);
5954 SDValue HI = DAG.getUNDEF(NewVT);
5957 // Don't emit a horizontal binop if the result is expected to be UNDEF.
5958 if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5959 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5960 if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5961 HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5963 // Don't emit a horizontal binop if the result is expected to be UNDEF.
5964 if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5965 V1_LO->getOpcode() != ISD::UNDEF))
5966 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5968 if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5969 V1_HI->getOpcode() != ISD::UNDEF))
5970 HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5973 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5976 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5978 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5979 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5980 MVT VT = BV->getSimpleValueType(0);
5981 if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5982 (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5986 unsigned NumElts = VT.getVectorNumElements();
5987 SDValue InVec0 = DAG.getUNDEF(VT);
5988 SDValue InVec1 = DAG.getUNDEF(VT);
5990 assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5991 VT == MVT::v2f64) && "build_vector with an invalid type found!");
5993 // Odd-numbered elements in the input build vector are obtained from
5994 // adding two integer/float elements.
5995 // Even-numbered elements in the input build vector are obtained from
5996 // subtracting two integer/float elements.
5997 unsigned ExpectedOpcode = ISD::FSUB;
5998 unsigned NextExpectedOpcode = ISD::FADD;
5999 bool AddFound = false;
6000 bool SubFound = false;
6002 for (unsigned i = 0, e = NumElts; i != e; ++i) {
6003 SDValue Op = BV->getOperand(i);
6005 // Skip 'undef' values.
6006 unsigned Opcode = Op.getOpcode();
6007 if (Opcode == ISD::UNDEF) {
6008 std::swap(ExpectedOpcode, NextExpectedOpcode);
6012 // Early exit if we found an unexpected opcode.
6013 if (Opcode != ExpectedOpcode)
6016 SDValue Op0 = Op.getOperand(0);
6017 SDValue Op1 = Op.getOperand(1);
6019 // Try to match the following pattern:
6020 // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6021 // Early exit if we cannot match that sequence.
6022 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6023 Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6024 !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6025 !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6026 Op0.getOperand(1) != Op1.getOperand(1))
6029 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6033 // We found a valid add/sub node. Update the information accordingly.
6039 // Update InVec0 and InVec1.
6040 if (InVec0.getOpcode() == ISD::UNDEF) {
6041 InVec0 = Op0.getOperand(0);
6042 if (InVec0.getSimpleValueType() != VT)
6045 if (InVec1.getOpcode() == ISD::UNDEF) {
6046 InVec1 = Op1.getOperand(0);
6047 if (InVec1.getSimpleValueType() != VT)
6051 // Make sure that operands in input to each add/sub node always
6052 // come from a same pair of vectors.
6053 if (InVec0 != Op0.getOperand(0)) {
6054 if (ExpectedOpcode == ISD::FSUB)
6057 // FADD is commutable. Try to commute the operands
6058 // and then test again.
6059 std::swap(Op0, Op1);
6060 if (InVec0 != Op0.getOperand(0))
6064 if (InVec1 != Op1.getOperand(0))
6067 // Update the pair of expected opcodes.
6068 std::swap(ExpectedOpcode, NextExpectedOpcode);
6071 // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
6072 if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6073 InVec1.getOpcode() != ISD::UNDEF)
6074 return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
6079 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
6080 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
6081 const X86Subtarget *Subtarget,
6082 SelectionDAG &DAG) {
6083 MVT VT = BV->getSimpleValueType(0);
6084 unsigned NumElts = VT.getVectorNumElements();
6085 unsigned NumUndefsLO = 0;
6086 unsigned NumUndefsHI = 0;
6087 unsigned Half = NumElts/2;
6089 // Count the number of UNDEF operands in the build_vector in input.
6090 for (unsigned i = 0, e = Half; i != e; ++i)
6091 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6094 for (unsigned i = Half, e = NumElts; i != e; ++i)
6095 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6098 // Early exit if this is either a build_vector of all UNDEFs or all the
6099 // operands but one are UNDEF.
6100 if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6104 SDValue InVec0, InVec1;
6105 if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6106 // Try to match an SSE3 float HADD/HSUB.
6107 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6108 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6110 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6111 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6112 } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6113 // Try to match an SSSE3 integer HADD/HSUB.
6114 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6115 return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6117 if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6118 return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6121 if (!Subtarget->hasAVX())
6124 if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6125 // Try to match an AVX horizontal add/sub of packed single/double
6126 // precision floating point values from 256-bit vectors.
6127 SDValue InVec2, InVec3;
6128 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6129 isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6130 ((InVec0.getOpcode() == ISD::UNDEF ||
6131 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6132 ((InVec1.getOpcode() == ISD::UNDEF ||
6133 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6134 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6136 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6137 isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6138 ((InVec0.getOpcode() == ISD::UNDEF ||
6139 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6140 ((InVec1.getOpcode() == ISD::UNDEF ||
6141 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6142 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6143 } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6144 // Try to match an AVX2 horizontal add/sub of signed integers.
6145 SDValue InVec2, InVec3;
6147 bool CanFold = true;
6149 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6150 isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6151 ((InVec0.getOpcode() == ISD::UNDEF ||
6152 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6153 ((InVec1.getOpcode() == ISD::UNDEF ||
6154 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6155 X86Opcode = X86ISD::HADD;
6156 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6157 isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6158 ((InVec0.getOpcode() == ISD::UNDEF ||
6159 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6160 ((InVec1.getOpcode() == ISD::UNDEF ||
6161 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6162 X86Opcode = X86ISD::HSUB;
6167 // Fold this build_vector into a single horizontal add/sub.
6168 // Do this only if the target has AVX2.
6169 if (Subtarget->hasAVX2())
6170 return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6172 // Do not try to expand this build_vector into a pair of horizontal
6173 // add/sub if we can emit a pair of scalar add/sub.
6174 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6177 // Convert this build_vector into a pair of horizontal binop followed by
6179 bool isUndefLO = NumUndefsLO == Half;
6180 bool isUndefHI = NumUndefsHI == Half;
6181 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6182 isUndefLO, isUndefHI);
6186 if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6187 VT == MVT::v16i16) && Subtarget->hasAVX()) {
6189 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6190 X86Opcode = X86ISD::HADD;
6191 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6192 X86Opcode = X86ISD::HSUB;
6193 else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6194 X86Opcode = X86ISD::FHADD;
6195 else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6196 X86Opcode = X86ISD::FHSUB;
6200 // Don't try to expand this build_vector into a pair of horizontal add/sub
6201 // if we can simply emit a pair of scalar add/sub.
6202 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6205 // Convert this build_vector into two horizontal add/sub followed by
6207 bool isUndefLO = NumUndefsLO == Half;
6208 bool isUndefHI = NumUndefsHI == Half;
6209 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6210 isUndefLO, isUndefHI);
6217 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6220 MVT VT = Op.getSimpleValueType();
6221 MVT ExtVT = VT.getVectorElementType();
6222 unsigned NumElems = Op.getNumOperands();
6224 // Generate vectors for predicate vectors.
6225 if (VT.getVectorElementType() == MVT::i1 && Subtarget->hasAVX512())
6226 return LowerBUILD_VECTORvXi1(Op, DAG);
6228 // Vectors containing all zeros can be matched by pxor and xorps later
6229 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6230 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6231 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6232 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6235 return getZeroVector(VT, Subtarget, DAG, dl);
6238 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6239 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6240 // vpcmpeqd on 256-bit vectors.
6241 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6242 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6245 if (!VT.is512BitVector())
6246 return getOnesVector(VT, Subtarget, DAG, dl);
6249 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
6250 if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
6252 if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
6253 return HorizontalOp;
6254 if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
6257 unsigned EVTBits = ExtVT.getSizeInBits();
6259 unsigned NumZero = 0;
6260 unsigned NumNonZero = 0;
6261 uint64_t NonZeros = 0;
6262 bool IsAllConstants = true;
6263 SmallSet<SDValue, 8> Values;
6264 for (unsigned i = 0; i < NumElems; ++i) {
6265 SDValue Elt = Op.getOperand(i);
6266 if (Elt.getOpcode() == ISD::UNDEF)
6269 if (Elt.getOpcode() != ISD::Constant &&
6270 Elt.getOpcode() != ISD::ConstantFP)
6271 IsAllConstants = false;
6272 if (X86::isZeroNode(Elt))
6275 assert(i < sizeof(NonZeros) * 8); // Make sure the shift is within range.
6276 NonZeros |= ((uint64_t)1 << i);
6281 // All undef vector. Return an UNDEF. All zero vectors were handled above.
6282 if (NumNonZero == 0)
6283 return DAG.getUNDEF(VT);
6285 // Special case for single non-zero, non-undef, element.
6286 if (NumNonZero == 1) {
6287 unsigned Idx = countTrailingZeros(NonZeros);
6288 SDValue Item = Op.getOperand(Idx);
6290 // If this is an insertion of an i64 value on x86-32, and if the top bits of
6291 // the value are obviously zero, truncate the value to i32 and do the
6292 // insertion that way. Only do this if the value is non-constant or if the
6293 // value is a constant being inserted into element 0. It is cheaper to do
6294 // a constant pool load than it is to do a movd + shuffle.
6295 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6296 (!IsAllConstants || Idx == 0)) {
6297 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6299 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6300 MVT VecVT = MVT::v4i32;
6302 // Truncate the value (which may itself be a constant) to i32, and
6303 // convert it to a vector with movd (S2V+shuffle to zero extend).
6304 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6305 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6306 return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
6307 Item, Idx * 2, true, Subtarget, DAG));
6311 // If we have a constant or non-constant insertion into the low element of
6312 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6313 // the rest of the elements. This will be matched as movd/movq/movss/movsd
6314 // depending on what the source datatype is.
6317 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6319 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6320 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6321 if (VT.is512BitVector()) {
6322 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6323 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6324 Item, DAG.getIntPtrConstant(0, dl));
6326 assert((VT.is128BitVector() || VT.is256BitVector()) &&
6327 "Expected an SSE value type!");
6328 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6329 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6330 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6333 // We can't directly insert an i8 or i16 into a vector, so zero extend
6335 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6336 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6337 if (VT.is256BitVector()) {
6338 if (Subtarget->hasAVX()) {
6339 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
6340 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6342 // Without AVX, we need to extend to a 128-bit vector and then
6343 // insert into the 256-bit vector.
6344 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6345 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6346 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6349 assert(VT.is128BitVector() && "Expected an SSE value type!");
6350 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6351 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6353 return DAG.getBitcast(VT, Item);
6357 // Is it a vector logical left shift?
6358 if (NumElems == 2 && Idx == 1 &&
6359 X86::isZeroNode(Op.getOperand(0)) &&
6360 !X86::isZeroNode(Op.getOperand(1))) {
6361 unsigned NumBits = VT.getSizeInBits();
6362 return getVShift(true, VT,
6363 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6364 VT, Op.getOperand(1)),
6365 NumBits/2, DAG, *this, dl);
6368 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6371 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6372 // is a non-constant being inserted into an element other than the low one,
6373 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6374 // movd/movss) to move this into the low element, then shuffle it into
6376 if (EVTBits == 32) {
6377 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6378 return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6382 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6383 if (Values.size() == 1) {
6384 if (EVTBits == 32) {
6385 // Instead of a shuffle like this:
6386 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6387 // Check if it's possible to issue this instead.
6388 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6389 unsigned Idx = countTrailingZeros(NonZeros);
6390 SDValue Item = Op.getOperand(Idx);
6391 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6392 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6397 // A vector full of immediates; various special cases are already
6398 // handled, so this is best done with a single constant-pool load.
6402 // For AVX-length vectors, see if we can use a vector load to get all of the
6403 // elements, otherwise build the individual 128-bit pieces and use
6404 // shuffles to put them in place.
6405 if (VT.is256BitVector() || VT.is512BitVector()) {
6406 SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6408 // Check for a build vector of consecutive loads.
6409 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6412 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6414 // Build both the lower and upper subvector.
6415 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6416 makeArrayRef(&V[0], NumElems/2));
6417 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6418 makeArrayRef(&V[NumElems / 2], NumElems/2));
6420 // Recreate the wider vector with the lower and upper part.
6421 if (VT.is256BitVector())
6422 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6423 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6426 // Let legalizer expand 2-wide build_vectors.
6427 if (EVTBits == 64) {
6428 if (NumNonZero == 1) {
6429 // One half is zero or undef.
6430 unsigned Idx = countTrailingZeros(NonZeros);
6431 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6432 Op.getOperand(Idx));
6433 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6438 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6439 if (EVTBits == 8 && NumElems == 16)
6440 if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros, NumNonZero, NumZero,
6441 DAG, Subtarget, *this))
6444 if (EVTBits == 16 && NumElems == 8)
6445 if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros, NumNonZero, NumZero,
6446 DAG, Subtarget, *this))
6449 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6450 if (EVTBits == 32 && NumElems == 4)
6451 if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6454 // If element VT is == 32 bits, turn it into a number of shuffles.
6455 SmallVector<SDValue, 8> V(NumElems);
6456 if (NumElems == 4 && NumZero > 0) {
6457 for (unsigned i = 0; i < 4; ++i) {
6458 bool isZero = !(NonZeros & (1ULL << i));
6460 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6462 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6465 for (unsigned i = 0; i < 2; ++i) {
6466 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6469 V[i] = V[i*2]; // Must be a zero vector.
6472 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6475 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6478 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6483 bool Reverse1 = (NonZeros & 0x3) == 2;
6484 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6488 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6489 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6491 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6494 if (Values.size() > 1 && VT.is128BitVector()) {
6495 // Check for a build vector of consecutive loads.
6496 for (unsigned i = 0; i < NumElems; ++i)
6497 V[i] = Op.getOperand(i);
6499 // Check for elements which are consecutive loads.
6500 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6503 // Check for a build vector from mostly shuffle plus few inserting.
6504 if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6507 // For SSE 4.1, use insertps to put the high elements into the low element.
6508 if (Subtarget->hasSSE41()) {
6510 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6511 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6513 Result = DAG.getUNDEF(VT);
6515 for (unsigned i = 1; i < NumElems; ++i) {
6516 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6517 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6518 Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6523 // Otherwise, expand into a number of unpckl*, start by extending each of
6524 // our (non-undef) elements to the full vector width with the element in the
6525 // bottom slot of the vector (which generates no code for SSE).
6526 for (unsigned i = 0; i < NumElems; ++i) {
6527 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6528 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6530 V[i] = DAG.getUNDEF(VT);
6533 // Next, we iteratively mix elements, e.g. for v4f32:
6534 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6535 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6536 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6537 unsigned EltStride = NumElems >> 1;
6538 while (EltStride != 0) {
6539 for (unsigned i = 0; i < EltStride; ++i) {
6540 // If V[i+EltStride] is undef and this is the first round of mixing,
6541 // then it is safe to just drop this shuffle: V[i] is already in the
6542 // right place, the one element (since it's the first round) being
6543 // inserted as undef can be dropped. This isn't safe for successive
6544 // rounds because they will permute elements within both vectors.
6545 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6546 EltStride == NumElems/2)
6549 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6558 // 256-bit AVX can use the vinsertf128 instruction
6559 // to create 256-bit vectors from two other 128-bit ones.
6560 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6562 MVT ResVT = Op.getSimpleValueType();
6564 assert((ResVT.is256BitVector() ||
6565 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6567 SDValue V1 = Op.getOperand(0);
6568 SDValue V2 = Op.getOperand(1);
6569 unsigned NumElems = ResVT.getVectorNumElements();
6570 if (ResVT.is256BitVector())
6571 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6573 if (Op.getNumOperands() == 4) {
6574 MVT HalfVT = MVT::getVectorVT(ResVT.getVectorElementType(),
6575 ResVT.getVectorNumElements()/2);
6576 SDValue V3 = Op.getOperand(2);
6577 SDValue V4 = Op.getOperand(3);
6578 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6579 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6581 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6584 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6585 const X86Subtarget *Subtarget,
6586 SelectionDAG & DAG) {
6588 MVT ResVT = Op.getSimpleValueType();
6589 unsigned NumOfOperands = Op.getNumOperands();
6591 assert(isPowerOf2_32(NumOfOperands) &&
6592 "Unexpected number of operands in CONCAT_VECTORS");
6594 SDValue Undef = DAG.getUNDEF(ResVT);
6595 if (NumOfOperands > 2) {
6596 // Specialize the cases when all, or all but one, of the operands are undef.
6597 unsigned NumOfDefinedOps = 0;
6599 for (unsigned i = 0; i < NumOfOperands; i++)
6600 if (!Op.getOperand(i).isUndef()) {
6604 if (NumOfDefinedOps == 0)
6606 if (NumOfDefinedOps == 1) {
6607 unsigned SubVecNumElts =
6608 Op.getOperand(OpIdx).getValueType().getVectorNumElements();
6609 SDValue IdxVal = DAG.getIntPtrConstant(SubVecNumElts * OpIdx, dl);
6610 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef,
6611 Op.getOperand(OpIdx), IdxVal);
6614 MVT HalfVT = MVT::getVectorVT(ResVT.getVectorElementType(),
6615 ResVT.getVectorNumElements()/2);
6616 SmallVector<SDValue, 2> Ops;
6617 for (unsigned i = 0; i < NumOfOperands/2; i++)
6618 Ops.push_back(Op.getOperand(i));
6619 SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6621 for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6622 Ops.push_back(Op.getOperand(i));
6623 SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6624 return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6628 SDValue V1 = Op.getOperand(0);
6629 SDValue V2 = Op.getOperand(1);
6630 unsigned NumElems = ResVT.getVectorNumElements();
6631 assert(V1.getValueType() == V2.getValueType() &&
6632 V1.getValueType().getVectorNumElements() == NumElems/2 &&
6633 "Unexpected operands in CONCAT_VECTORS");
6635 if (ResVT.getSizeInBits() >= 16)
6636 return Op; // The operation is legal with KUNPCK
6638 bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6639 bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6640 SDValue ZeroVec = getZeroVector(ResVT, Subtarget, DAG, dl);
6641 if (IsZeroV1 && IsZeroV2)
6644 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6646 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6648 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, ZeroVec, V1, ZeroIdx);
6650 SDValue IdxVal = DAG.getIntPtrConstant(NumElems/2, dl);
6652 V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, IdxVal);
6655 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, ZeroVec, V2, IdxVal);
6657 V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6658 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, V1, V2, IdxVal);
6661 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6662 const X86Subtarget *Subtarget,
6663 SelectionDAG &DAG) {
6664 MVT VT = Op.getSimpleValueType();
6665 if (VT.getVectorElementType() == MVT::i1)
6666 return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6668 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6669 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6670 Op.getNumOperands() == 4)));
6672 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6673 // from two other 128-bit ones.
6675 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6676 return LowerAVXCONCAT_VECTORS(Op, DAG);
6679 //===----------------------------------------------------------------------===//
6680 // Vector shuffle lowering
6682 // This is an experimental code path for lowering vector shuffles on x86. It is
6683 // designed to handle arbitrary vector shuffles and blends, gracefully
6684 // degrading performance as necessary. It works hard to recognize idiomatic
6685 // shuffles and lower them to optimal instruction patterns without leaving
6686 // a framework that allows reasonably efficient handling of all vector shuffle
6688 //===----------------------------------------------------------------------===//
6690 /// \brief Tiny helper function to identify a no-op mask.
6692 /// This is a somewhat boring predicate function. It checks whether the mask
6693 /// array input, which is assumed to be a single-input shuffle mask of the kind
6694 /// used by the X86 shuffle instructions (not a fully general
6695 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6696 /// in-place shuffle are 'no-op's.
6697 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6698 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6699 if (Mask[i] != -1 && Mask[i] != i)
6704 /// \brief Helper function to classify a mask as a single-input mask.
6706 /// This isn't a generic single-input test because in the vector shuffle
6707 /// lowering we canonicalize single inputs to be the first input operand. This
6708 /// means we can more quickly test for a single input by only checking whether
6709 /// an input from the second operand exists. We also assume that the size of
6710 /// mask corresponds to the size of the input vectors which isn't true in the
6711 /// fully general case.
6712 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6714 if (M >= (int)Mask.size())
6719 /// \brief Test whether there are elements crossing 128-bit lanes in this
6722 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6723 /// and we routinely test for these.
6724 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6725 int LaneSize = 128 / VT.getScalarSizeInBits();
6726 int Size = Mask.size();
6727 for (int i = 0; i < Size; ++i)
6728 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6733 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6735 /// This checks a shuffle mask to see if it is performing the same
6736 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6737 /// that it is also not lane-crossing. It may however involve a blend from the
6738 /// same lane of a second vector.
6740 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6741 /// non-trivial to compute in the face of undef lanes. The representation is
6742 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6743 /// entries from both V1 and V2 inputs to the wider mask.
6745 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6746 SmallVectorImpl<int> &RepeatedMask) {
6747 int LaneSize = 128 / VT.getScalarSizeInBits();
6748 RepeatedMask.resize(LaneSize, -1);
6749 int Size = Mask.size();
6750 for (int i = 0; i < Size; ++i) {
6753 if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6754 // This entry crosses lanes, so there is no way to model this shuffle.
6757 // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6758 if (RepeatedMask[i % LaneSize] == -1)
6759 // This is the first non-undef entry in this slot of a 128-bit lane.
6760 RepeatedMask[i % LaneSize] =
6761 Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6762 else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6763 // Found a mismatch with the repeated mask.
6769 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6772 /// This is a fast way to test a shuffle mask against a fixed pattern:
6774 /// if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6776 /// It returns true if the mask is exactly as wide as the argument list, and
6777 /// each element of the mask is either -1 (signifying undef) or the value given
6778 /// in the argument.
6779 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6780 ArrayRef<int> ExpectedMask) {
6781 if (Mask.size() != ExpectedMask.size())
6784 int Size = Mask.size();
6786 // If the values are build vectors, we can look through them to find
6787 // equivalent inputs that make the shuffles equivalent.
6788 auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6789 auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6791 for (int i = 0; i < Size; ++i)
6792 if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6793 auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6794 auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6795 if (!MaskBV || !ExpectedBV ||
6796 MaskBV->getOperand(Mask[i] % Size) !=
6797 ExpectedBV->getOperand(ExpectedMask[i] % Size))
6804 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6806 /// This helper function produces an 8-bit shuffle immediate corresponding to
6807 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6808 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6811 /// NB: We rely heavily on "undef" masks preserving the input lane.
6812 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6813 SelectionDAG &DAG) {
6814 assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6815 assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6816 assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6817 assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6818 assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6821 Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6822 Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6823 Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6824 Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6825 return DAG.getConstant(Imm, DL, MVT::i8);
6828 /// \brief Compute whether each element of a shuffle is zeroable.
6830 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6831 /// Either it is an undef element in the shuffle mask, the element of the input
6832 /// referenced is undef, or the element of the input referenced is known to be
6833 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6834 /// as many lanes with this technique as possible to simplify the remaining
6836 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6837 SDValue V1, SDValue V2) {
6838 SmallBitVector Zeroable(Mask.size(), false);
6840 while (V1.getOpcode() == ISD::BITCAST)
6841 V1 = V1->getOperand(0);
6842 while (V2.getOpcode() == ISD::BITCAST)
6843 V2 = V2->getOperand(0);
6845 bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6846 bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6848 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6850 // Handle the easy cases.
6851 if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6856 // If this is an index into a build_vector node (which has the same number
6857 // of elements), dig out the input value and use it.
6858 SDValue V = M < Size ? V1 : V2;
6859 if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6862 SDValue Input = V.getOperand(M % Size);
6863 // The UNDEF opcode check really should be dead code here, but not quite
6864 // worth asserting on (it isn't invalid, just unexpected).
6865 if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6872 // X86 has dedicated unpack instructions that can handle specific blend
6873 // operations: UNPCKH and UNPCKL.
6874 static SDValue lowerVectorShuffleWithUNPCK(SDLoc DL, MVT VT, ArrayRef<int> Mask,
6875 SDValue V1, SDValue V2,
6876 SelectionDAG &DAG) {
6877 int NumElts = VT.getVectorNumElements();
6878 int NumEltsInLane = 128 / VT.getScalarSizeInBits();
6879 SmallVector<int, 8> Unpckl;
6880 SmallVector<int, 8> Unpckh;
6882 for (int i = 0; i < NumElts; ++i) {
6883 unsigned LaneStart = (i / NumEltsInLane) * NumEltsInLane;
6884 int LoPos = (i % NumEltsInLane) / 2 + LaneStart + NumElts * (i % 2);
6885 int HiPos = LoPos + NumEltsInLane / 2;
6886 Unpckl.push_back(LoPos);
6887 Unpckh.push_back(HiPos);
6890 if (isShuffleEquivalent(V1, V2, Mask, Unpckl))
6891 return DAG.getNode(X86ISD::UNPCKL, DL, VT, V1, V2);
6892 if (isShuffleEquivalent(V1, V2, Mask, Unpckh))
6893 return DAG.getNode(X86ISD::UNPCKH, DL, VT, V1, V2);
6895 // Commute and try again.
6896 ShuffleVectorSDNode::commuteMask(Unpckl);
6897 if (isShuffleEquivalent(V1, V2, Mask, Unpckl))
6898 return DAG.getNode(X86ISD::UNPCKL, DL, VT, V2, V1);
6900 ShuffleVectorSDNode::commuteMask(Unpckh);
6901 if (isShuffleEquivalent(V1, V2, Mask, Unpckh))
6902 return DAG.getNode(X86ISD::UNPCKH, DL, VT, V2, V1);
6907 /// \brief Try to emit a bitmask instruction for a shuffle.
6909 /// This handles cases where we can model a blend exactly as a bitmask due to
6910 /// one of the inputs being zeroable.
6911 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6912 SDValue V2, ArrayRef<int> Mask,
6913 SelectionDAG &DAG) {
6914 MVT EltVT = VT.getVectorElementType();
6915 int NumEltBits = EltVT.getSizeInBits();
6916 MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6917 SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6918 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6920 if (EltVT.isFloatingPoint()) {
6921 Zero = DAG.getBitcast(EltVT, Zero);
6922 AllOnes = DAG.getBitcast(EltVT, AllOnes);
6924 SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6925 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6927 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6930 if (Mask[i] % Size != i)
6931 return SDValue(); // Not a blend.
6933 V = Mask[i] < Size ? V1 : V2;
6934 else if (V != (Mask[i] < Size ? V1 : V2))
6935 return SDValue(); // Can only let one input through the mask.
6937 VMaskOps[i] = AllOnes;
6940 return SDValue(); // No non-zeroable elements!
6942 SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6943 V = DAG.getNode(VT.isFloatingPoint()
6944 ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6949 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6951 /// This is used as a fallback approach when first class blend instructions are
6952 /// unavailable. Currently it is only suitable for integer vectors, but could
6953 /// be generalized for floating point vectors if desirable.
6954 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6955 SDValue V2, ArrayRef<int> Mask,
6956 SelectionDAG &DAG) {
6957 assert(VT.isInteger() && "Only supports integer vector types!");
6958 MVT EltVT = VT.getVectorElementType();
6959 int NumEltBits = EltVT.getSizeInBits();
6960 SDValue Zero = DAG.getConstant(0, DL, EltVT);
6961 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6963 SmallVector<SDValue, 16> MaskOps;
6964 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6965 if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6966 return SDValue(); // Shuffled input!
6967 MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6970 SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6971 V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6972 // We have to cast V2 around.
6973 MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6974 V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6975 DAG.getBitcast(MaskVT, V1Mask),
6976 DAG.getBitcast(MaskVT, V2)));
6977 return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6980 /// \brief Try to emit a blend instruction for a shuffle.
6982 /// This doesn't do any checks for the availability of instructions for blending
6983 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6984 /// be matched in the backend with the type given. What it does check for is
6985 /// that the shuffle mask is a blend, or convertible into a blend with zero.
6986 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6987 SDValue V2, ArrayRef<int> Original,
6988 const X86Subtarget *Subtarget,
6989 SelectionDAG &DAG) {
6990 bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6991 bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6992 SmallVector<int, 8> Mask(Original.begin(), Original.end());
6993 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6994 bool ForceV1Zero = false, ForceV2Zero = false;
6996 // Attempt to generate the binary blend mask. If an input is zero then
6997 // we can use any lane.
6998 // TODO: generalize the zero matching to any scalar like isShuffleEquivalent.
6999 unsigned BlendMask = 0;
7000 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7006 if (M == i + Size) {
7007 BlendMask |= 1u << i;
7018 BlendMask |= 1u << i;
7023 return SDValue(); // Shuffled input!
7026 // Create a REAL zero vector - ISD::isBuildVectorAllZeros allows UNDEFs.
7028 V1 = getZeroVector(VT, Subtarget, DAG, DL);
7030 V2 = getZeroVector(VT, Subtarget, DAG, DL);
7032 auto ScaleBlendMask = [](unsigned BlendMask, int Size, int Scale) {
7033 unsigned ScaledMask = 0;
7034 for (int i = 0; i != Size; ++i)
7035 if (BlendMask & (1u << i))
7036 for (int j = 0; j != Scale; ++j)
7037 ScaledMask |= 1u << (i * Scale + j);
7041 switch (VT.SimpleTy) {
7046 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
7047 DAG.getConstant(BlendMask, DL, MVT::i8));
7051 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
7055 // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
7056 // that instruction.
7057 if (Subtarget->hasAVX2()) {
7058 // Scale the blend by the number of 32-bit dwords per element.
7059 int Scale = VT.getScalarSizeInBits() / 32;
7060 BlendMask = ScaleBlendMask(BlendMask, Mask.size(), Scale);
7061 MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
7062 V1 = DAG.getBitcast(BlendVT, V1);
7063 V2 = DAG.getBitcast(BlendVT, V2);
7064 return DAG.getBitcast(
7065 VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
7066 DAG.getConstant(BlendMask, DL, MVT::i8)));
7070 // For integer shuffles we need to expand the mask and cast the inputs to
7071 // v8i16s prior to blending.
7072 int Scale = 8 / VT.getVectorNumElements();
7073 BlendMask = ScaleBlendMask(BlendMask, Mask.size(), Scale);
7074 V1 = DAG.getBitcast(MVT::v8i16, V1);
7075 V2 = DAG.getBitcast(MVT::v8i16, V2);
7076 return DAG.getBitcast(VT,
7077 DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
7078 DAG.getConstant(BlendMask, DL, MVT::i8)));
7082 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
7083 SmallVector<int, 8> RepeatedMask;
7084 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
7085 // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
7086 assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
7088 for (int i = 0; i < 8; ++i)
7089 if (RepeatedMask[i] >= 16)
7090 BlendMask |= 1u << i;
7091 return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
7092 DAG.getConstant(BlendMask, DL, MVT::i8));
7098 assert((VT.is128BitVector() || Subtarget->hasAVX2()) &&
7099 "256-bit byte-blends require AVX2 support!");
7101 // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
7102 if (SDValue Masked = lowerVectorShuffleAsBitMask(DL, VT, V1, V2, Mask, DAG))
7105 // Scale the blend by the number of bytes per element.
7106 int Scale = VT.getScalarSizeInBits() / 8;
7108 // This form of blend is always done on bytes. Compute the byte vector
7110 MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
7112 // Compute the VSELECT mask. Note that VSELECT is really confusing in the
7113 // mix of LLVM's code generator and the x86 backend. We tell the code
7114 // generator that boolean values in the elements of an x86 vector register
7115 // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
7116 // mapping a select to operand #1, and 'false' mapping to operand #2. The
7117 // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
7118 // of the element (the remaining are ignored) and 0 in that high bit would
7119 // mean operand #1 while 1 in the high bit would mean operand #2. So while
7120 // the LLVM model for boolean values in vector elements gets the relevant
7121 // bit set, it is set backwards and over constrained relative to x86's
7123 SmallVector<SDValue, 32> VSELECTMask;
7124 for (int i = 0, Size = Mask.size(); i < Size; ++i)
7125 for (int j = 0; j < Scale; ++j)
7126 VSELECTMask.push_back(
7127 Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
7128 : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
7131 V1 = DAG.getBitcast(BlendVT, V1);
7132 V2 = DAG.getBitcast(BlendVT, V2);
7133 return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
7134 DAG.getNode(ISD::BUILD_VECTOR, DL,
7135 BlendVT, VSELECTMask),
7140 llvm_unreachable("Not a supported integer vector type!");
7144 /// \brief Try to lower as a blend of elements from two inputs followed by
7145 /// a single-input permutation.
7147 /// This matches the pattern where we can blend elements from two inputs and
7148 /// then reduce the shuffle to a single-input permutation.
7149 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
7152 SelectionDAG &DAG) {
7153 // We build up the blend mask while checking whether a blend is a viable way
7154 // to reduce the shuffle.
7155 SmallVector<int, 32> BlendMask(Mask.size(), -1);
7156 SmallVector<int, 32> PermuteMask(Mask.size(), -1);
7158 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7162 assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
7164 if (BlendMask[Mask[i] % Size] == -1)
7165 BlendMask[Mask[i] % Size] = Mask[i];
7166 else if (BlendMask[Mask[i] % Size] != Mask[i])
7167 return SDValue(); // Can't blend in the needed input!
7169 PermuteMask[i] = Mask[i] % Size;
7172 SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7173 return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
7176 /// \brief Generic routine to decompose a shuffle and blend into indepndent
7177 /// blends and permutes.
7179 /// This matches the extremely common pattern for handling combined
7180 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
7181 /// operations. It will try to pick the best arrangement of shuffles and
7183 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
7187 SelectionDAG &DAG) {
7188 // Shuffle the input elements into the desired positions in V1 and V2 and
7189 // blend them together.
7190 SmallVector<int, 32> V1Mask(Mask.size(), -1);
7191 SmallVector<int, 32> V2Mask(Mask.size(), -1);
7192 SmallVector<int, 32> BlendMask(Mask.size(), -1);
7193 for (int i = 0, Size = Mask.size(); i < Size; ++i)
7194 if (Mask[i] >= 0 && Mask[i] < Size) {
7195 V1Mask[i] = Mask[i];
7197 } else if (Mask[i] >= Size) {
7198 V2Mask[i] = Mask[i] - Size;
7199 BlendMask[i] = i + Size;
7202 // Try to lower with the simpler initial blend strategy unless one of the
7203 // input shuffles would be a no-op. We prefer to shuffle inputs as the
7204 // shuffle may be able to fold with a load or other benefit. However, when
7205 // we'll have to do 2x as many shuffles in order to achieve this, blending
7206 // first is a better strategy.
7207 if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
7208 if (SDValue BlendPerm =
7209 lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
7212 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7213 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7214 return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
7217 /// \brief Try to lower a vector shuffle as a byte rotation.
7219 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
7220 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
7221 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
7222 /// try to generically lower a vector shuffle through such an pattern. It
7223 /// does not check for the profitability of lowering either as PALIGNR or
7224 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
7225 /// This matches shuffle vectors that look like:
7227 /// v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
7229 /// Essentially it concatenates V1 and V2, shifts right by some number of
7230 /// elements, and takes the low elements as the result. Note that while this is
7231 /// specified as a *right shift* because x86 is little-endian, it is a *left
7232 /// rotate* of the vector lanes.
7233 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
7236 const X86Subtarget *Subtarget,
7237 SelectionDAG &DAG) {
7238 assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
7240 int NumElts = Mask.size();
7241 int NumLanes = VT.getSizeInBits() / 128;
7242 int NumLaneElts = NumElts / NumLanes;
7244 // We need to detect various ways of spelling a rotation:
7245 // [11, 12, 13, 14, 15, 0, 1, 2]
7246 // [-1, 12, 13, 14, -1, -1, 1, -1]
7247 // [-1, -1, -1, -1, -1, -1, 1, 2]
7248 // [ 3, 4, 5, 6, 7, 8, 9, 10]
7249 // [-1, 4, 5, 6, -1, -1, 9, -1]
7250 // [-1, 4, 5, 6, -1, -1, -1, -1]
7253 for (int l = 0; l < NumElts; l += NumLaneElts) {
7254 for (int i = 0; i < NumLaneElts; ++i) {
7255 if (Mask[l + i] == -1)
7257 assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
7259 // Get the mod-Size index and lane correct it.
7260 int LaneIdx = (Mask[l + i] % NumElts) - l;
7261 // Make sure it was in this lane.
7262 if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
7265 // Determine where a rotated vector would have started.
7266 int StartIdx = i - LaneIdx;
7268 // The identity rotation isn't interesting, stop.
7271 // If we found the tail of a vector the rotation must be the missing
7272 // front. If we found the head of a vector, it must be how much of the
7274 int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
7277 Rotation = CandidateRotation;
7278 else if (Rotation != CandidateRotation)
7279 // The rotations don't match, so we can't match this mask.
7282 // Compute which value this mask is pointing at.
7283 SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
7285 // Compute which of the two target values this index should be assigned
7286 // to. This reflects whether the high elements are remaining or the low
7287 // elements are remaining.
7288 SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
7290 // Either set up this value if we've not encountered it before, or check
7291 // that it remains consistent.
7294 else if (TargetV != MaskV)
7295 // This may be a rotation, but it pulls from the inputs in some
7296 // unsupported interleaving.
7301 // Check that we successfully analyzed the mask, and normalize the results.
7302 assert(Rotation != 0 && "Failed to locate a viable rotation!");
7303 assert((Lo || Hi) && "Failed to find a rotated input vector!");
7309 // The actual rotate instruction rotates bytes, so we need to scale the
7310 // rotation based on how many bytes are in the vector lane.
7311 int Scale = 16 / NumLaneElts;
7313 // SSSE3 targets can use the palignr instruction.
7314 if (Subtarget->hasSSSE3()) {
7315 // Cast the inputs to i8 vector of correct length to match PALIGNR.
7316 MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
7317 Lo = DAG.getBitcast(AlignVT, Lo);
7318 Hi = DAG.getBitcast(AlignVT, Hi);
7320 return DAG.getBitcast(
7321 VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Lo, Hi,
7322 DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
7325 assert(VT.is128BitVector() &&
7326 "Rotate-based lowering only supports 128-bit lowering!");
7327 assert(Mask.size() <= 16 &&
7328 "Can shuffle at most 16 bytes in a 128-bit vector!");
7330 // Default SSE2 implementation
7331 int LoByteShift = 16 - Rotation * Scale;
7332 int HiByteShift = Rotation * Scale;
7334 // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
7335 Lo = DAG.getBitcast(MVT::v2i64, Lo);
7336 Hi = DAG.getBitcast(MVT::v2i64, Hi);
7338 SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
7339 DAG.getConstant(LoByteShift, DL, MVT::i8));
7340 SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
7341 DAG.getConstant(HiByteShift, DL, MVT::i8));
7342 return DAG.getBitcast(VT,
7343 DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
7346 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
7348 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
7349 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
7350 /// matches elements from one of the input vectors shuffled to the left or
7351 /// right with zeroable elements 'shifted in'. It handles both the strictly
7352 /// bit-wise element shifts and the byte shift across an entire 128-bit double
7355 /// PSHL : (little-endian) left bit shift.
7356 /// [ zz, 0, zz, 2 ]
7357 /// [ -1, 4, zz, -1 ]
7358 /// PSRL : (little-endian) right bit shift.
7360 /// [ -1, -1, 7, zz]
7361 /// PSLLDQ : (little-endian) left byte shift
7362 /// [ zz, 0, 1, 2, 3, 4, 5, 6]
7363 /// [ zz, zz, -1, -1, 2, 3, 4, -1]
7364 /// [ zz, zz, zz, zz, zz, zz, -1, 1]
7365 /// PSRLDQ : (little-endian) right byte shift
7366 /// [ 5, 6, 7, zz, zz, zz, zz, zz]
7367 /// [ -1, 5, 6, 7, zz, zz, zz, zz]
7368 /// [ 1, 2, -1, -1, -1, -1, zz, zz]
7369 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
7370 SDValue V2, ArrayRef<int> Mask,
7371 SelectionDAG &DAG) {
7372 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7374 int Size = Mask.size();
7375 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7377 auto CheckZeros = [&](int Shift, int Scale, bool Left) {
7378 for (int i = 0; i < Size; i += Scale)
7379 for (int j = 0; j < Shift; ++j)
7380 if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
7386 auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
7387 for (int i = 0; i != Size; i += Scale) {
7388 unsigned Pos = Left ? i + Shift : i;
7389 unsigned Low = Left ? i : i + Shift;
7390 unsigned Len = Scale - Shift;
7391 if (!isSequentialOrUndefInRange(Mask, Pos, Len,
7392 Low + (V == V1 ? 0 : Size)))
7396 int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
7397 bool ByteShift = ShiftEltBits > 64;
7398 unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
7399 : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
7400 int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
7402 // Normalize the scale for byte shifts to still produce an i64 element
7404 Scale = ByteShift ? Scale / 2 : Scale;
7406 // We need to round trip through the appropriate type for the shift.
7407 MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
7408 MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
7409 assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
7410 "Illegal integer vector type");
7411 V = DAG.getBitcast(ShiftVT, V);
7413 V = DAG.getNode(OpCode, DL, ShiftVT, V,
7414 DAG.getConstant(ShiftAmt, DL, MVT::i8));
7415 return DAG.getBitcast(VT, V);
7418 // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
7419 // keep doubling the size of the integer elements up to that. We can
7420 // then shift the elements of the integer vector by whole multiples of
7421 // their width within the elements of the larger integer vector. Test each
7422 // multiple to see if we can find a match with the moved element indices
7423 // and that the shifted in elements are all zeroable.
7424 for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
7425 for (int Shift = 1; Shift != Scale; ++Shift)
7426 for (bool Left : {true, false})
7427 if (CheckZeros(Shift, Scale, Left))
7428 for (SDValue V : {V1, V2})
7429 if (SDValue Match = MatchShift(Shift, Scale, Left, V))
7436 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
7437 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
7438 SDValue V2, ArrayRef<int> Mask,
7439 SelectionDAG &DAG) {
7440 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7441 assert(!Zeroable.all() && "Fully zeroable shuffle mask");
7443 int Size = Mask.size();
7444 int HalfSize = Size / 2;
7445 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7447 // Upper half must be undefined.
7448 if (!isUndefInRange(Mask, HalfSize, HalfSize))
7451 // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7452 // Remainder of lower half result is zero and upper half is all undef.
7453 auto LowerAsEXTRQ = [&]() {
7454 // Determine the extraction length from the part of the
7455 // lower half that isn't zeroable.
7457 for (; Len > 0; --Len)
7458 if (!Zeroable[Len - 1])
7460 assert(Len > 0 && "Zeroable shuffle mask");
7462 // Attempt to match first Len sequential elements from the lower half.
7465 for (int i = 0; i != Len; ++i) {
7469 SDValue &V = (M < Size ? V1 : V2);
7472 // The extracted elements must start at a valid index and all mask
7473 // elements must be in the lower half.
7474 if (i > M || M >= HalfSize)
7477 if (Idx < 0 || (Src == V && Idx == (M - i))) {
7488 assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7489 int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7490 int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7491 return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7492 DAG.getConstant(BitLen, DL, MVT::i8),
7493 DAG.getConstant(BitIdx, DL, MVT::i8));
7496 if (SDValue ExtrQ = LowerAsEXTRQ())
7499 // INSERTQ: Extract lowest Len elements from lower half of second source and
7500 // insert over first source, starting at Idx.
7501 // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7502 auto LowerAsInsertQ = [&]() {
7503 for (int Idx = 0; Idx != HalfSize; ++Idx) {
7506 // Attempt to match first source from mask before insertion point.
7507 if (isUndefInRange(Mask, 0, Idx)) {
7509 } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7511 } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7517 // Extend the extraction length looking to match both the insertion of
7518 // the second source and the remaining elements of the first.
7519 for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7524 if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7526 } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7532 // Match the remaining elements of the lower half.
7533 if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7535 } else if ((!Base || (Base == V1)) &&
7536 isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7538 } else if ((!Base || (Base == V2)) &&
7539 isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7546 // We may not have a base (first source) - this can safely be undefined.
7548 Base = DAG.getUNDEF(VT);
7550 int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7551 int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7552 return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7553 DAG.getConstant(BitLen, DL, MVT::i8),
7554 DAG.getConstant(BitIdx, DL, MVT::i8));
7561 if (SDValue InsertQ = LowerAsInsertQ())
7567 /// \brief Lower a vector shuffle as a zero or any extension.
7569 /// Given a specific number of elements, element bit width, and extension
7570 /// stride, produce either a zero or any extension based on the available
7571 /// features of the subtarget. The extended elements are consecutive and
7572 /// begin and can start from an offseted element index in the input; to
7573 /// avoid excess shuffling the offset must either being in the bottom lane
7574 /// or at the start of a higher lane. All extended elements must be from
7576 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7577 SDLoc DL, MVT VT, int Scale, int Offset, bool AnyExt, SDValue InputV,
7578 ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7579 assert(Scale > 1 && "Need a scale to extend.");
7580 int EltBits = VT.getScalarSizeInBits();
7581 int NumElements = VT.getVectorNumElements();
7582 int NumEltsPerLane = 128 / EltBits;
7583 int OffsetLane = Offset / NumEltsPerLane;
7584 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7585 "Only 8, 16, and 32 bit elements can be extended.");
7586 assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7587 assert(0 <= Offset && "Extension offset must be positive.");
7588 assert((Offset < NumEltsPerLane || Offset % NumEltsPerLane == 0) &&
7589 "Extension offset must be in the first lane or start an upper lane.");
7591 // Check that an index is in same lane as the base offset.
7592 auto SafeOffset = [&](int Idx) {
7593 return OffsetLane == (Idx / NumEltsPerLane);
7596 // Shift along an input so that the offset base moves to the first element.
7597 auto ShuffleOffset = [&](SDValue V) {
7601 SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7602 for (int i = 0; i * Scale < NumElements; ++i) {
7603 int SrcIdx = i + Offset;
7604 ShMask[i] = SafeOffset(SrcIdx) ? SrcIdx : -1;
7606 return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), ShMask);
7609 // Found a valid zext mask! Try various lowering strategies based on the
7610 // input type and available ISA extensions.
7611 if (Subtarget->hasSSE41()) {
7612 // Not worth offseting 128-bit vectors if scale == 2, a pattern using
7613 // PUNPCK will catch this in a later shuffle match.
7614 if (Offset && Scale == 2 && VT.is128BitVector())
7616 MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7617 NumElements / Scale);
7618 InputV = DAG.getNode(X86ISD::VZEXT, DL, ExtVT, ShuffleOffset(InputV));
7619 return DAG.getBitcast(VT, InputV);
7622 assert(VT.is128BitVector() && "Only 128-bit vectors can be extended.");
7624 // For any extends we can cheat for larger element sizes and use shuffle
7625 // instructions that can fold with a load and/or copy.
7626 if (AnyExt && EltBits == 32) {
7627 int PSHUFDMask[4] = {Offset, -1, SafeOffset(Offset + 1) ? Offset + 1 : -1,
7629 return DAG.getBitcast(
7630 VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7631 DAG.getBitcast(MVT::v4i32, InputV),
7632 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7634 if (AnyExt && EltBits == 16 && Scale > 2) {
7635 int PSHUFDMask[4] = {Offset / 2, -1,
7636 SafeOffset(Offset + 1) ? (Offset + 1) / 2 : -1, -1};
7637 InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7638 DAG.getBitcast(MVT::v4i32, InputV),
7639 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7640 int PSHUFWMask[4] = {1, -1, -1, -1};
7641 unsigned OddEvenOp = (Offset & 1 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW);
7642 return DAG.getBitcast(
7643 VT, DAG.getNode(OddEvenOp, DL, MVT::v8i16,
7644 DAG.getBitcast(MVT::v8i16, InputV),
7645 getV4X86ShuffleImm8ForMask(PSHUFWMask, DL, DAG)));
7648 // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7650 if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7651 assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7652 assert(VT.is128BitVector() && "Unexpected vector width!");
7654 int LoIdx = Offset * EltBits;
7655 SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7656 DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7657 DAG.getConstant(EltBits, DL, MVT::i8),
7658 DAG.getConstant(LoIdx, DL, MVT::i8)));
7660 if (isUndefInRange(Mask, NumElements / 2, NumElements / 2) ||
7661 !SafeOffset(Offset + 1))
7662 return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7664 int HiIdx = (Offset + 1) * EltBits;
7665 SDValue Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7666 DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7667 DAG.getConstant(EltBits, DL, MVT::i8),
7668 DAG.getConstant(HiIdx, DL, MVT::i8)));
7669 return DAG.getNode(ISD::BITCAST, DL, VT,
7670 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7673 // If this would require more than 2 unpack instructions to expand, use
7674 // pshufb when available. We can only use more than 2 unpack instructions
7675 // when zero extending i8 elements which also makes it easier to use pshufb.
7676 if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7677 assert(NumElements == 16 && "Unexpected byte vector width!");
7678 SDValue PSHUFBMask[16];
7679 for (int i = 0; i < 16; ++i) {
7680 int Idx = Offset + (i / Scale);
7681 PSHUFBMask[i] = DAG.getConstant(
7682 (i % Scale == 0 && SafeOffset(Idx)) ? Idx : 0x80, DL, MVT::i8);
7684 InputV = DAG.getBitcast(MVT::v16i8, InputV);
7685 return DAG.getBitcast(VT,
7686 DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7687 DAG.getNode(ISD::BUILD_VECTOR, DL,
7688 MVT::v16i8, PSHUFBMask)));
7691 // If we are extending from an offset, ensure we start on a boundary that
7692 // we can unpack from.
7693 int AlignToUnpack = Offset % (NumElements / Scale);
7694 if (AlignToUnpack) {
7695 SmallVector<int, 8> ShMask((unsigned)NumElements, -1);
7696 for (int i = AlignToUnpack; i < NumElements; ++i)
7697 ShMask[i - AlignToUnpack] = i;
7698 InputV = DAG.getVectorShuffle(VT, DL, InputV, DAG.getUNDEF(VT), ShMask);
7699 Offset -= AlignToUnpack;
7702 // Otherwise emit a sequence of unpacks.
7704 unsigned UnpackLoHi = X86ISD::UNPCKL;
7705 if (Offset >= (NumElements / 2)) {
7706 UnpackLoHi = X86ISD::UNPCKH;
7707 Offset -= (NumElements / 2);
7710 MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7711 SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7712 : getZeroVector(InputVT, Subtarget, DAG, DL);
7713 InputV = DAG.getBitcast(InputVT, InputV);
7714 InputV = DAG.getNode(UnpackLoHi, DL, InputVT, InputV, Ext);
7718 } while (Scale > 1);
7719 return DAG.getBitcast(VT, InputV);
7722 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7724 /// This routine will try to do everything in its power to cleverly lower
7725 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7726 /// check for the profitability of this lowering, it tries to aggressively
7727 /// match this pattern. It will use all of the micro-architectural details it
7728 /// can to emit an efficient lowering. It handles both blends with all-zero
7729 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7730 /// masking out later).
7732 /// The reason we have dedicated lowering for zext-style shuffles is that they
7733 /// are both incredibly common and often quite performance sensitive.
7734 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7735 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7736 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7737 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7739 int Bits = VT.getSizeInBits();
7740 int NumLanes = Bits / 128;
7741 int NumElements = VT.getVectorNumElements();
7742 int NumEltsPerLane = NumElements / NumLanes;
7743 assert(VT.getScalarSizeInBits() <= 32 &&
7744 "Exceeds 32-bit integer zero extension limit");
7745 assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7747 // Define a helper function to check a particular ext-scale and lower to it if
7749 auto Lower = [&](int Scale) -> SDValue {
7754 for (int i = 0; i < NumElements; ++i) {
7757 continue; // Valid anywhere but doesn't tell us anything.
7758 if (i % Scale != 0) {
7759 // Each of the extended elements need to be zeroable.
7763 // We no longer are in the anyext case.
7768 // Each of the base elements needs to be consecutive indices into the
7769 // same input vector.
7770 SDValue V = M < NumElements ? V1 : V2;
7771 M = M % NumElements;
7774 Offset = M - (i / Scale);
7775 } else if (InputV != V)
7776 return SDValue(); // Flip-flopping inputs.
7778 // Offset must start in the lowest 128-bit lane or at the start of an
7780 // FIXME: Is it ever worth allowing a negative base offset?
7781 if (!((0 <= Offset && Offset < NumEltsPerLane) ||
7782 (Offset % NumEltsPerLane) == 0))
7785 // If we are offsetting, all referenced entries must come from the same
7787 if (Offset && (Offset / NumEltsPerLane) != (M / NumEltsPerLane))
7790 if ((M % NumElements) != (Offset + (i / Scale)))
7791 return SDValue(); // Non-consecutive strided elements.
7795 // If we fail to find an input, we have a zero-shuffle which should always
7796 // have already been handled.
7797 // FIXME: Maybe handle this here in case during blending we end up with one?
7801 // If we are offsetting, don't extend if we only match a single input, we
7802 // can always do better by using a basic PSHUF or PUNPCK.
7803 if (Offset != 0 && Matches < 2)
7806 return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7807 DL, VT, Scale, Offset, AnyExt, InputV, Mask, Subtarget, DAG);
7810 // The widest scale possible for extending is to a 64-bit integer.
7811 assert(Bits % 64 == 0 &&
7812 "The number of bits in a vector must be divisible by 64 on x86!");
7813 int NumExtElements = Bits / 64;
7815 // Each iteration, try extending the elements half as much, but into twice as
7817 for (; NumExtElements < NumElements; NumExtElements *= 2) {
7818 assert(NumElements % NumExtElements == 0 &&
7819 "The input vector size must be divisible by the extended size.");
7820 if (SDValue V = Lower(NumElements / NumExtElements))
7824 // General extends failed, but 128-bit vectors may be able to use MOVQ.
7828 // Returns one of the source operands if the shuffle can be reduced to a
7829 // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7830 auto CanZExtLowHalf = [&]() {
7831 for (int i = NumElements / 2; i != NumElements; ++i)
7834 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7836 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7841 if (SDValue V = CanZExtLowHalf()) {
7842 V = DAG.getBitcast(MVT::v2i64, V);
7843 V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7844 return DAG.getBitcast(VT, V);
7847 // No viable ext lowering found.
7851 /// \brief Try to get a scalar value for a specific element of a vector.
7853 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7854 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7855 SelectionDAG &DAG) {
7856 MVT VT = V.getSimpleValueType();
7857 MVT EltVT = VT.getVectorElementType();
7858 while (V.getOpcode() == ISD::BITCAST)
7859 V = V.getOperand(0);
7860 // If the bitcasts shift the element size, we can't extract an equivalent
7862 MVT NewVT = V.getSimpleValueType();
7863 if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7866 if (V.getOpcode() == ISD::BUILD_VECTOR ||
7867 (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7868 // Ensure the scalar operand is the same size as the destination.
7869 // FIXME: Add support for scalar truncation where possible.
7870 SDValue S = V.getOperand(Idx);
7871 if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7872 return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7878 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7880 /// This is particularly important because the set of instructions varies
7881 /// significantly based on whether the operand is a load or not.
7882 static bool isShuffleFoldableLoad(SDValue V) {
7883 while (V.getOpcode() == ISD::BITCAST)
7884 V = V.getOperand(0);
7886 return ISD::isNON_EXTLoad(V.getNode());
7889 /// \brief Try to lower insertion of a single element into a zero vector.
7891 /// This is a common pattern that we have especially efficient patterns to lower
7892 /// across all subtarget feature sets.
7893 static SDValue lowerVectorShuffleAsElementInsertion(
7894 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7895 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7896 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7898 MVT EltVT = VT.getVectorElementType();
7900 int V2Index = std::find_if(Mask.begin(), Mask.end(),
7901 [&Mask](int M) { return M >= (int)Mask.size(); }) -
7903 bool IsV1Zeroable = true;
7904 for (int i = 0, Size = Mask.size(); i < Size; ++i)
7905 if (i != V2Index && !Zeroable[i]) {
7906 IsV1Zeroable = false;
7910 // Check for a single input from a SCALAR_TO_VECTOR node.
7911 // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7912 // all the smarts here sunk into that routine. However, the current
7913 // lowering of BUILD_VECTOR makes that nearly impossible until the old
7914 // vector shuffle lowering is dead.
7915 SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
7917 if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
7918 // We need to zext the scalar if it is smaller than an i32.
7919 V2S = DAG.getBitcast(EltVT, V2S);
7920 if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7921 // Using zext to expand a narrow element won't work for non-zero
7926 // Zero-extend directly to i32.
7928 V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7930 V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7931 } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7932 EltVT == MVT::i16) {
7933 // Either not inserting from the low element of the input or the input
7934 // element size is too small to use VZEXT_MOVL to clear the high bits.
7938 if (!IsV1Zeroable) {
7939 // If V1 can't be treated as a zero vector we have fewer options to lower
7940 // this. We can't support integer vectors or non-zero targets cheaply, and
7941 // the V1 elements can't be permuted in any way.
7942 assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7943 if (!VT.isFloatingPoint() || V2Index != 0)
7945 SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7946 V1Mask[V2Index] = -1;
7947 if (!isNoopShuffleMask(V1Mask))
7949 // This is essentially a special case blend operation, but if we have
7950 // general purpose blend operations, they are always faster. Bail and let
7951 // the rest of the lowering handle these as blends.
7952 if (Subtarget->hasSSE41())
7955 // Otherwise, use MOVSD or MOVSS.
7956 assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7957 "Only two types of floating point element types to handle!");
7958 return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7962 // This lowering only works for the low element with floating point vectors.
7963 if (VT.isFloatingPoint() && V2Index != 0)
7966 V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7968 V2 = DAG.getBitcast(VT, V2);
7971 // If we have 4 or fewer lanes we can cheaply shuffle the element into
7972 // the desired position. Otherwise it is more efficient to do a vector
7973 // shift left. We know that we can do a vector shift left because all
7974 // the inputs are zero.
7975 if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7976 SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7977 V2Shuffle[V2Index] = 0;
7978 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7980 V2 = DAG.getBitcast(MVT::v2i64, V2);
7982 X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7983 DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
7984 DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
7985 DAG.getDataLayout(), VT)));
7986 V2 = DAG.getBitcast(VT, V2);
7992 /// \brief Try to lower broadcast of a single - truncated - integer element,
7993 /// coming from a scalar_to_vector/build_vector node \p V0 with larger elements.
7995 /// This assumes we have AVX2.
7996 static SDValue lowerVectorShuffleAsTruncBroadcast(SDLoc DL, MVT VT, SDValue V0,
7998 const X86Subtarget *Subtarget,
7999 SelectionDAG &DAG) {
8000 assert(Subtarget->hasAVX2() &&
8001 "We can only lower integer broadcasts with AVX2!");
8003 EVT EltVT = VT.getVectorElementType();
8004 EVT V0VT = V0.getValueType();
8006 assert(VT.isInteger() && "Unexpected non-integer trunc broadcast!");
8007 assert(V0VT.isVector() && "Unexpected non-vector vector-sized value!");
8009 EVT V0EltVT = V0VT.getVectorElementType();
8010 if (!V0EltVT.isInteger())
8013 const unsigned EltSize = EltVT.getSizeInBits();
8014 const unsigned V0EltSize = V0EltVT.getSizeInBits();
8016 // This is only a truncation if the original element type is larger.
8017 if (V0EltSize <= EltSize)
8020 assert(((V0EltSize % EltSize) == 0) &&
8021 "Scalar type sizes must all be powers of 2 on x86!");
8023 const unsigned V0Opc = V0.getOpcode();
8024 const unsigned Scale = V0EltSize / EltSize;
8025 const unsigned V0BroadcastIdx = BroadcastIdx / Scale;
8027 if ((V0Opc != ISD::SCALAR_TO_VECTOR || V0BroadcastIdx != 0) &&
8028 V0Opc != ISD::BUILD_VECTOR)
8031 SDValue Scalar = V0.getOperand(V0BroadcastIdx);
8033 // If we're extracting non-least-significant bits, shift so we can truncate.
8034 // Hopefully, we can fold away the trunc/srl/load into the broadcast.
8035 // Even if we can't (and !isShuffleFoldableLoad(Scalar)), prefer
8036 // vpbroadcast+vmovd+shr to vpshufb(m)+vmovd.
8037 if (const int OffsetIdx = BroadcastIdx % Scale)
8038 Scalar = DAG.getNode(ISD::SRL, DL, Scalar.getValueType(), Scalar,
8039 DAG.getConstant(OffsetIdx * EltSize, DL, Scalar.getValueType()));
8041 return DAG.getNode(X86ISD::VBROADCAST, DL, VT,
8042 DAG.getNode(ISD::TRUNCATE, DL, EltVT, Scalar));
8045 /// \brief Try to lower broadcast of a single element.
8047 /// For convenience, this code also bundles all of the subtarget feature set
8048 /// filtering. While a little annoying to re-dispatch on type here, there isn't
8049 /// a convenient way to factor it out.
8050 /// FIXME: This is very similar to LowerVectorBroadcast - can we merge them?
8051 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
8053 const X86Subtarget *Subtarget,
8054 SelectionDAG &DAG) {
8055 if (!Subtarget->hasAVX())
8057 if (VT.isInteger() && !Subtarget->hasAVX2())
8060 // Check that the mask is a broadcast.
8061 int BroadcastIdx = -1;
8063 if (M >= 0 && BroadcastIdx == -1)
8065 else if (M >= 0 && M != BroadcastIdx)
8068 assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
8069 "a sorted mask where the broadcast "
8072 // Go up the chain of (vector) values to find a scalar load that we can
8073 // combine with the broadcast.
8075 switch (V.getOpcode()) {
8076 case ISD::CONCAT_VECTORS: {
8077 int OperandSize = Mask.size() / V.getNumOperands();
8078 V = V.getOperand(BroadcastIdx / OperandSize);
8079 BroadcastIdx %= OperandSize;
8083 case ISD::INSERT_SUBVECTOR: {
8084 SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
8085 auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
8089 int BeginIdx = (int)ConstantIdx->getZExtValue();
8091 BeginIdx + (int)VInner.getSimpleValueType().getVectorNumElements();
8092 if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
8093 BroadcastIdx -= BeginIdx;
8104 // Check if this is a broadcast of a scalar. We special case lowering
8105 // for scalars so that we can more effectively fold with loads.
8106 // First, look through bitcast: if the original value has a larger element
8107 // type than the shuffle, the broadcast element is in essence truncated.
8108 // Make that explicit to ease folding.
8109 if (V.getOpcode() == ISD::BITCAST && VT.isInteger())
8110 if (SDValue TruncBroadcast = lowerVectorShuffleAsTruncBroadcast(
8111 DL, VT, V.getOperand(0), BroadcastIdx, Subtarget, DAG))
8112 return TruncBroadcast;
8114 // Also check the simpler case, where we can directly reuse the scalar.
8115 if (V.getOpcode() == ISD::BUILD_VECTOR ||
8116 (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
8117 V = V.getOperand(BroadcastIdx);
8119 // If the scalar isn't a load, we can't broadcast from it in AVX1.
8120 // Only AVX2 has register broadcasts.
8121 if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
8123 } else if (MayFoldLoad(V) && !cast<LoadSDNode>(V)->isVolatile()) {
8124 // If we are broadcasting a load that is only used by the shuffle
8125 // then we can reduce the vector load to the broadcasted scalar load.
8126 LoadSDNode *Ld = cast<LoadSDNode>(V);
8127 SDValue BaseAddr = Ld->getOperand(1);
8128 EVT AddrVT = BaseAddr.getValueType();
8129 EVT SVT = VT.getScalarType();
8130 unsigned Offset = BroadcastIdx * SVT.getStoreSize();
8131 SDValue NewAddr = DAG.getNode(
8132 ISD::ADD, DL, AddrVT, BaseAddr,
8133 DAG.getConstant(Offset, DL, AddrVT));
8134 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
8135 DAG.getMachineFunction().getMachineMemOperand(
8136 Ld->getMemOperand(), Offset, SVT.getStoreSize()));
8137 } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
8138 // We can't broadcast from a vector register without AVX2, and we can only
8139 // broadcast from the zero-element of a vector register.
8143 return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
8146 // Check for whether we can use INSERTPS to perform the shuffle. We only use
8147 // INSERTPS when the V1 elements are already in the correct locations
8148 // because otherwise we can just always use two SHUFPS instructions which
8149 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
8150 // perform INSERTPS if a single V1 element is out of place and all V2
8151 // elements are zeroable.
8152 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
8154 SelectionDAG &DAG) {
8155 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8156 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8157 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8158 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8160 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8163 int V1DstIndex = -1;
8164 int V2DstIndex = -1;
8165 bool V1UsedInPlace = false;
8167 for (int i = 0; i < 4; ++i) {
8168 // Synthesize a zero mask from the zeroable elements (includes undefs).
8174 // Flag if we use any V1 inputs in place.
8176 V1UsedInPlace = true;
8180 // We can only insert a single non-zeroable element.
8181 if (V1DstIndex != -1 || V2DstIndex != -1)
8185 // V1 input out of place for insertion.
8188 // V2 input for insertion.
8193 // Don't bother if we have no (non-zeroable) element for insertion.
8194 if (V1DstIndex == -1 && V2DstIndex == -1)
8197 // Determine element insertion src/dst indices. The src index is from the
8198 // start of the inserted vector, not the start of the concatenated vector.
8199 unsigned V2SrcIndex = 0;
8200 if (V1DstIndex != -1) {
8201 // If we have a V1 input out of place, we use V1 as the V2 element insertion
8202 // and don't use the original V2 at all.
8203 V2SrcIndex = Mask[V1DstIndex];
8204 V2DstIndex = V1DstIndex;
8207 V2SrcIndex = Mask[V2DstIndex] - 4;
8210 // If no V1 inputs are used in place, then the result is created only from
8211 // the zero mask and the V2 insertion - so remove V1 dependency.
8213 V1 = DAG.getUNDEF(MVT::v4f32);
8215 unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
8216 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
8218 // Insert the V2 element into the desired position.
8220 return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
8221 DAG.getConstant(InsertPSMask, DL, MVT::i8));
8224 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
8225 /// UNPCK instruction.
8227 /// This specifically targets cases where we end up with alternating between
8228 /// the two inputs, and so can permute them into something that feeds a single
8229 /// UNPCK instruction. Note that this routine only targets integer vectors
8230 /// because for floating point vectors we have a generalized SHUFPS lowering
8231 /// strategy that handles everything that doesn't *exactly* match an unpack,
8232 /// making this clever lowering unnecessary.
8233 static SDValue lowerVectorShuffleAsPermuteAndUnpack(SDLoc DL, MVT VT,
8234 SDValue V1, SDValue V2,
8236 SelectionDAG &DAG) {
8237 assert(!VT.isFloatingPoint() &&
8238 "This routine only supports integer vectors.");
8239 assert(!isSingleInputShuffleMask(Mask) &&
8240 "This routine should only be used when blending two inputs.");
8241 assert(Mask.size() >= 2 && "Single element masks are invalid.");
8243 int Size = Mask.size();
8245 int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
8246 return M >= 0 && M % Size < Size / 2;
8248 int NumHiInputs = std::count_if(
8249 Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
8251 bool UnpackLo = NumLoInputs >= NumHiInputs;
8253 auto TryUnpack = [&](MVT UnpackVT, int Scale) {
8254 SmallVector<int, 32> V1Mask(Mask.size(), -1);
8255 SmallVector<int, 32> V2Mask(Mask.size(), -1);
8257 for (int i = 0; i < Size; ++i) {
8261 // Each element of the unpack contains Scale elements from this mask.
8262 int UnpackIdx = i / Scale;
8264 // We only handle the case where V1 feeds the first slots of the unpack.
8265 // We rely on canonicalization to ensure this is the case.
8266 if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
8269 // Setup the mask for this input. The indexing is tricky as we have to
8270 // handle the unpack stride.
8271 SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
8272 VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
8276 // If we will have to shuffle both inputs to use the unpack, check whether
8277 // we can just unpack first and shuffle the result. If so, skip this unpack.
8278 if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
8279 !isNoopShuffleMask(V2Mask))
8282 // Shuffle the inputs into place.
8283 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
8284 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
8286 // Cast the inputs to the type we will use to unpack them.
8287 V1 = DAG.getBitcast(UnpackVT, V1);
8288 V2 = DAG.getBitcast(UnpackVT, V2);
8290 // Unpack the inputs and cast the result back to the desired type.
8291 return DAG.getBitcast(
8292 VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8296 // We try each unpack from the largest to the smallest to try and find one
8297 // that fits this mask.
8298 int OrigNumElements = VT.getVectorNumElements();
8299 int OrigScalarSize = VT.getScalarSizeInBits();
8300 for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
8301 int Scale = ScalarSize / OrigScalarSize;
8302 int NumElements = OrigNumElements / Scale;
8303 MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
8304 if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
8308 // If none of the unpack-rooted lowerings worked (or were profitable) try an
8310 if (NumLoInputs == 0 || NumHiInputs == 0) {
8311 assert((NumLoInputs > 0 || NumHiInputs > 0) &&
8312 "We have to have *some* inputs!");
8313 int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
8315 // FIXME: We could consider the total complexity of the permute of each
8316 // possible unpacking. Or at the least we should consider how many
8317 // half-crossings are created.
8318 // FIXME: We could consider commuting the unpacks.
8320 SmallVector<int, 32> PermMask;
8321 PermMask.assign(Size, -1);
8322 for (int i = 0; i < Size; ++i) {
8326 assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
8329 2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
8331 return DAG.getVectorShuffle(
8332 VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
8334 DAG.getUNDEF(VT), PermMask);
8340 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
8342 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
8343 /// support for floating point shuffles but not integer shuffles. These
8344 /// instructions will incur a domain crossing penalty on some chips though so
8345 /// it is better to avoid lowering through this for integer vectors where
8347 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8348 const X86Subtarget *Subtarget,
8349 SelectionDAG &DAG) {
8351 assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
8352 assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8353 assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
8354 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8355 ArrayRef<int> Mask = SVOp->getMask();
8356 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8358 if (isSingleInputShuffleMask(Mask)) {
8359 // Use low duplicate instructions for masks that match their pattern.
8360 if (Subtarget->hasSSE3())
8361 if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
8362 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
8364 // Straight shuffle of a single input vector. Simulate this by using the
8365 // single input as both of the "inputs" to this instruction..
8366 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
8368 if (Subtarget->hasAVX()) {
8369 // If we have AVX, we can use VPERMILPS which will allow folding a load
8370 // into the shuffle.
8371 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
8372 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8375 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
8376 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8378 assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
8379 assert(Mask[1] >= 2 && "Non-canonicalized blend!");
8381 // If we have a single input, insert that into V1 if we can do so cheaply.
8382 if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
8383 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8384 DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
8386 // Try inverting the insertion since for v2 masks it is easy to do and we
8387 // can't reliably sort the mask one way or the other.
8388 int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
8389 Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
8390 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8391 DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
8395 // Try to use one of the special instruction patterns to handle two common
8396 // blend patterns if a zero-blend above didn't work.
8397 if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
8398 isShuffleEquivalent(V1, V2, Mask, {1, 3}))
8399 if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
8400 // We can either use a special instruction to load over the low double or
8401 // to move just the low double.
8403 isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
8405 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
8407 if (Subtarget->hasSSE41())
8408 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
8412 // Use dedicated unpack instructions for masks that match their pattern.
8414 lowerVectorShuffleWithUNPCK(DL, MVT::v2f64, Mask, V1, V2, DAG))
8417 unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
8418 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
8419 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
8422 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
8424 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
8425 /// the integer unit to minimize domain crossing penalties. However, for blends
8426 /// it falls back to the floating point shuffle operation with appropriate bit
8428 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8429 const X86Subtarget *Subtarget,
8430 SelectionDAG &DAG) {
8432 assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
8433 assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8434 assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
8435 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8436 ArrayRef<int> Mask = SVOp->getMask();
8437 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
8439 if (isSingleInputShuffleMask(Mask)) {
8440 // Check for being able to broadcast a single element.
8441 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
8442 Mask, Subtarget, DAG))
8445 // Straight shuffle of a single input vector. For everything from SSE2
8446 // onward this has a single fast instruction with no scary immediates.
8447 // We have to map the mask as it is actually a v4i32 shuffle instruction.
8448 V1 = DAG.getBitcast(MVT::v4i32, V1);
8449 int WidenedMask[4] = {
8450 std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
8451 std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
8452 return DAG.getBitcast(
8454 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8455 getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
8457 assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
8458 assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
8459 assert(Mask[0] < 2 && "We sort V1 to be the first input.");
8460 assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
8462 // If we have a blend of two PACKUS operations an the blend aligns with the
8463 // low and half halves, we can just merge the PACKUS operations. This is
8464 // particularly important as it lets us merge shuffles that this routine itself
8466 auto GetPackNode = [](SDValue V) {
8467 while (V.getOpcode() == ISD::BITCAST)
8468 V = V.getOperand(0);
8470 return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
8472 if (SDValue V1Pack = GetPackNode(V1))
8473 if (SDValue V2Pack = GetPackNode(V2))
8474 return DAG.getBitcast(MVT::v2i64,
8475 DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
8476 Mask[0] == 0 ? V1Pack.getOperand(0)
8477 : V1Pack.getOperand(1),
8478 Mask[1] == 2 ? V2Pack.getOperand(0)
8479 : V2Pack.getOperand(1)));
8481 // Try to use shift instructions.
8483 lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
8486 // When loading a scalar and then shuffling it into a vector we can often do
8487 // the insertion cheaply.
8488 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8489 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8491 // Try inverting the insertion since for v2 masks it is easy to do and we
8492 // can't reliably sort the mask one way or the other.
8493 int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
8494 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
8495 DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
8498 // We have different paths for blend lowering, but they all must use the
8499 // *exact* same predicate.
8500 bool IsBlendSupported = Subtarget->hasSSE41();
8501 if (IsBlendSupported)
8502 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
8506 // Use dedicated unpack instructions for masks that match their pattern.
8508 lowerVectorShuffleWithUNPCK(DL, MVT::v2i64, Mask, V1, V2, DAG))
8511 // Try to use byte rotation instructions.
8512 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8513 if (Subtarget->hasSSSE3())
8514 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8515 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
8518 // If we have direct support for blends, we should lower by decomposing into
8519 // a permute. That will be faster than the domain cross.
8520 if (IsBlendSupported)
8521 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
8524 // We implement this with SHUFPD which is pretty lame because it will likely
8525 // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
8526 // However, all the alternatives are still more cycles and newer chips don't
8527 // have this problem. It would be really nice if x86 had better shuffles here.
8528 V1 = DAG.getBitcast(MVT::v2f64, V1);
8529 V2 = DAG.getBitcast(MVT::v2f64, V2);
8530 return DAG.getBitcast(MVT::v2i64,
8531 DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
8534 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
8536 /// This is used to disable more specialized lowerings when the shufps lowering
8537 /// will happen to be efficient.
8538 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
8539 // This routine only handles 128-bit shufps.
8540 assert(Mask.size() == 4 && "Unsupported mask size!");
8542 // To lower with a single SHUFPS we need to have the low half and high half
8543 // each requiring a single input.
8544 if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
8546 if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
8552 /// \brief Lower a vector shuffle using the SHUFPS instruction.
8554 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
8555 /// It makes no assumptions about whether this is the *best* lowering, it simply
8557 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
8558 ArrayRef<int> Mask, SDValue V1,
8559 SDValue V2, SelectionDAG &DAG) {
8560 SDValue LowV = V1, HighV = V2;
8561 int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
8564 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8566 if (NumV2Elements == 1) {
8568 std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
8571 // Compute the index adjacent to V2Index and in the same half by toggling
8573 int V2AdjIndex = V2Index ^ 1;
8575 if (Mask[V2AdjIndex] == -1) {
8576 // Handles all the cases where we have a single V2 element and an undef.
8577 // This will only ever happen in the high lanes because we commute the
8578 // vector otherwise.
8580 std::swap(LowV, HighV);
8581 NewMask[V2Index] -= 4;
8583 // Handle the case where the V2 element ends up adjacent to a V1 element.
8584 // To make this work, blend them together as the first step.
8585 int V1Index = V2AdjIndex;
8586 int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
8587 V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
8588 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8590 // Now proceed to reconstruct the final blend as we have the necessary
8591 // high or low half formed.
8598 NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8599 NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8601 } else if (NumV2Elements == 2) {
8602 if (Mask[0] < 4 && Mask[1] < 4) {
8603 // Handle the easy case where we have V1 in the low lanes and V2 in the
8607 } else if (Mask[2] < 4 && Mask[3] < 4) {
8608 // We also handle the reversed case because this utility may get called
8609 // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8610 // arrange things in the right direction.
8616 // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8617 // trying to place elements directly, just blend them and set up the final
8618 // shuffle to place them.
8620 // The first two blend mask elements are for V1, the second two are for
8622 int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8623 Mask[2] < 4 ? Mask[2] : Mask[3],
8624 (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8625 (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8626 V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8627 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8629 // Now we do a normal shuffle of V1 by giving V1 as both operands to
8632 NewMask[0] = Mask[0] < 4 ? 0 : 2;
8633 NewMask[1] = Mask[0] < 4 ? 2 : 0;
8634 NewMask[2] = Mask[2] < 4 ? 1 : 3;
8635 NewMask[3] = Mask[2] < 4 ? 3 : 1;
8638 return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8639 getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8642 /// \brief Lower 4-lane 32-bit floating point shuffles.
8644 /// Uses instructions exclusively from the floating point unit to minimize
8645 /// domain crossing penalties, as these are sufficient to implement all v4f32
8647 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8648 const X86Subtarget *Subtarget,
8649 SelectionDAG &DAG) {
8651 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8652 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8653 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8654 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8655 ArrayRef<int> Mask = SVOp->getMask();
8656 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8659 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8661 if (NumV2Elements == 0) {
8662 // Check for being able to broadcast a single element.
8663 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8664 Mask, Subtarget, DAG))
8667 // Use even/odd duplicate instructions for masks that match their pattern.
8668 if (Subtarget->hasSSE3()) {
8669 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8670 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8671 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8672 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8675 if (Subtarget->hasAVX()) {
8676 // If we have AVX, we can use VPERMILPS which will allow folding a load
8677 // into the shuffle.
8678 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8679 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8682 // Otherwise, use a straight shuffle of a single input vector. We pass the
8683 // input vector to both operands to simulate this with a SHUFPS.
8684 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8685 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8688 // There are special ways we can lower some single-element blends. However, we
8689 // have custom ways we can lower more complex single-element blends below that
8690 // we defer to if both this and BLENDPS fail to match, so restrict this to
8691 // when the V2 input is targeting element 0 of the mask -- that is the fast
8693 if (NumV2Elements == 1 && Mask[0] >= 4)
8694 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8695 Mask, Subtarget, DAG))
8698 if (Subtarget->hasSSE41()) {
8699 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8703 // Use INSERTPS if we can complete the shuffle efficiently.
8704 if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8707 if (!isSingleSHUFPSMask(Mask))
8708 if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8709 DL, MVT::v4f32, V1, V2, Mask, DAG))
8713 // Use dedicated unpack instructions for masks that match their pattern.
8715 lowerVectorShuffleWithUNPCK(DL, MVT::v4f32, Mask, V1, V2, DAG))
8718 // Otherwise fall back to a SHUFPS lowering strategy.
8719 return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8722 /// \brief Lower 4-lane i32 vector shuffles.
8724 /// We try to handle these with integer-domain shuffles where we can, but for
8725 /// blends we use the floating point domain blend instructions.
8726 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8727 const X86Subtarget *Subtarget,
8728 SelectionDAG &DAG) {
8730 assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8731 assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8732 assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8733 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8734 ArrayRef<int> Mask = SVOp->getMask();
8735 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8737 // Whenever we can lower this as a zext, that instruction is strictly faster
8738 // than any alternative. It also allows us to fold memory operands into the
8739 // shuffle in many cases.
8740 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8741 Mask, Subtarget, DAG))
8745 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8747 if (NumV2Elements == 0) {
8748 // Check for being able to broadcast a single element.
8749 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8750 Mask, Subtarget, DAG))
8753 // Straight shuffle of a single input vector. For everything from SSE2
8754 // onward this has a single fast instruction with no scary immediates.
8755 // We coerce the shuffle pattern to be compatible with UNPCK instructions
8756 // but we aren't actually going to use the UNPCK instruction because doing
8757 // so prevents folding a load into this instruction or making a copy.
8758 const int UnpackLoMask[] = {0, 0, 1, 1};
8759 const int UnpackHiMask[] = {2, 2, 3, 3};
8760 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8761 Mask = UnpackLoMask;
8762 else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8763 Mask = UnpackHiMask;
8765 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8766 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8769 // Try to use shift instructions.
8771 lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8774 // There are special ways we can lower some single-element blends.
8775 if (NumV2Elements == 1)
8776 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8777 Mask, Subtarget, DAG))
8780 // We have different paths for blend lowering, but they all must use the
8781 // *exact* same predicate.
8782 bool IsBlendSupported = Subtarget->hasSSE41();
8783 if (IsBlendSupported)
8784 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8788 if (SDValue Masked =
8789 lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8792 // Use dedicated unpack instructions for masks that match their pattern.
8794 lowerVectorShuffleWithUNPCK(DL, MVT::v4i32, Mask, V1, V2, DAG))
8797 // Try to use byte rotation instructions.
8798 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8799 if (Subtarget->hasSSSE3())
8800 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8801 DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8804 // If we have direct support for blends, we should lower by decomposing into
8805 // a permute. That will be faster than the domain cross.
8806 if (IsBlendSupported)
8807 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8810 // Try to lower by permuting the inputs into an unpack instruction.
8811 if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v4i32, V1,
8815 // We implement this with SHUFPS because it can blend from two vectors.
8816 // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8817 // up the inputs, bypassing domain shift penalties that we would encur if we
8818 // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8820 return DAG.getBitcast(
8822 DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8823 DAG.getBitcast(MVT::v4f32, V2), Mask));
8826 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8827 /// shuffle lowering, and the most complex part.
8829 /// The lowering strategy is to try to form pairs of input lanes which are
8830 /// targeted at the same half of the final vector, and then use a dword shuffle
8831 /// to place them onto the right half, and finally unpack the paired lanes into
8832 /// their final position.
8834 /// The exact breakdown of how to form these dword pairs and align them on the
8835 /// correct sides is really tricky. See the comments within the function for
8836 /// more of the details.
8838 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8839 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8840 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8841 /// vector, form the analogous 128-bit 8-element Mask.
8842 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8843 SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8844 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8845 assert(VT.getVectorElementType() == MVT::i16 && "Bad input type!");
8846 MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8848 assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8849 MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8850 MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8852 SmallVector<int, 4> LoInputs;
8853 std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8854 [](int M) { return M >= 0; });
8855 std::sort(LoInputs.begin(), LoInputs.end());
8856 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8857 SmallVector<int, 4> HiInputs;
8858 std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8859 [](int M) { return M >= 0; });
8860 std::sort(HiInputs.begin(), HiInputs.end());
8861 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8863 std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8864 int NumHToL = LoInputs.size() - NumLToL;
8866 std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8867 int NumHToH = HiInputs.size() - NumLToH;
8868 MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8869 MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8870 MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8871 MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8873 // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8874 // such inputs we can swap two of the dwords across the half mark and end up
8875 // with <=2 inputs to each half in each half. Once there, we can fall through
8876 // to the generic code below. For example:
8878 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8879 // Mask: [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8881 // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8882 // and an existing 2-into-2 on the other half. In this case we may have to
8883 // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8884 // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8885 // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8886 // because any other situation (including a 3-into-1 or 1-into-3 in the other
8887 // half than the one we target for fixing) will be fixed when we re-enter this
8888 // path. We will also combine away any sequence of PSHUFD instructions that
8889 // result into a single instruction. Here is an example of the tricky case:
8891 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8892 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8894 // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8896 // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8897 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8899 // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8900 // Mask: [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8902 // The result is fine to be handled by the generic logic.
8903 auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8904 ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8905 int AOffset, int BOffset) {
8906 assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8907 "Must call this with A having 3 or 1 inputs from the A half.");
8908 assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8909 "Must call this with B having 1 or 3 inputs from the B half.");
8910 assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8911 "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8913 bool ThreeAInputs = AToAInputs.size() == 3;
8915 // Compute the index of dword with only one word among the three inputs in
8916 // a half by taking the sum of the half with three inputs and subtracting
8917 // the sum of the actual three inputs. The difference is the remaining
8920 int &TripleDWord = ThreeAInputs ? ADWord : BDWord;
8921 int &OneInputDWord = ThreeAInputs ? BDWord : ADWord;
8922 int TripleInputOffset = ThreeAInputs ? AOffset : BOffset;
8923 ArrayRef<int> TripleInputs = ThreeAInputs ? AToAInputs : BToAInputs;
8924 int OneInput = ThreeAInputs ? BToAInputs[0] : AToAInputs[0];
8925 int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8926 int TripleNonInputIdx =
8927 TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8928 TripleDWord = TripleNonInputIdx / 2;
8930 // We use xor with one to compute the adjacent DWord to whichever one the
8932 OneInputDWord = (OneInput / 2) ^ 1;
8934 // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8935 // and BToA inputs. If there is also such a problem with the BToB and AToB
8936 // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8937 // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8938 // is essential that we don't *create* a 3<-1 as then we might oscillate.
8939 if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8940 // Compute how many inputs will be flipped by swapping these DWords. We
8942 // to balance this to ensure we don't form a 3-1 shuffle in the other
8944 int NumFlippedAToBInputs =
8945 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8946 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8947 int NumFlippedBToBInputs =
8948 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8949 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8950 if ((NumFlippedAToBInputs == 1 &&
8951 (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8952 (NumFlippedBToBInputs == 1 &&
8953 (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8954 // We choose whether to fix the A half or B half based on whether that
8955 // half has zero flipped inputs. At zero, we may not be able to fix it
8956 // with that half. We also bias towards fixing the B half because that
8957 // will more commonly be the high half, and we have to bias one way.
8958 auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8959 ArrayRef<int> Inputs) {
8960 int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8961 bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8962 PinnedIdx ^ 1) != Inputs.end();
8963 // Determine whether the free index is in the flipped dword or the
8964 // unflipped dword based on where the pinned index is. We use this bit
8965 // in an xor to conditionally select the adjacent dword.
8966 int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8967 bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8968 FixFreeIdx) != Inputs.end();
8969 if (IsFixIdxInput == IsFixFreeIdxInput)
8971 IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8972 FixFreeIdx) != Inputs.end();
8973 assert(IsFixIdxInput != IsFixFreeIdxInput &&
8974 "We need to be changing the number of flipped inputs!");
8975 int PSHUFHalfMask[] = {0, 1, 2, 3};
8976 std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8977 V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8979 getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8982 if (M != -1 && M == FixIdx)
8984 else if (M != -1 && M == FixFreeIdx)
8987 if (NumFlippedBToBInputs != 0) {
8989 BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8990 FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8992 assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8993 int APinnedIdx = ThreeAInputs ? TripleNonInputIdx : OneInput;
8994 FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8999 int PSHUFDMask[] = {0, 1, 2, 3};
9000 PSHUFDMask[ADWord] = BDWord;
9001 PSHUFDMask[BDWord] = ADWord;
9004 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
9005 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9007 // Adjust the mask to match the new locations of A and B.
9009 if (M != -1 && M/2 == ADWord)
9010 M = 2 * BDWord + M % 2;
9011 else if (M != -1 && M/2 == BDWord)
9012 M = 2 * ADWord + M % 2;
9014 // Recurse back into this routine to re-compute state now that this isn't
9015 // a 3 and 1 problem.
9016 return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
9019 if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
9020 return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
9021 else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
9022 return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
9024 // At this point there are at most two inputs to the low and high halves from
9025 // each half. That means the inputs can always be grouped into dwords and
9026 // those dwords can then be moved to the correct half with a dword shuffle.
9027 // We use at most one low and one high word shuffle to collect these paired
9028 // inputs into dwords, and finally a dword shuffle to place them.
9029 int PSHUFLMask[4] = {-1, -1, -1, -1};
9030 int PSHUFHMask[4] = {-1, -1, -1, -1};
9031 int PSHUFDMask[4] = {-1, -1, -1, -1};
9033 // First fix the masks for all the inputs that are staying in their
9034 // original halves. This will then dictate the targets of the cross-half
9036 auto fixInPlaceInputs =
9037 [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
9038 MutableArrayRef<int> SourceHalfMask,
9039 MutableArrayRef<int> HalfMask, int HalfOffset) {
9040 if (InPlaceInputs.empty())
9042 if (InPlaceInputs.size() == 1) {
9043 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
9044 InPlaceInputs[0] - HalfOffset;
9045 PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
9048 if (IncomingInputs.empty()) {
9049 // Just fix all of the in place inputs.
9050 for (int Input : InPlaceInputs) {
9051 SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
9052 PSHUFDMask[Input / 2] = Input / 2;
9057 assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
9058 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
9059 InPlaceInputs[0] - HalfOffset;
9060 // Put the second input next to the first so that they are packed into
9061 // a dword. We find the adjacent index by toggling the low bit.
9062 int AdjIndex = InPlaceInputs[0] ^ 1;
9063 SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
9064 std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
9065 PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
9067 fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
9068 fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
9070 // Now gather the cross-half inputs and place them into a free dword of
9071 // their target half.
9072 // FIXME: This operation could almost certainly be simplified dramatically to
9073 // look more like the 3-1 fixing operation.
9074 auto moveInputsToRightHalf = [&PSHUFDMask](
9075 MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
9076 MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
9077 MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
9079 auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
9080 return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
9082 auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
9084 int LowWord = Word & ~1;
9085 int HighWord = Word | 1;
9086 return isWordClobbered(SourceHalfMask, LowWord) ||
9087 isWordClobbered(SourceHalfMask, HighWord);
9090 if (IncomingInputs.empty())
9093 if (ExistingInputs.empty()) {
9094 // Map any dwords with inputs from them into the right half.
9095 for (int Input : IncomingInputs) {
9096 // If the source half mask maps over the inputs, turn those into
9097 // swaps and use the swapped lane.
9098 if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
9099 if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
9100 SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
9101 Input - SourceOffset;
9102 // We have to swap the uses in our half mask in one sweep.
9103 for (int &M : HalfMask)
9104 if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
9106 else if (M == Input)
9107 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
9109 assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
9110 Input - SourceOffset &&
9111 "Previous placement doesn't match!");
9113 // Note that this correctly re-maps both when we do a swap and when
9114 // we observe the other side of the swap above. We rely on that to
9115 // avoid swapping the members of the input list directly.
9116 Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
9119 // Map the input's dword into the correct half.
9120 if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
9121 PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
9123 assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
9125 "Previous placement doesn't match!");
9128 // And just directly shift any other-half mask elements to be same-half
9129 // as we will have mirrored the dword containing the element into the
9130 // same position within that half.
9131 for (int &M : HalfMask)
9132 if (M >= SourceOffset && M < SourceOffset + 4) {
9133 M = M - SourceOffset + DestOffset;
9134 assert(M >= 0 && "This should never wrap below zero!");
9139 // Ensure we have the input in a viable dword of its current half. This
9140 // is particularly tricky because the original position may be clobbered
9141 // by inputs being moved and *staying* in that half.
9142 if (IncomingInputs.size() == 1) {
9143 if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
9144 int InputFixed = std::find(std::begin(SourceHalfMask),
9145 std::end(SourceHalfMask), -1) -
9146 std::begin(SourceHalfMask) + SourceOffset;
9147 SourceHalfMask[InputFixed - SourceOffset] =
9148 IncomingInputs[0] - SourceOffset;
9149 std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
9151 IncomingInputs[0] = InputFixed;
9153 } else if (IncomingInputs.size() == 2) {
9154 if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
9155 isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
9156 // We have two non-adjacent or clobbered inputs we need to extract from
9157 // the source half. To do this, we need to map them into some adjacent
9158 // dword slot in the source mask.
9159 int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
9160 IncomingInputs[1] - SourceOffset};
9162 // If there is a free slot in the source half mask adjacent to one of
9163 // the inputs, place the other input in it. We use (Index XOR 1) to
9164 // compute an adjacent index.
9165 if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
9166 SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
9167 SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
9168 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
9169 InputsFixed[1] = InputsFixed[0] ^ 1;
9170 } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
9171 SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
9172 SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
9173 SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
9174 InputsFixed[0] = InputsFixed[1] ^ 1;
9175 } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
9176 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
9177 // The two inputs are in the same DWord but it is clobbered and the
9178 // adjacent DWord isn't used at all. Move both inputs to the free
9180 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
9181 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
9182 InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
9183 InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
9185 // The only way we hit this point is if there is no clobbering
9186 // (because there are no off-half inputs to this half) and there is no
9187 // free slot adjacent to one of the inputs. In this case, we have to
9188 // swap an input with a non-input.
9189 for (int i = 0; i < 4; ++i)
9190 assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
9191 "We can't handle any clobbers here!");
9192 assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
9193 "Cannot have adjacent inputs here!");
9195 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
9196 SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
9198 // We also have to update the final source mask in this case because
9199 // it may need to undo the above swap.
9200 for (int &M : FinalSourceHalfMask)
9201 if (M == (InputsFixed[0] ^ 1) + SourceOffset)
9202 M = InputsFixed[1] + SourceOffset;
9203 else if (M == InputsFixed[1] + SourceOffset)
9204 M = (InputsFixed[0] ^ 1) + SourceOffset;
9206 InputsFixed[1] = InputsFixed[0] ^ 1;
9209 // Point everything at the fixed inputs.
9210 for (int &M : HalfMask)
9211 if (M == IncomingInputs[0])
9212 M = InputsFixed[0] + SourceOffset;
9213 else if (M == IncomingInputs[1])
9214 M = InputsFixed[1] + SourceOffset;
9216 IncomingInputs[0] = InputsFixed[0] + SourceOffset;
9217 IncomingInputs[1] = InputsFixed[1] + SourceOffset;
9220 llvm_unreachable("Unhandled input size!");
9223 // Now hoist the DWord down to the right half.
9224 int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
9225 assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
9226 PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
9227 for (int &M : HalfMask)
9228 for (int Input : IncomingInputs)
9230 M = FreeDWord * 2 + Input % 2;
9232 moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
9233 /*SourceOffset*/ 4, /*DestOffset*/ 0);
9234 moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
9235 /*SourceOffset*/ 0, /*DestOffset*/ 4);
9237 // Now enact all the shuffles we've computed to move the inputs into their
9239 if (!isNoopShuffleMask(PSHUFLMask))
9240 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
9241 getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
9242 if (!isNoopShuffleMask(PSHUFHMask))
9243 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
9244 getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
9245 if (!isNoopShuffleMask(PSHUFDMask))
9248 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
9249 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9251 // At this point, each half should contain all its inputs, and we can then
9252 // just shuffle them into their final position.
9253 assert(std::count_if(LoMask.begin(), LoMask.end(),
9254 [](int M) { return M >= 4; }) == 0 &&
9255 "Failed to lift all the high half inputs to the low mask!");
9256 assert(std::count_if(HiMask.begin(), HiMask.end(),
9257 [](int M) { return M >= 0 && M < 4; }) == 0 &&
9258 "Failed to lift all the low half inputs to the high mask!");
9260 // Do a half shuffle for the low mask.
9261 if (!isNoopShuffleMask(LoMask))
9262 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
9263 getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
9265 // Do a half shuffle with the high mask after shifting its values down.
9266 for (int &M : HiMask)
9269 if (!isNoopShuffleMask(HiMask))
9270 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
9271 getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
9276 /// \brief Helper to form a PSHUFB-based shuffle+blend.
9277 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
9278 SDValue V2, ArrayRef<int> Mask,
9279 SelectionDAG &DAG, bool &V1InUse,
9281 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
9287 int Size = Mask.size();
9288 int Scale = 16 / Size;
9289 for (int i = 0; i < 16; ++i) {
9290 if (Mask[i / Scale] == -1) {
9291 V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
9293 const int ZeroMask = 0x80;
9294 int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
9296 int V2Idx = Mask[i / Scale] < Size
9298 : (Mask[i / Scale] - Size) * Scale + i % Scale;
9299 if (Zeroable[i / Scale])
9300 V1Idx = V2Idx = ZeroMask;
9301 V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
9302 V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
9303 V1InUse |= (ZeroMask != V1Idx);
9304 V2InUse |= (ZeroMask != V2Idx);
9309 V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9310 DAG.getBitcast(MVT::v16i8, V1),
9311 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
9313 V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
9314 DAG.getBitcast(MVT::v16i8, V2),
9315 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
9317 // If we need shuffled inputs from both, blend the two.
9319 if (V1InUse && V2InUse)
9320 V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
9322 V = V1InUse ? V1 : V2;
9324 // Cast the result back to the correct type.
9325 return DAG.getBitcast(VT, V);
9328 /// \brief Generic lowering of 8-lane i16 shuffles.
9330 /// This handles both single-input shuffles and combined shuffle/blends with
9331 /// two inputs. The single input shuffles are immediately delegated to
9332 /// a dedicated lowering routine.
9334 /// The blends are lowered in one of three fundamental ways. If there are few
9335 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
9336 /// of the input is significantly cheaper when lowered as an interleaving of
9337 /// the two inputs, try to interleave them. Otherwise, blend the low and high
9338 /// halves of the inputs separately (making them have relatively few inputs)
9339 /// and then concatenate them.
9340 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9341 const X86Subtarget *Subtarget,
9342 SelectionDAG &DAG) {
9344 assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
9345 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9346 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
9347 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9348 ArrayRef<int> OrigMask = SVOp->getMask();
9349 int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
9350 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
9351 MutableArrayRef<int> Mask(MaskStorage);
9353 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9355 // Whenever we can lower this as a zext, that instruction is strictly faster
9356 // than any alternative.
9357 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9358 DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
9361 auto isV1 = [](int M) { return M >= 0 && M < 8; };
9363 auto isV2 = [](int M) { return M >= 8; };
9365 int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
9367 if (NumV2Inputs == 0) {
9368 // Check for being able to broadcast a single element.
9369 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
9370 Mask, Subtarget, DAG))
9373 // Try to use shift instructions.
9375 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
9378 // Use dedicated unpack instructions for masks that match their pattern.
9380 lowerVectorShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
9383 // Try to use byte rotation instructions.
9384 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
9385 Mask, Subtarget, DAG))
9388 return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
9392 assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
9393 "All single-input shuffles should be canonicalized to be V1-input "
9396 // Try to use shift instructions.
9398 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
9401 // See if we can use SSE4A Extraction / Insertion.
9402 if (Subtarget->hasSSE4A())
9403 if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
9406 // There are special ways we can lower some single-element blends.
9407 if (NumV2Inputs == 1)
9408 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
9409 Mask, Subtarget, DAG))
9412 // We have different paths for blend lowering, but they all must use the
9413 // *exact* same predicate.
9414 bool IsBlendSupported = Subtarget->hasSSE41();
9415 if (IsBlendSupported)
9416 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
9420 if (SDValue Masked =
9421 lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
9424 // Use dedicated unpack instructions for masks that match their pattern.
9426 lowerVectorShuffleWithUNPCK(DL, MVT::v8i16, Mask, V1, V2, DAG))
9429 // Try to use byte rotation instructions.
9430 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9431 DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
9434 if (SDValue BitBlend =
9435 lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
9438 if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(DL, MVT::v8i16, V1,
9442 // If we can't directly blend but can use PSHUFB, that will be better as it
9443 // can both shuffle and set up the inefficient blend.
9444 if (!IsBlendSupported && Subtarget->hasSSSE3()) {
9445 bool V1InUse, V2InUse;
9446 return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
9450 // We can always bit-blend if we have to so the fallback strategy is to
9451 // decompose into single-input permutes and blends.
9452 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
9456 /// \brief Check whether a compaction lowering can be done by dropping even
9457 /// elements and compute how many times even elements must be dropped.
9459 /// This handles shuffles which take every Nth element where N is a power of
9460 /// two. Example shuffle masks:
9462 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14
9463 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
9464 /// N = 2: 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12
9465 /// N = 2: 0, 4, 8, 12, 16, 20, 24, 28, 0, 4, 8, 12, 16, 20, 24, 28
9466 /// N = 3: 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8
9467 /// N = 3: 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24
9469 /// Any of these lanes can of course be undef.
9471 /// This routine only supports N <= 3.
9472 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
9475 /// \returns N above, or the number of times even elements must be dropped if
9476 /// there is such a number. Otherwise returns zero.
9477 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
9478 // Figure out whether we're looping over two inputs or just one.
9479 bool IsSingleInput = isSingleInputShuffleMask(Mask);
9481 // The modulus for the shuffle vector entries is based on whether this is
9482 // a single input or not.
9483 int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
9484 assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
9485 "We should only be called with masks with a power-of-2 size!");
9487 uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
9489 // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
9490 // and 2^3 simultaneously. This is because we may have ambiguity with
9491 // partially undef inputs.
9492 bool ViableForN[3] = {true, true, true};
9494 for (int i = 0, e = Mask.size(); i < e; ++i) {
9495 // Ignore undef lanes, we'll optimistically collapse them to the pattern we
9500 bool IsAnyViable = false;
9501 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9502 if (ViableForN[j]) {
9505 // The shuffle mask must be equal to (i * 2^N) % M.
9506 if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
9509 ViableForN[j] = false;
9511 // Early exit if we exhaust the possible powers of two.
9516 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
9520 // Return 0 as there is no viable power of two.
9524 /// \brief Generic lowering of v16i8 shuffles.
9526 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
9527 /// detect any complexity reducing interleaving. If that doesn't help, it uses
9528 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
9529 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
9531 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9532 const X86Subtarget *Subtarget,
9533 SelectionDAG &DAG) {
9535 assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
9536 assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9537 assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
9538 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9539 ArrayRef<int> Mask = SVOp->getMask();
9540 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9542 // Try to use shift instructions.
9544 lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
9547 // Try to use byte rotation instructions.
9548 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9549 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9552 // Try to use a zext lowering.
9553 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
9554 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
9557 // See if we can use SSE4A Extraction / Insertion.
9558 if (Subtarget->hasSSE4A())
9559 if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
9563 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
9565 // For single-input shuffles, there are some nicer lowering tricks we can use.
9566 if (NumV2Elements == 0) {
9567 // Check for being able to broadcast a single element.
9568 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
9569 Mask, Subtarget, DAG))
9572 // Check whether we can widen this to an i16 shuffle by duplicating bytes.
9573 // Notably, this handles splat and partial-splat shuffles more efficiently.
9574 // However, it only makes sense if the pre-duplication shuffle simplifies
9575 // things significantly. Currently, this means we need to be able to
9576 // express the pre-duplication shuffle as an i16 shuffle.
9578 // FIXME: We should check for other patterns which can be widened into an
9579 // i16 shuffle as well.
9580 auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9581 for (int i = 0; i < 16; i += 2)
9582 if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9587 auto tryToWidenViaDuplication = [&]() -> SDValue {
9588 if (!canWidenViaDuplication(Mask))
9590 SmallVector<int, 4> LoInputs;
9591 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9592 [](int M) { return M >= 0 && M < 8; });
9593 std::sort(LoInputs.begin(), LoInputs.end());
9594 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9596 SmallVector<int, 4> HiInputs;
9597 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9598 [](int M) { return M >= 8; });
9599 std::sort(HiInputs.begin(), HiInputs.end());
9600 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9603 bool TargetLo = LoInputs.size() >= HiInputs.size();
9604 ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9605 ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9607 int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9608 SmallDenseMap<int, int, 8> LaneMap;
9609 for (int I : InPlaceInputs) {
9610 PreDupI16Shuffle[I/2] = I/2;
9613 int j = TargetLo ? 0 : 4, je = j + 4;
9614 for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9615 // Check if j is already a shuffle of this input. This happens when
9616 // there are two adjacent bytes after we move the low one.
9617 if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9618 // If we haven't yet mapped the input, search for a slot into which
9620 while (j < je && PreDupI16Shuffle[j] != -1)
9624 // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9627 // Map this input with the i16 shuffle.
9628 PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9631 // Update the lane map based on the mapping we ended up with.
9632 LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9634 V1 = DAG.getBitcast(
9636 DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9637 DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9639 // Unpack the bytes to form the i16s that will be shuffled into place.
9640 V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9641 MVT::v16i8, V1, V1);
9643 int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9644 for (int i = 0; i < 16; ++i)
9645 if (Mask[i] != -1) {
9646 int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9647 assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9648 if (PostDupI16Shuffle[i / 2] == -1)
9649 PostDupI16Shuffle[i / 2] = MappedMask;
9651 assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9652 "Conflicting entrties in the original shuffle!");
9654 return DAG.getBitcast(
9656 DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9657 DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9659 if (SDValue V = tryToWidenViaDuplication())
9663 if (SDValue Masked =
9664 lowerVectorShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask, DAG))
9667 // Use dedicated unpack instructions for masks that match their pattern.
9669 lowerVectorShuffleWithUNPCK(DL, MVT::v16i8, Mask, V1, V2, DAG))
9672 // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9673 // with PSHUFB. It is important to do this before we attempt to generate any
9674 // blends but after all of the single-input lowerings. If the single input
9675 // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9676 // want to preserve that and we can DAG combine any longer sequences into
9677 // a PSHUFB in the end. But once we start blending from multiple inputs,
9678 // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9679 // and there are *very* few patterns that would actually be faster than the
9680 // PSHUFB approach because of its ability to zero lanes.
9682 // FIXME: The only exceptions to the above are blends which are exact
9683 // interleavings with direct instructions supporting them. We currently don't
9684 // handle those well here.
9685 if (Subtarget->hasSSSE3()) {
9686 bool V1InUse = false;
9687 bool V2InUse = false;
9689 SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9690 DAG, V1InUse, V2InUse);
9692 // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9693 // do so. This avoids using them to handle blends-with-zero which is
9694 // important as a single pshufb is significantly faster for that.
9695 if (V1InUse && V2InUse) {
9696 if (Subtarget->hasSSE41())
9697 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9698 Mask, Subtarget, DAG))
9701 // We can use an unpack to do the blending rather than an or in some
9702 // cases. Even though the or may be (very minorly) more efficient, we
9703 // preference this lowering because there are common cases where part of
9704 // the complexity of the shuffles goes away when we do the final blend as
9706 // FIXME: It might be worth trying to detect if the unpack-feeding
9707 // shuffles will both be pshufb, in which case we shouldn't bother with
9709 if (SDValue Unpack = lowerVectorShuffleAsPermuteAndUnpack(
9710 DL, MVT::v16i8, V1, V2, Mask, DAG))
9717 // There are special ways we can lower some single-element blends.
9718 if (NumV2Elements == 1)
9719 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9720 Mask, Subtarget, DAG))
9723 if (SDValue BitBlend =
9724 lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9727 // Check whether a compaction lowering can be done. This handles shuffles
9728 // which take every Nth element for some even N. See the helper function for
9731 // We special case these as they can be particularly efficiently handled with
9732 // the PACKUSB instruction on x86 and they show up in common patterns of
9733 // rearranging bytes to truncate wide elements.
9734 if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9735 // NumEvenDrops is the power of two stride of the elements. Another way of
9736 // thinking about it is that we need to drop the even elements this many
9737 // times to get the original input.
9738 bool IsSingleInput = isSingleInputShuffleMask(Mask);
9740 // First we need to zero all the dropped bytes.
9741 assert(NumEvenDrops <= 3 &&
9742 "No support for dropping even elements more than 3 times.");
9743 // We use the mask type to pick which bytes are preserved based on how many
9744 // elements are dropped.
9745 MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9746 SDValue ByteClearMask = DAG.getBitcast(
9747 MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9748 V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9750 V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9752 // Now pack things back together.
9753 V1 = DAG.getBitcast(MVT::v8i16, V1);
9754 V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9755 SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9756 for (int i = 1; i < NumEvenDrops; ++i) {
9757 Result = DAG.getBitcast(MVT::v8i16, Result);
9758 Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9764 // Handle multi-input cases by blending single-input shuffles.
9765 if (NumV2Elements > 0)
9766 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9769 // The fallback path for single-input shuffles widens this into two v8i16
9770 // vectors with unpacks, shuffles those, and then pulls them back together
9774 int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9775 int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9776 for (int i = 0; i < 16; ++i)
9778 (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9780 SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9782 SDValue VLoHalf, VHiHalf;
9783 // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9784 // them out and avoid using UNPCK{L,H} to extract the elements of V as
9786 if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9787 [](int M) { return M >= 0 && M % 2 == 1; }) &&
9788 std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9789 [](int M) { return M >= 0 && M % 2 == 1; })) {
9790 // Use a mask to drop the high bytes.
9791 VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9792 VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9793 DAG.getConstant(0x00FF, DL, MVT::v8i16));
9795 // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9796 VHiHalf = DAG.getUNDEF(MVT::v8i16);
9798 // Squash the masks to point directly into VLoHalf.
9799 for (int &M : LoBlendMask)
9802 for (int &M : HiBlendMask)
9806 // Otherwise just unpack the low half of V into VLoHalf and the high half into
9807 // VHiHalf so that we can blend them as i16s.
9808 VLoHalf = DAG.getBitcast(
9809 MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9810 VHiHalf = DAG.getBitcast(
9811 MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9814 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9815 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9817 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9820 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9822 /// This routine breaks down the specific type of 128-bit shuffle and
9823 /// dispatches to the lowering routines accordingly.
9824 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9825 MVT VT, const X86Subtarget *Subtarget,
9826 SelectionDAG &DAG) {
9827 switch (VT.SimpleTy) {
9829 return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9831 return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9833 return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9835 return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9837 return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9839 return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9842 llvm_unreachable("Unimplemented!");
9846 /// \brief Helper function to test whether a shuffle mask could be
9847 /// simplified by widening the elements being shuffled.
9849 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9850 /// leaves it in an unspecified state.
9852 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9853 /// shuffle masks. The latter have the special property of a '-2' representing
9854 /// a zero-ed lane of a vector.
9855 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9856 SmallVectorImpl<int> &WidenedMask) {
9857 for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9858 // If both elements are undef, its trivial.
9859 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9860 WidenedMask.push_back(SM_SentinelUndef);
9864 // Check for an undef mask and a mask value properly aligned to fit with
9865 // a pair of values. If we find such a case, use the non-undef mask's value.
9866 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9867 WidenedMask.push_back(Mask[i + 1] / 2);
9870 if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9871 WidenedMask.push_back(Mask[i] / 2);
9875 // When zeroing, we need to spread the zeroing across both lanes to widen.
9876 if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9877 if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9878 (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9879 WidenedMask.push_back(SM_SentinelZero);
9885 // Finally check if the two mask values are adjacent and aligned with
9887 if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9888 WidenedMask.push_back(Mask[i] / 2);
9892 // Otherwise we can't safely widen the elements used in this shuffle.
9895 assert(WidenedMask.size() == Mask.size() / 2 &&
9896 "Incorrect size of mask after widening the elements!");
9901 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9903 /// This routine just extracts two subvectors, shuffles them independently, and
9904 /// then concatenates them back together. This should work effectively with all
9905 /// AVX vector shuffle types.
9906 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9907 SDValue V2, ArrayRef<int> Mask,
9908 SelectionDAG &DAG) {
9909 assert(VT.getSizeInBits() >= 256 &&
9910 "Only for 256-bit or wider vector shuffles!");
9911 assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9912 assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9914 ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9915 ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9917 int NumElements = VT.getVectorNumElements();
9918 int SplitNumElements = NumElements / 2;
9919 MVT ScalarVT = VT.getVectorElementType();
9920 MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9922 // Rather than splitting build-vectors, just build two narrower build
9923 // vectors. This helps shuffling with splats and zeros.
9924 auto SplitVector = [&](SDValue V) {
9925 while (V.getOpcode() == ISD::BITCAST)
9926 V = V->getOperand(0);
9928 MVT OrigVT = V.getSimpleValueType();
9929 int OrigNumElements = OrigVT.getVectorNumElements();
9930 int OrigSplitNumElements = OrigNumElements / 2;
9931 MVT OrigScalarVT = OrigVT.getVectorElementType();
9932 MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9936 auto *BV = dyn_cast<BuildVectorSDNode>(V);
9938 LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9939 DAG.getIntPtrConstant(0, DL));
9940 HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9941 DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9944 SmallVector<SDValue, 16> LoOps, HiOps;
9945 for (int i = 0; i < OrigSplitNumElements; ++i) {
9946 LoOps.push_back(BV->getOperand(i));
9947 HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9949 LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9950 HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9952 return std::make_pair(DAG.getBitcast(SplitVT, LoV),
9953 DAG.getBitcast(SplitVT, HiV));
9956 SDValue LoV1, HiV1, LoV2, HiV2;
9957 std::tie(LoV1, HiV1) = SplitVector(V1);
9958 std::tie(LoV2, HiV2) = SplitVector(V2);
9960 // Now create two 4-way blends of these half-width vectors.
9961 auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9962 bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9963 SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9964 for (int i = 0; i < SplitNumElements; ++i) {
9965 int M = HalfMask[i];
9966 if (M >= NumElements) {
9967 if (M >= NumElements + SplitNumElements)
9971 V2BlendMask.push_back(M - NumElements);
9972 V1BlendMask.push_back(-1);
9973 BlendMask.push_back(SplitNumElements + i);
9974 } else if (M >= 0) {
9975 if (M >= SplitNumElements)
9979 V2BlendMask.push_back(-1);
9980 V1BlendMask.push_back(M);
9981 BlendMask.push_back(i);
9983 V2BlendMask.push_back(-1);
9984 V1BlendMask.push_back(-1);
9985 BlendMask.push_back(-1);
9989 // Because the lowering happens after all combining takes place, we need to
9990 // manually combine these blend masks as much as possible so that we create
9991 // a minimal number of high-level vector shuffle nodes.
9993 // First try just blending the halves of V1 or V2.
9994 if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9995 return DAG.getUNDEF(SplitVT);
9996 if (!UseLoV2 && !UseHiV2)
9997 return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9998 if (!UseLoV1 && !UseHiV1)
9999 return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
10001 SDValue V1Blend, V2Blend;
10002 if (UseLoV1 && UseHiV1) {
10004 DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
10006 // We only use half of V1 so map the usage down into the final blend mask.
10007 V1Blend = UseLoV1 ? LoV1 : HiV1;
10008 for (int i = 0; i < SplitNumElements; ++i)
10009 if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
10010 BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
10012 if (UseLoV2 && UseHiV2) {
10014 DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
10016 // We only use half of V2 so map the usage down into the final blend mask.
10017 V2Blend = UseLoV2 ? LoV2 : HiV2;
10018 for (int i = 0; i < SplitNumElements; ++i)
10019 if (BlendMask[i] >= SplitNumElements)
10020 BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
10022 return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
10024 SDValue Lo = HalfBlend(LoMask);
10025 SDValue Hi = HalfBlend(HiMask);
10026 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
10029 /// \brief Either split a vector in halves or decompose the shuffles and the
10032 /// This is provided as a good fallback for many lowerings of non-single-input
10033 /// shuffles with more than one 128-bit lane. In those cases, we want to select
10034 /// between splitting the shuffle into 128-bit components and stitching those
10035 /// back together vs. extracting the single-input shuffles and blending those
10037 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
10038 SDValue V2, ArrayRef<int> Mask,
10039 SelectionDAG &DAG) {
10040 assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
10041 "lower single-input shuffles as it "
10042 "could then recurse on itself.");
10043 int Size = Mask.size();
10045 // If this can be modeled as a broadcast of two elements followed by a blend,
10046 // prefer that lowering. This is especially important because broadcasts can
10047 // often fold with memory operands.
10048 auto DoBothBroadcast = [&] {
10049 int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
10052 if (V2BroadcastIdx == -1)
10053 V2BroadcastIdx = M - Size;
10054 else if (M - Size != V2BroadcastIdx)
10056 } else if (M >= 0) {
10057 if (V1BroadcastIdx == -1)
10058 V1BroadcastIdx = M;
10059 else if (M != V1BroadcastIdx)
10064 if (DoBothBroadcast())
10065 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
10068 // If the inputs all stem from a single 128-bit lane of each input, then we
10069 // split them rather than blending because the split will decompose to
10070 // unusually few instructions.
10071 int LaneCount = VT.getSizeInBits() / 128;
10072 int LaneSize = Size / LaneCount;
10073 SmallBitVector LaneInputs[2];
10074 LaneInputs[0].resize(LaneCount, false);
10075 LaneInputs[1].resize(LaneCount, false);
10076 for (int i = 0; i < Size; ++i)
10078 LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
10079 if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
10080 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10082 // Otherwise, just fall back to decomposed shuffles and a blend. This requires
10083 // that the decomposed single-input shuffles don't end up here.
10084 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
10087 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
10088 /// a permutation and blend of those lanes.
10090 /// This essentially blends the out-of-lane inputs to each lane into the lane
10091 /// from a permuted copy of the vector. This lowering strategy results in four
10092 /// instructions in the worst case for a single-input cross lane shuffle which
10093 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
10094 /// of. Special cases for each particular shuffle pattern should be handled
10095 /// prior to trying this lowering.
10096 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
10097 SDValue V1, SDValue V2,
10098 ArrayRef<int> Mask,
10099 SelectionDAG &DAG) {
10100 // FIXME: This should probably be generalized for 512-bit vectors as well.
10101 assert(VT.is256BitVector() && "Only for 256-bit vector shuffles!");
10102 int LaneSize = Mask.size() / 2;
10104 // If there are only inputs from one 128-bit lane, splitting will in fact be
10105 // less expensive. The flags track whether the given lane contains an element
10106 // that crosses to another lane.
10107 bool LaneCrossing[2] = {false, false};
10108 for (int i = 0, Size = Mask.size(); i < Size; ++i)
10109 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
10110 LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
10111 if (!LaneCrossing[0] || !LaneCrossing[1])
10112 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10114 if (isSingleInputShuffleMask(Mask)) {
10115 SmallVector<int, 32> FlippedBlendMask;
10116 for (int i = 0, Size = Mask.size(); i < Size; ++i)
10117 FlippedBlendMask.push_back(
10118 Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
10120 : Mask[i] % LaneSize +
10121 (i / LaneSize) * LaneSize + Size));
10123 // Flip the vector, and blend the results which should now be in-lane. The
10124 // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
10125 // 5 for the high source. The value 3 selects the high half of source 2 and
10126 // the value 2 selects the low half of source 2. We only use source 2 to
10127 // allow folding it into a memory operand.
10128 unsigned PERMMask = 3 | 2 << 4;
10129 SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
10130 V1, DAG.getConstant(PERMMask, DL, MVT::i8));
10131 return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
10134 // This now reduces to two single-input shuffles of V1 and V2 which at worst
10135 // will be handled by the above logic and a blend of the results, much like
10136 // other patterns in AVX.
10137 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
10140 /// \brief Handle lowering 2-lane 128-bit shuffles.
10141 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
10142 SDValue V2, ArrayRef<int> Mask,
10143 const X86Subtarget *Subtarget,
10144 SelectionDAG &DAG) {
10145 // TODO: If minimizing size and one of the inputs is a zero vector and the
10146 // the zero vector has only one use, we could use a VPERM2X128 to save the
10147 // instruction bytes needed to explicitly generate the zero vector.
10149 // Blends are faster and handle all the non-lane-crossing cases.
10150 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
10154 bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
10155 bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
10157 // If either input operand is a zero vector, use VPERM2X128 because its mask
10158 // allows us to replace the zero input with an implicit zero.
10159 if (!IsV1Zero && !IsV2Zero) {
10160 // Check for patterns which can be matched with a single insert of a 128-bit
10162 bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
10163 if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
10164 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
10165 VT.getVectorNumElements() / 2);
10166 SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
10167 DAG.getIntPtrConstant(0, DL));
10168 SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
10169 OnlyUsesV1 ? V1 : V2,
10170 DAG.getIntPtrConstant(0, DL));
10171 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
10175 // Otherwise form a 128-bit permutation. After accounting for undefs,
10176 // convert the 64-bit shuffle mask selection values into 128-bit
10177 // selection bits by dividing the indexes by 2 and shifting into positions
10178 // defined by a vperm2*128 instruction's immediate control byte.
10180 // The immediate permute control byte looks like this:
10181 // [1:0] - select 128 bits from sources for low half of destination
10183 // [3] - zero low half of destination
10184 // [5:4] - select 128 bits from sources for high half of destination
10186 // [7] - zero high half of destination
10188 int MaskLO = Mask[0];
10189 if (MaskLO == SM_SentinelUndef)
10190 MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
10192 int MaskHI = Mask[2];
10193 if (MaskHI == SM_SentinelUndef)
10194 MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
10196 unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
10198 // If either input is a zero vector, replace it with an undef input.
10199 // Shuffle mask values < 4 are selecting elements of V1.
10200 // Shuffle mask values >= 4 are selecting elements of V2.
10201 // Adjust each half of the permute mask by clearing the half that was
10202 // selecting the zero vector and setting the zero mask bit.
10204 V1 = DAG.getUNDEF(VT);
10206 PermMask = (PermMask & 0xf0) | 0x08;
10208 PermMask = (PermMask & 0x0f) | 0x80;
10211 V2 = DAG.getUNDEF(VT);
10213 PermMask = (PermMask & 0xf0) | 0x08;
10215 PermMask = (PermMask & 0x0f) | 0x80;
10218 return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
10219 DAG.getConstant(PermMask, DL, MVT::i8));
10222 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
10223 /// shuffling each lane.
10225 /// This will only succeed when the result of fixing the 128-bit lanes results
10226 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
10227 /// each 128-bit lanes. This handles many cases where we can quickly blend away
10228 /// the lane crosses early and then use simpler shuffles within each lane.
10230 /// FIXME: It might be worthwhile at some point to support this without
10231 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
10232 /// in x86 only floating point has interesting non-repeating shuffles, and even
10233 /// those are still *marginally* more expensive.
10234 static SDValue lowerVectorShuffleByMerging128BitLanes(
10235 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
10236 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
10237 assert(!isSingleInputShuffleMask(Mask) &&
10238 "This is only useful with multiple inputs.");
10240 int Size = Mask.size();
10241 int LaneSize = 128 / VT.getScalarSizeInBits();
10242 int NumLanes = Size / LaneSize;
10243 assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
10245 // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
10246 // check whether the in-128-bit lane shuffles share a repeating pattern.
10247 SmallVector<int, 4> Lanes;
10248 Lanes.resize(NumLanes, -1);
10249 SmallVector<int, 4> InLaneMask;
10250 InLaneMask.resize(LaneSize, -1);
10251 for (int i = 0; i < Size; ++i) {
10255 int j = i / LaneSize;
10257 if (Lanes[j] < 0) {
10258 // First entry we've seen for this lane.
10259 Lanes[j] = Mask[i] / LaneSize;
10260 } else if (Lanes[j] != Mask[i] / LaneSize) {
10261 // This doesn't match the lane selected previously!
10265 // Check that within each lane we have a consistent shuffle mask.
10266 int k = i % LaneSize;
10267 if (InLaneMask[k] < 0) {
10268 InLaneMask[k] = Mask[i] % LaneSize;
10269 } else if (InLaneMask[k] != Mask[i] % LaneSize) {
10270 // This doesn't fit a repeating in-lane mask.
10275 // First shuffle the lanes into place.
10276 MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
10277 VT.getSizeInBits() / 64);
10278 SmallVector<int, 8> LaneMask;
10279 LaneMask.resize(NumLanes * 2, -1);
10280 for (int i = 0; i < NumLanes; ++i)
10281 if (Lanes[i] >= 0) {
10282 LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
10283 LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
10286 V1 = DAG.getBitcast(LaneVT, V1);
10287 V2 = DAG.getBitcast(LaneVT, V2);
10288 SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
10290 // Cast it back to the type we actually want.
10291 LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
10293 // Now do a simple shuffle that isn't lane crossing.
10294 SmallVector<int, 8> NewMask;
10295 NewMask.resize(Size, -1);
10296 for (int i = 0; i < Size; ++i)
10298 NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
10299 assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
10300 "Must not introduce lane crosses at this point!");
10302 return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
10305 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
10308 /// This returns true if the elements from a particular input are already in the
10309 /// slot required by the given mask and require no permutation.
10310 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
10311 assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
10312 int Size = Mask.size();
10313 for (int i = 0; i < Size; ++i)
10314 if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
10320 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
10321 ArrayRef<int> Mask, SDValue V1,
10322 SDValue V2, SelectionDAG &DAG) {
10324 // Mask for V8F64: 0/1, 8/9, 2/3, 10/11, 4/5, ..
10325 // Mask for V4F64; 0/1, 4/5, 2/3, 6/7..
10326 assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
10327 int NumElts = VT.getVectorNumElements();
10328 bool ShufpdMask = true;
10329 bool CommutableMask = true;
10330 unsigned Immediate = 0;
10331 for (int i = 0; i < NumElts; ++i) {
10334 int Val = (i & 6) + NumElts * (i & 1);
10335 int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
10336 if (Mask[i] < Val || Mask[i] > Val + 1)
10337 ShufpdMask = false;
10338 if (Mask[i] < CommutVal || Mask[i] > CommutVal + 1)
10339 CommutableMask = false;
10340 Immediate |= (Mask[i] % 2) << i;
10343 return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
10344 DAG.getConstant(Immediate, DL, MVT::i8));
10345 if (CommutableMask)
10346 return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
10347 DAG.getConstant(Immediate, DL, MVT::i8));
10351 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
10353 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
10354 /// isn't available.
10355 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10356 const X86Subtarget *Subtarget,
10357 SelectionDAG &DAG) {
10359 assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10360 assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
10361 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10362 ArrayRef<int> Mask = SVOp->getMask();
10363 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10365 SmallVector<int, 4> WidenedMask;
10366 if (canWidenShuffleElements(Mask, WidenedMask))
10367 return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
10370 if (isSingleInputShuffleMask(Mask)) {
10371 // Check for being able to broadcast a single element.
10372 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
10373 Mask, Subtarget, DAG))
10376 // Use low duplicate instructions for masks that match their pattern.
10377 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
10378 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
10380 if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
10381 // Non-half-crossing single input shuffles can be lowerid with an
10382 // interleaved permutation.
10383 unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
10384 ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
10385 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
10386 DAG.getConstant(VPERMILPMask, DL, MVT::i8));
10389 // With AVX2 we have direct support for this permutation.
10390 if (Subtarget->hasAVX2())
10391 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
10392 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10394 // Otherwise, fall back.
10395 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
10399 // Use dedicated unpack instructions for masks that match their pattern.
10401 lowerVectorShuffleWithUNPCK(DL, MVT::v4f64, Mask, V1, V2, DAG))
10404 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
10408 // Check if the blend happens to exactly fit that of SHUFPD.
10410 lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
10413 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10414 // shuffle. However, if we have AVX2 and either inputs are already in place,
10415 // we will be able to shuffle even across lanes the other input in a single
10416 // instruction so skip this pattern.
10417 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10418 isShuffleMaskInputInPlace(1, Mask))))
10419 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10420 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
10423 // If we have AVX2 then we always want to lower with a blend because an v4 we
10424 // can fully permute the elements.
10425 if (Subtarget->hasAVX2())
10426 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
10429 // Otherwise fall back on generic lowering.
10430 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
10433 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
10435 /// This routine is only called when we have AVX2 and thus a reasonable
10436 /// instruction set for v4i64 shuffling..
10437 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10438 const X86Subtarget *Subtarget,
10439 SelectionDAG &DAG) {
10441 assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10442 assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
10443 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10444 ArrayRef<int> Mask = SVOp->getMask();
10445 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
10446 assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
10448 SmallVector<int, 4> WidenedMask;
10449 if (canWidenShuffleElements(Mask, WidenedMask))
10450 return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
10453 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
10457 // Check for being able to broadcast a single element.
10458 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
10459 Mask, Subtarget, DAG))
10462 // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
10463 // use lower latency instructions that will operate on both 128-bit lanes.
10464 SmallVector<int, 2> RepeatedMask;
10465 if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
10466 if (isSingleInputShuffleMask(Mask)) {
10467 int PSHUFDMask[] = {-1, -1, -1, -1};
10468 for (int i = 0; i < 2; ++i)
10469 if (RepeatedMask[i] >= 0) {
10470 PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
10471 PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
10473 return DAG.getBitcast(
10475 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
10476 DAG.getBitcast(MVT::v8i32, V1),
10477 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
10481 // AVX2 provides a direct instruction for permuting a single input across
10483 if (isSingleInputShuffleMask(Mask))
10484 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
10485 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
10487 // Try to use shift instructions.
10488 if (SDValue Shift =
10489 lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
10492 // Use dedicated unpack instructions for masks that match their pattern.
10494 lowerVectorShuffleWithUNPCK(DL, MVT::v4i64, Mask, V1, V2, DAG))
10497 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10498 // shuffle. However, if we have AVX2 and either inputs are already in place,
10499 // we will be able to shuffle even across lanes the other input in a single
10500 // instruction so skip this pattern.
10501 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
10502 isShuffleMaskInputInPlace(1, Mask))))
10503 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10504 DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
10507 // Otherwise fall back on generic blend lowering.
10508 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
10512 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
10514 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
10515 /// isn't available.
10516 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10517 const X86Subtarget *Subtarget,
10518 SelectionDAG &DAG) {
10520 assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10521 assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
10522 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10523 ArrayRef<int> Mask = SVOp->getMask();
10524 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10526 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
10530 // Check for being able to broadcast a single element.
10531 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
10532 Mask, Subtarget, DAG))
10535 // If the shuffle mask is repeated in each 128-bit lane, we have many more
10536 // options to efficiently lower the shuffle.
10537 SmallVector<int, 4> RepeatedMask;
10538 if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
10539 assert(RepeatedMask.size() == 4 &&
10540 "Repeated masks must be half the mask width!");
10542 // Use even/odd duplicate instructions for masks that match their pattern.
10543 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
10544 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
10545 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
10546 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
10548 if (isSingleInputShuffleMask(Mask))
10549 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
10550 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10552 // Use dedicated unpack instructions for masks that match their pattern.
10554 lowerVectorShuffleWithUNPCK(DL, MVT::v8f32, Mask, V1, V2, DAG))
10557 // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10558 // have already handled any direct blends. We also need to squash the
10559 // repeated mask into a simulated v4f32 mask.
10560 for (int i = 0; i < 4; ++i)
10561 if (RepeatedMask[i] >= 8)
10562 RepeatedMask[i] -= 4;
10563 return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10566 // If we have a single input shuffle with different shuffle patterns in the
10567 // two 128-bit lanes use the variable mask to VPERMILPS.
10568 if (isSingleInputShuffleMask(Mask)) {
10569 SDValue VPermMask[8];
10570 for (int i = 0; i < 8; ++i)
10571 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10572 : DAG.getConstant(Mask[i], DL, MVT::i32);
10573 if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10574 return DAG.getNode(
10575 X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10576 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10578 if (Subtarget->hasAVX2())
10579 return DAG.getNode(
10580 X86ISD::VPERMV, DL, MVT::v8f32,
10581 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10583 // Otherwise, fall back.
10584 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10588 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10590 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10591 DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10594 // If we have AVX2 then we always want to lower with a blend because at v8 we
10595 // can fully permute the elements.
10596 if (Subtarget->hasAVX2())
10597 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10600 // Otherwise fall back on generic lowering.
10601 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10604 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10606 /// This routine is only called when we have AVX2 and thus a reasonable
10607 /// instruction set for v8i32 shuffling..
10608 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10609 const X86Subtarget *Subtarget,
10610 SelectionDAG &DAG) {
10612 assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10613 assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10614 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10615 ArrayRef<int> Mask = SVOp->getMask();
10616 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10617 assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10619 // Whenever we can lower this as a zext, that instruction is strictly faster
10620 // than any alternative. It also allows us to fold memory operands into the
10621 // shuffle in many cases.
10622 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10623 Mask, Subtarget, DAG))
10626 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10630 // Check for being able to broadcast a single element.
10631 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10632 Mask, Subtarget, DAG))
10635 // If the shuffle mask is repeated in each 128-bit lane we can use more
10636 // efficient instructions that mirror the shuffles across the two 128-bit
10638 SmallVector<int, 4> RepeatedMask;
10639 if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10640 assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10641 if (isSingleInputShuffleMask(Mask))
10642 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10643 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10645 // Use dedicated unpack instructions for masks that match their pattern.
10647 lowerVectorShuffleWithUNPCK(DL, MVT::v8i32, Mask, V1, V2, DAG))
10651 // Try to use shift instructions.
10652 if (SDValue Shift =
10653 lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10656 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10657 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10660 // If the shuffle patterns aren't repeated but it is a single input, directly
10661 // generate a cross-lane VPERMD instruction.
10662 if (isSingleInputShuffleMask(Mask)) {
10663 SDValue VPermMask[8];
10664 for (int i = 0; i < 8; ++i)
10665 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10666 : DAG.getConstant(Mask[i], DL, MVT::i32);
10667 return DAG.getNode(
10668 X86ISD::VPERMV, DL, MVT::v8i32,
10669 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10672 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10674 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10675 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10678 // Otherwise fall back on generic blend lowering.
10679 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10683 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10685 /// This routine is only called when we have AVX2 and thus a reasonable
10686 /// instruction set for v16i16 shuffling..
10687 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10688 const X86Subtarget *Subtarget,
10689 SelectionDAG &DAG) {
10691 assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10692 assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10693 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10694 ArrayRef<int> Mask = SVOp->getMask();
10695 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10696 assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10698 // Whenever we can lower this as a zext, that instruction is strictly faster
10699 // than any alternative. It also allows us to fold memory operands into the
10700 // shuffle in many cases.
10701 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10702 Mask, Subtarget, DAG))
10705 // Check for being able to broadcast a single element.
10706 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10707 Mask, Subtarget, DAG))
10710 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10714 // Use dedicated unpack instructions for masks that match their pattern.
10716 lowerVectorShuffleWithUNPCK(DL, MVT::v16i16, Mask, V1, V2, DAG))
10719 // Try to use shift instructions.
10720 if (SDValue Shift =
10721 lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10724 // Try to use byte rotation instructions.
10725 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10726 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10729 if (isSingleInputShuffleMask(Mask)) {
10730 // There are no generalized cross-lane shuffle operations available on i16
10732 if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10733 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10736 SmallVector<int, 8> RepeatedMask;
10737 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10738 // As this is a single-input shuffle, the repeated mask should be
10739 // a strictly valid v8i16 mask that we can pass through to the v8i16
10740 // lowering to handle even the v16 case.
10741 return lowerV8I16GeneralSingleInputVectorShuffle(
10742 DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10745 SDValue PSHUFBMask[32];
10746 for (int i = 0; i < 16; ++i) {
10747 if (Mask[i] == -1) {
10748 PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10752 int M = i < 8 ? Mask[i] : Mask[i] - 8;
10753 assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10754 PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10755 PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10757 return DAG.getBitcast(MVT::v16i16,
10758 DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10759 DAG.getBitcast(MVT::v32i8, V1),
10760 DAG.getNode(ISD::BUILD_VECTOR, DL,
10761 MVT::v32i8, PSHUFBMask)));
10764 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10766 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10767 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10770 // Otherwise fall back on generic lowering.
10771 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10774 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10776 /// This routine is only called when we have AVX2 and thus a reasonable
10777 /// instruction set for v32i8 shuffling..
10778 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10779 const X86Subtarget *Subtarget,
10780 SelectionDAG &DAG) {
10782 assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10783 assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10784 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10785 ArrayRef<int> Mask = SVOp->getMask();
10786 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10787 assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10789 // Whenever we can lower this as a zext, that instruction is strictly faster
10790 // than any alternative. It also allows us to fold memory operands into the
10791 // shuffle in many cases.
10792 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10793 Mask, Subtarget, DAG))
10796 // Check for being able to broadcast a single element.
10797 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10798 Mask, Subtarget, DAG))
10801 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10805 // Use dedicated unpack instructions for masks that match their pattern.
10807 lowerVectorShuffleWithUNPCK(DL, MVT::v32i8, Mask, V1, V2, DAG))
10810 // Try to use shift instructions.
10811 if (SDValue Shift =
10812 lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10815 // Try to use byte rotation instructions.
10816 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10817 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10820 if (isSingleInputShuffleMask(Mask)) {
10821 // There are no generalized cross-lane shuffle operations available on i8
10823 if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10824 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10827 SDValue PSHUFBMask[32];
10828 for (int i = 0; i < 32; ++i)
10831 ? DAG.getUNDEF(MVT::i8)
10832 : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10835 return DAG.getNode(
10836 X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10837 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10840 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10842 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10843 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10846 // Otherwise fall back on generic lowering.
10847 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10850 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10852 /// This routine either breaks down the specific type of a 256-bit x86 vector
10853 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10854 /// together based on the available instructions.
10855 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10856 MVT VT, const X86Subtarget *Subtarget,
10857 SelectionDAG &DAG) {
10859 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10860 ArrayRef<int> Mask = SVOp->getMask();
10862 // If we have a single input to the zero element, insert that into V1 if we
10863 // can do so cheaply.
10864 int NumElts = VT.getVectorNumElements();
10865 int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10866 return M >= NumElts;
10869 if (NumV2Elements == 1 && Mask[0] >= NumElts)
10870 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10871 DL, VT, V1, V2, Mask, Subtarget, DAG))
10874 // There is a really nice hard cut-over between AVX1 and AVX2 that means we
10875 // can check for those subtargets here and avoid much of the subtarget
10876 // querying in the per-vector-type lowering routines. With AVX1 we have
10877 // essentially *zero* ability to manipulate a 256-bit vector with integer
10878 // types. Since we'll use floating point types there eventually, just
10879 // immediately cast everything to a float and operate entirely in that domain.
10880 if (VT.isInteger() && !Subtarget->hasAVX2()) {
10881 int ElementBits = VT.getScalarSizeInBits();
10882 if (ElementBits < 32)
10883 // No floating point type available, decompose into 128-bit vectors.
10884 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10886 MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10887 VT.getVectorNumElements());
10888 V1 = DAG.getBitcast(FpVT, V1);
10889 V2 = DAG.getBitcast(FpVT, V2);
10890 return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10893 switch (VT.SimpleTy) {
10895 return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10897 return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10899 return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10901 return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10903 return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10905 return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10908 llvm_unreachable("Not a valid 256-bit x86 vector type!");
10912 /// \brief Try to lower a vector shuffle as a 128-bit shuffles.
10913 static SDValue lowerV4X128VectorShuffle(SDLoc DL, MVT VT,
10914 ArrayRef<int> Mask,
10915 SDValue V1, SDValue V2,
10916 SelectionDAG &DAG) {
10917 assert(VT.getScalarSizeInBits() == 64 &&
10918 "Unexpected element type size for 128bit shuffle.");
10920 // To handle 256 bit vector requires VLX and most probably
10921 // function lowerV2X128VectorShuffle() is better solution.
10922 assert(VT.is512BitVector() && "Unexpected vector size for 128bit shuffle.");
10924 SmallVector<int, 4> WidenedMask;
10925 if (!canWidenShuffleElements(Mask, WidenedMask))
10928 // Form a 128-bit permutation.
10929 // Convert the 64-bit shuffle mask selection values into 128-bit selection
10930 // bits defined by a vshuf64x2 instruction's immediate control byte.
10931 unsigned PermMask = 0, Imm = 0;
10932 unsigned ControlBitsNum = WidenedMask.size() / 2;
10934 for (int i = 0, Size = WidenedMask.size(); i < Size; ++i) {
10935 if (WidenedMask[i] == SM_SentinelZero)
10938 // Use first element in place of undef mask.
10939 Imm = (WidenedMask[i] == SM_SentinelUndef) ? 0 : WidenedMask[i];
10940 PermMask |= (Imm % WidenedMask.size()) << (i * ControlBitsNum);
10943 return DAG.getNode(X86ISD::SHUF128, DL, VT, V1, V2,
10944 DAG.getConstant(PermMask, DL, MVT::i8));
10947 static SDValue lowerVectorShuffleWithPERMV(SDLoc DL, MVT VT,
10948 ArrayRef<int> Mask, SDValue V1,
10949 SDValue V2, SelectionDAG &DAG) {
10951 assert(VT.getScalarSizeInBits() >= 16 && "Unexpected data type for PERMV");
10953 MVT MaskEltVT = MVT::getIntegerVT(VT.getScalarSizeInBits());
10954 MVT MaskVecVT = MVT::getVectorVT(MaskEltVT, VT.getVectorNumElements());
10956 SDValue MaskNode = getConstVector(Mask, MaskVecVT, DAG, DL, true);
10957 if (isSingleInputShuffleMask(Mask))
10958 return DAG.getNode(X86ISD::VPERMV, DL, VT, MaskNode, V1);
10960 return DAG.getNode(X86ISD::VPERMV3, DL, VT, V1, MaskNode, V2);
10963 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10964 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10965 const X86Subtarget *Subtarget,
10966 SelectionDAG &DAG) {
10968 assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10969 assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10970 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10971 ArrayRef<int> Mask = SVOp->getMask();
10972 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10974 if (SDValue Shuf128 =
10975 lowerV4X128VectorShuffle(DL, MVT::v8f64, Mask, V1, V2, DAG))
10978 if (SDValue Unpck =
10979 lowerVectorShuffleWithUNPCK(DL, MVT::v8f64, Mask, V1, V2, DAG))
10982 return lowerVectorShuffleWithPERMV(DL, MVT::v8f64, Mask, V1, V2, DAG);
10985 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10986 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10987 const X86Subtarget *Subtarget,
10988 SelectionDAG &DAG) {
10990 assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10991 assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10992 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10993 ArrayRef<int> Mask = SVOp->getMask();
10994 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10996 if (SDValue Unpck =
10997 lowerVectorShuffleWithUNPCK(DL, MVT::v16f32, Mask, V1, V2, DAG))
11000 return lowerVectorShuffleWithPERMV(DL, MVT::v16f32, Mask, V1, V2, DAG);
11003 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
11004 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11005 const X86Subtarget *Subtarget,
11006 SelectionDAG &DAG) {
11008 assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
11009 assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
11010 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11011 ArrayRef<int> Mask = SVOp->getMask();
11012 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
11014 if (SDValue Shuf128 =
11015 lowerV4X128VectorShuffle(DL, MVT::v8i64, Mask, V1, V2, DAG))
11018 if (SDValue Unpck =
11019 lowerVectorShuffleWithUNPCK(DL, MVT::v8i64, Mask, V1, V2, DAG))
11022 return lowerVectorShuffleWithPERMV(DL, MVT::v8i64, Mask, V1, V2, DAG);
11025 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
11026 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11027 const X86Subtarget *Subtarget,
11028 SelectionDAG &DAG) {
11030 assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
11031 assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
11032 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11033 ArrayRef<int> Mask = SVOp->getMask();
11034 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
11036 if (SDValue Unpck =
11037 lowerVectorShuffleWithUNPCK(DL, MVT::v16i32, Mask, V1, V2, DAG))
11040 return lowerVectorShuffleWithPERMV(DL, MVT::v16i32, Mask, V1, V2, DAG);
11043 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
11044 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11045 const X86Subtarget *Subtarget,
11046 SelectionDAG &DAG) {
11048 assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
11049 assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
11050 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11051 ArrayRef<int> Mask = SVOp->getMask();
11052 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
11053 assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
11055 return lowerVectorShuffleWithPERMV(DL, MVT::v32i16, Mask, V1, V2, DAG);
11058 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
11059 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11060 const X86Subtarget *Subtarget,
11061 SelectionDAG &DAG) {
11063 assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
11064 assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
11065 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11066 ArrayRef<int> Mask = SVOp->getMask();
11067 assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
11068 assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
11070 // FIXME: Implement direct support for this type!
11071 return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
11074 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
11076 /// This routine either breaks down the specific type of a 512-bit x86 vector
11077 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
11078 /// together based on the available instructions.
11079 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11080 MVT VT, const X86Subtarget *Subtarget,
11081 SelectionDAG &DAG) {
11083 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11084 ArrayRef<int> Mask = SVOp->getMask();
11085 assert(Subtarget->hasAVX512() &&
11086 "Cannot lower 512-bit vectors w/ basic ISA!");
11088 // Check for being able to broadcast a single element.
11089 if (SDValue Broadcast =
11090 lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
11093 // Dispatch to each element type for lowering. If we don't have supprot for
11094 // specific element type shuffles at 512 bits, immediately split them and
11095 // lower them. Each lowering routine of a given type is allowed to assume that
11096 // the requisite ISA extensions for that element type are available.
11097 switch (VT.SimpleTy) {
11099 return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11101 return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11103 return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
11105 return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
11107 if (Subtarget->hasBWI())
11108 return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
11111 if (Subtarget->hasBWI())
11112 return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
11116 llvm_unreachable("Not a valid 512-bit x86 vector type!");
11119 // Otherwise fall back on splitting.
11120 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
11123 // Lower vXi1 vector shuffles.
11124 // There is no a dedicated instruction on AVX-512 that shuffles the masks.
11125 // The only way to shuffle bits is to sign-extend the mask vector to SIMD
11126 // vector, shuffle and then truncate it back.
11127 static SDValue lower1BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
11128 MVT VT, const X86Subtarget *Subtarget,
11129 SelectionDAG &DAG) {
11131 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11132 ArrayRef<int> Mask = SVOp->getMask();
11133 assert(Subtarget->hasAVX512() &&
11134 "Cannot lower 512-bit vectors w/o basic ISA!");
11136 switch (VT.SimpleTy) {
11138 llvm_unreachable("Expected a vector of i1 elements");
11140 ExtVT = MVT::v2i64;
11143 ExtVT = MVT::v4i32;
11146 ExtVT = MVT::v8i64; // Take 512-bit type, more shuffles on KNL
11149 ExtVT = MVT::v16i32;
11152 ExtVT = MVT::v32i16;
11155 ExtVT = MVT::v64i8;
11159 if (ISD::isBuildVectorAllZeros(V1.getNode()))
11160 V1 = getZeroVector(ExtVT, Subtarget, DAG, DL);
11161 else if (ISD::isBuildVectorAllOnes(V1.getNode()))
11162 V1 = getOnesVector(ExtVT, Subtarget, DAG, DL);
11164 V1 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V1);
11167 V2 = DAG.getUNDEF(ExtVT);
11168 else if (ISD::isBuildVectorAllZeros(V2.getNode()))
11169 V2 = getZeroVector(ExtVT, Subtarget, DAG, DL);
11170 else if (ISD::isBuildVectorAllOnes(V2.getNode()))
11171 V2 = getOnesVector(ExtVT, Subtarget, DAG, DL);
11173 V2 = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, V2);
11174 return DAG.getNode(ISD::TRUNCATE, DL, VT,
11175 DAG.getVectorShuffle(ExtVT, DL, V1, V2, Mask));
11177 /// \brief Top-level lowering for x86 vector shuffles.
11179 /// This handles decomposition, canonicalization, and lowering of all x86
11180 /// vector shuffles. Most of the specific lowering strategies are encapsulated
11181 /// above in helper routines. The canonicalization attempts to widen shuffles
11182 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
11183 /// s.t. only one of the two inputs needs to be tested, etc.
11184 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
11185 SelectionDAG &DAG) {
11186 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11187 ArrayRef<int> Mask = SVOp->getMask();
11188 SDValue V1 = Op.getOperand(0);
11189 SDValue V2 = Op.getOperand(1);
11190 MVT VT = Op.getSimpleValueType();
11191 int NumElements = VT.getVectorNumElements();
11193 bool Is1BitVector = (VT.getVectorElementType() == MVT::i1);
11195 assert((VT.getSizeInBits() != 64 || Is1BitVector) &&
11196 "Can't lower MMX shuffles");
11198 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
11199 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
11200 if (V1IsUndef && V2IsUndef)
11201 return DAG.getUNDEF(VT);
11203 // When we create a shuffle node we put the UNDEF node to second operand,
11204 // but in some cases the first operand may be transformed to UNDEF.
11205 // In this case we should just commute the node.
11207 return DAG.getCommutedVectorShuffle(*SVOp);
11209 // Check for non-undef masks pointing at an undef vector and make the masks
11210 // undef as well. This makes it easier to match the shuffle based solely on
11214 if (M >= NumElements) {
11215 SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
11216 for (int &M : NewMask)
11217 if (M >= NumElements)
11219 return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
11222 // We actually see shuffles that are entirely re-arrangements of a set of
11223 // zero inputs. This mostly happens while decomposing complex shuffles into
11224 // simple ones. Directly lower these as a buildvector of zeros.
11225 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
11226 if (Zeroable.all())
11227 return getZeroVector(VT, Subtarget, DAG, dl);
11229 // Try to collapse shuffles into using a vector type with fewer elements but
11230 // wider element types. We cap this to not form integers or floating point
11231 // elements wider than 64 bits, but it might be interesting to form i128
11232 // integers to handle flipping the low and high halves of AVX 256-bit vectors.
11233 SmallVector<int, 16> WidenedMask;
11234 if (VT.getScalarSizeInBits() < 64 && !Is1BitVector &&
11235 canWidenShuffleElements(Mask, WidenedMask)) {
11236 MVT NewEltVT = VT.isFloatingPoint()
11237 ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
11238 : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
11239 MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
11240 // Make sure that the new vector type is legal. For example, v2f64 isn't
11242 if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
11243 V1 = DAG.getBitcast(NewVT, V1);
11244 V2 = DAG.getBitcast(NewVT, V2);
11245 return DAG.getBitcast(
11246 VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
11250 int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
11251 for (int M : SVOp->getMask())
11253 ++NumUndefElements;
11254 else if (M < NumElements)
11259 // Commute the shuffle as needed such that more elements come from V1 than
11260 // V2. This allows us to match the shuffle pattern strictly on how many
11261 // elements come from V1 without handling the symmetric cases.
11262 if (NumV2Elements > NumV1Elements)
11263 return DAG.getCommutedVectorShuffle(*SVOp);
11265 // When the number of V1 and V2 elements are the same, try to minimize the
11266 // number of uses of V2 in the low half of the vector. When that is tied,
11267 // ensure that the sum of indices for V1 is equal to or lower than the sum
11268 // indices for V2. When those are equal, try to ensure that the number of odd
11269 // indices for V1 is lower than the number of odd indices for V2.
11270 if (NumV1Elements == NumV2Elements) {
11271 int LowV1Elements = 0, LowV2Elements = 0;
11272 for (int M : SVOp->getMask().slice(0, NumElements / 2))
11273 if (M >= NumElements)
11277 if (LowV2Elements > LowV1Elements) {
11278 return DAG.getCommutedVectorShuffle(*SVOp);
11279 } else if (LowV2Elements == LowV1Elements) {
11280 int SumV1Indices = 0, SumV2Indices = 0;
11281 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11282 if (SVOp->getMask()[i] >= NumElements)
11284 else if (SVOp->getMask()[i] >= 0)
11286 if (SumV2Indices < SumV1Indices) {
11287 return DAG.getCommutedVectorShuffle(*SVOp);
11288 } else if (SumV2Indices == SumV1Indices) {
11289 int NumV1OddIndices = 0, NumV2OddIndices = 0;
11290 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
11291 if (SVOp->getMask()[i] >= NumElements)
11292 NumV2OddIndices += i % 2;
11293 else if (SVOp->getMask()[i] >= 0)
11294 NumV1OddIndices += i % 2;
11295 if (NumV2OddIndices < NumV1OddIndices)
11296 return DAG.getCommutedVectorShuffle(*SVOp);
11301 // For each vector width, delegate to a specialized lowering routine.
11302 if (VT.is128BitVector())
11303 return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11305 if (VT.is256BitVector())
11306 return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11308 if (VT.is512BitVector())
11309 return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11312 return lower1BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
11313 llvm_unreachable("Unimplemented!");
11316 // This function assumes its argument is a BUILD_VECTOR of constants or
11317 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
11319 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
11320 unsigned &MaskValue) {
11322 unsigned NumElems = BuildVector->getNumOperands();
11324 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
11325 // We don't handle the >2 lanes case right now.
11326 unsigned NumLanes = (NumElems - 1) / 8 + 1;
11330 unsigned NumElemsInLane = NumElems / NumLanes;
11332 // Blend for v16i16 should be symmetric for the both lanes.
11333 for (unsigned i = 0; i < NumElemsInLane; ++i) {
11334 SDValue EltCond = BuildVector->getOperand(i);
11335 SDValue SndLaneEltCond =
11336 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
11338 int Lane1Cond = -1, Lane2Cond = -1;
11339 if (isa<ConstantSDNode>(EltCond))
11340 Lane1Cond = !isNullConstant(EltCond);
11341 if (isa<ConstantSDNode>(SndLaneEltCond))
11342 Lane2Cond = !isNullConstant(SndLaneEltCond);
11344 unsigned LaneMask = 0;
11345 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
11346 // Lane1Cond != 0, means we want the first argument.
11347 // Lane1Cond == 0, means we want the second argument.
11348 // The encoding of this argument is 0 for the first argument, 1
11349 // for the second. Therefore, invert the condition.
11350 LaneMask = !Lane1Cond << i;
11351 else if (Lane1Cond < 0)
11352 LaneMask = !Lane2Cond << i;
11356 MaskValue |= LaneMask;
11358 MaskValue |= LaneMask << NumElemsInLane;
11363 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
11364 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
11365 const X86Subtarget *Subtarget,
11366 SelectionDAG &DAG) {
11367 SDValue Cond = Op.getOperand(0);
11368 SDValue LHS = Op.getOperand(1);
11369 SDValue RHS = Op.getOperand(2);
11371 MVT VT = Op.getSimpleValueType();
11373 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
11375 auto *CondBV = cast<BuildVectorSDNode>(Cond);
11377 // Only non-legal VSELECTs reach this lowering, convert those into generic
11378 // shuffles and re-use the shuffle lowering path for blends.
11379 SmallVector<int, 32> Mask;
11380 for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
11381 SDValue CondElt = CondBV->getOperand(i);
11383 isa<ConstantSDNode>(CondElt) ? i + (isNullConstant(CondElt) ? Size : 0)
11386 return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
11389 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
11390 // A vselect where all conditions and data are constants can be optimized into
11391 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
11392 if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
11393 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
11394 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
11397 // Try to lower this to a blend-style vector shuffle. This can handle all
11398 // constant condition cases.
11399 if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
11402 // Variable blends are only legal from SSE4.1 onward.
11403 if (!Subtarget->hasSSE41())
11406 // Only some types will be legal on some subtargets. If we can emit a legal
11407 // VSELECT-matching blend, return Op, and but if we need to expand, return
11409 switch (Op.getSimpleValueType().SimpleTy) {
11411 // Most of the vector types have blends past SSE4.1.
11415 // The byte blends for AVX vectors were introduced only in AVX2.
11416 if (Subtarget->hasAVX2())
11423 // AVX-512 BWI and VLX features support VSELECT with i16 elements.
11424 if (Subtarget->hasBWI() && Subtarget->hasVLX())
11427 // FIXME: We should custom lower this by fixing the condition and using i8
11433 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
11434 MVT VT = Op.getSimpleValueType();
11437 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
11440 if (VT.getSizeInBits() == 8) {
11441 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
11442 Op.getOperand(0), Op.getOperand(1));
11443 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11444 DAG.getValueType(VT));
11445 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11448 if (VT.getSizeInBits() == 16) {
11449 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
11450 if (isNullConstant(Op.getOperand(1)))
11451 return DAG.getNode(
11452 ISD::TRUNCATE, dl, MVT::i16,
11453 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11454 DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11455 Op.getOperand(1)));
11456 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
11457 Op.getOperand(0), Op.getOperand(1));
11458 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11459 DAG.getValueType(VT));
11460 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11463 if (VT == MVT::f32) {
11464 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
11465 // the result back to FR32 register. It's only worth matching if the
11466 // result has a single use which is a store or a bitcast to i32. And in
11467 // the case of a store, it's not worth it if the index is a constant 0,
11468 // because a MOVSSmr can be used instead, which is smaller and faster.
11469 if (!Op.hasOneUse())
11471 SDNode *User = *Op.getNode()->use_begin();
11472 if ((User->getOpcode() != ISD::STORE ||
11473 isNullConstant(Op.getOperand(1))) &&
11474 (User->getOpcode() != ISD::BITCAST ||
11475 User->getValueType(0) != MVT::i32))
11477 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11478 DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
11480 return DAG.getBitcast(MVT::f32, Extract);
11483 if (VT == MVT::i32 || VT == MVT::i64) {
11484 // ExtractPS/pextrq works with constant index.
11485 if (isa<ConstantSDNode>(Op.getOperand(1)))
11491 /// Extract one bit from mask vector, like v16i1 or v8i1.
11492 /// AVX-512 feature.
11494 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
11495 SDValue Vec = Op.getOperand(0);
11497 MVT VecVT = Vec.getSimpleValueType();
11498 SDValue Idx = Op.getOperand(1);
11499 MVT EltVT = Op.getSimpleValueType();
11501 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
11502 assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
11503 "Unexpected vector type in ExtractBitFromMaskVector");
11505 // variable index can't be handled in mask registers,
11506 // extend vector to VR512
11507 if (!isa<ConstantSDNode>(Idx)) {
11508 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
11509 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
11510 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
11511 ExtVT.getVectorElementType(), Ext, Idx);
11512 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
11515 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11516 const TargetRegisterClass* rc = getRegClassFor(VecVT);
11517 if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
11518 rc = getRegClassFor(MVT::v16i1);
11519 unsigned MaxSift = rc->getSize()*8 - 1;
11520 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
11521 DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
11522 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
11523 DAG.getConstant(MaxSift, dl, MVT::i8));
11524 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
11525 DAG.getIntPtrConstant(0, dl));
11529 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
11530 SelectionDAG &DAG) const {
11532 SDValue Vec = Op.getOperand(0);
11533 MVT VecVT = Vec.getSimpleValueType();
11534 SDValue Idx = Op.getOperand(1);
11536 if (Op.getSimpleValueType() == MVT::i1)
11537 return ExtractBitFromMaskVector(Op, DAG);
11539 if (!isa<ConstantSDNode>(Idx)) {
11540 if (VecVT.is512BitVector() ||
11541 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
11542 VecVT.getVectorElementType().getSizeInBits() == 32)) {
11545 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
11546 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
11547 MaskEltVT.getSizeInBits());
11549 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
11550 auto PtrVT = getPointerTy(DAG.getDataLayout());
11551 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
11552 getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
11553 DAG.getConstant(0, dl, PtrVT));
11554 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
11555 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
11556 DAG.getConstant(0, dl, PtrVT));
11561 // If this is a 256-bit vector result, first extract the 128-bit vector and
11562 // then extract the element from the 128-bit vector.
11563 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
11565 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11566 // Get the 128-bit vector.
11567 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
11568 MVT EltVT = VecVT.getVectorElementType();
11570 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
11571 assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2");
11573 // Find IdxVal modulo ElemsPerChunk. Since ElemsPerChunk is a power of 2
11574 // this can be done with a mask.
11575 IdxVal &= ElemsPerChunk - 1;
11576 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
11577 DAG.getConstant(IdxVal, dl, MVT::i32));
11580 assert(VecVT.is128BitVector() && "Unexpected vector length");
11582 if (Subtarget->hasSSE41())
11583 if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
11586 MVT VT = Op.getSimpleValueType();
11587 // TODO: handle v16i8.
11588 if (VT.getSizeInBits() == 16) {
11589 SDValue Vec = Op.getOperand(0);
11590 if (isNullConstant(Op.getOperand(1)))
11591 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
11592 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11593 DAG.getBitcast(MVT::v4i32, Vec),
11594 Op.getOperand(1)));
11595 // Transform it so it match pextrw which produces a 32-bit result.
11596 MVT EltVT = MVT::i32;
11597 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
11598 Op.getOperand(0), Op.getOperand(1));
11599 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
11600 DAG.getValueType(VT));
11601 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11604 if (VT.getSizeInBits() == 32) {
11605 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11609 // SHUFPS the element to the lowest double word, then movss.
11610 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
11611 MVT VVT = Op.getOperand(0).getSimpleValueType();
11612 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11613 DAG.getUNDEF(VVT), Mask);
11614 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11615 DAG.getIntPtrConstant(0, dl));
11618 if (VT.getSizeInBits() == 64) {
11619 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
11620 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
11621 // to match extract_elt for f64.
11622 if (isNullConstant(Op.getOperand(1)))
11625 // UNPCKHPD the element to the lowest double word, then movsd.
11626 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
11627 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
11628 int Mask[2] = { 1, -1 };
11629 MVT VVT = Op.getOperand(0).getSimpleValueType();
11630 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11631 DAG.getUNDEF(VVT), Mask);
11632 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11633 DAG.getIntPtrConstant(0, dl));
11639 /// Insert one bit to mask vector, like v16i1 or v8i1.
11640 /// AVX-512 feature.
11642 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11644 SDValue Vec = Op.getOperand(0);
11645 SDValue Elt = Op.getOperand(1);
11646 SDValue Idx = Op.getOperand(2);
11647 MVT VecVT = Vec.getSimpleValueType();
11649 if (!isa<ConstantSDNode>(Idx)) {
11650 // Non constant index. Extend source and destination,
11651 // insert element and then truncate the result.
11652 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
11653 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
11654 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11655 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11656 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11657 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11660 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11661 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11663 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11664 DAG.getConstant(IdxVal, dl, MVT::i8));
11665 if (Vec.getOpcode() == ISD::UNDEF)
11667 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11670 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11671 SelectionDAG &DAG) const {
11672 MVT VT = Op.getSimpleValueType();
11673 MVT EltVT = VT.getVectorElementType();
11675 if (EltVT == MVT::i1)
11676 return InsertBitToMaskVector(Op, DAG);
11679 SDValue N0 = Op.getOperand(0);
11680 SDValue N1 = Op.getOperand(1);
11681 SDValue N2 = Op.getOperand(2);
11682 if (!isa<ConstantSDNode>(N2))
11684 auto *N2C = cast<ConstantSDNode>(N2);
11685 unsigned IdxVal = N2C->getZExtValue();
11687 // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11688 // into that, and then insert the subvector back into the result.
11689 if (VT.is256BitVector() || VT.is512BitVector()) {
11690 // With a 256-bit vector, we can insert into the zero element efficiently
11691 // using a blend if we have AVX or AVX2 and the right data type.
11692 if (VT.is256BitVector() && IdxVal == 0) {
11693 // TODO: It is worthwhile to cast integer to floating point and back
11694 // and incur a domain crossing penalty if that's what we'll end up
11695 // doing anyway after extracting to a 128-bit vector.
11696 if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11697 (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11698 SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11699 N2 = DAG.getIntPtrConstant(1, dl);
11700 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11704 // Get the desired 128-bit vector chunk.
11705 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11707 // Insert the element into the desired chunk.
11708 unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11709 assert(isPowerOf2_32(NumEltsIn128));
11710 // Since NumEltsIn128 is a power of 2 we can use mask instead of modulo.
11711 unsigned IdxIn128 = IdxVal & (NumEltsIn128 - 1);
11713 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11714 DAG.getConstant(IdxIn128, dl, MVT::i32));
11716 // Insert the changed part back into the bigger vector
11717 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11719 assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11721 if (Subtarget->hasSSE41()) {
11722 if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11724 if (VT == MVT::v8i16) {
11725 Opc = X86ISD::PINSRW;
11727 assert(VT == MVT::v16i8);
11728 Opc = X86ISD::PINSRB;
11731 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11733 if (N1.getValueType() != MVT::i32)
11734 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11735 if (N2.getValueType() != MVT::i32)
11736 N2 = DAG.getIntPtrConstant(IdxVal, dl);
11737 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11740 if (EltVT == MVT::f32) {
11741 // Bits [7:6] of the constant are the source select. This will always be
11742 // zero here. The DAG Combiner may combine an extract_elt index into
11743 // these bits. For example (insert (extract, 3), 2) could be matched by
11744 // putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11745 // Bits [5:4] of the constant are the destination select. This is the
11746 // value of the incoming immediate.
11747 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11748 // combine either bitwise AND or insert of float 0.0 to set these bits.
11750 bool MinSize = DAG.getMachineFunction().getFunction()->optForMinSize();
11751 if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11752 // If this is an insertion of 32-bits into the low 32-bits of
11753 // a vector, we prefer to generate a blend with immediate rather
11754 // than an insertps. Blends are simpler operations in hardware and so
11755 // will always have equal or better performance than insertps.
11756 // But if optimizing for size and there's a load folding opportunity,
11757 // generate insertps because blendps does not have a 32-bit memory
11759 N2 = DAG.getIntPtrConstant(1, dl);
11760 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11761 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11763 N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11764 // Create this as a scalar to vector..
11765 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11766 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11769 if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11770 // PINSR* works with constant index.
11775 if (EltVT == MVT::i8)
11778 if (EltVT.getSizeInBits() == 16) {
11779 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11780 // as its second argument.
11781 if (N1.getValueType() != MVT::i32)
11782 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11783 if (N2.getValueType() != MVT::i32)
11784 N2 = DAG.getIntPtrConstant(IdxVal, dl);
11785 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11790 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11792 MVT OpVT = Op.getSimpleValueType();
11794 // If this is a 256-bit vector result, first insert into a 128-bit
11795 // vector and then insert into the 256-bit vector.
11796 if (!OpVT.is128BitVector()) {
11797 // Insert into a 128-bit vector.
11798 unsigned SizeFactor = OpVT.getSizeInBits()/128;
11799 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11800 OpVT.getVectorNumElements() / SizeFactor);
11802 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11804 // Insert the 128-bit vector.
11805 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11808 if (OpVT == MVT::v1i64 &&
11809 Op.getOperand(0).getValueType() == MVT::i64)
11810 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11812 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11813 assert(OpVT.is128BitVector() && "Expected an SSE type!");
11814 return DAG.getBitcast(
11815 OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11818 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
11819 // a simple subregister reference or explicit instructions to grab
11820 // upper bits of a vector.
11821 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11822 SelectionDAG &DAG) {
11824 SDValue In = Op.getOperand(0);
11825 SDValue Idx = Op.getOperand(1);
11826 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11827 MVT ResVT = Op.getSimpleValueType();
11828 MVT InVT = In.getSimpleValueType();
11830 if (Subtarget->hasFp256()) {
11831 if (ResVT.is128BitVector() &&
11832 (InVT.is256BitVector() || InVT.is512BitVector()) &&
11833 isa<ConstantSDNode>(Idx)) {
11834 return Extract128BitVector(In, IdxVal, DAG, dl);
11836 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
11837 isa<ConstantSDNode>(Idx)) {
11838 return Extract256BitVector(In, IdxVal, DAG, dl);
11844 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
11845 // simple superregister reference or explicit instructions to insert
11846 // the upper bits of a vector.
11847 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11848 SelectionDAG &DAG) {
11849 if (!Subtarget->hasAVX())
11853 SDValue Vec = Op.getOperand(0);
11854 SDValue SubVec = Op.getOperand(1);
11855 SDValue Idx = Op.getOperand(2);
11857 if (!isa<ConstantSDNode>(Idx))
11860 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11861 MVT OpVT = Op.getSimpleValueType();
11862 MVT SubVecVT = SubVec.getSimpleValueType();
11864 // Fold two 16-byte subvector loads into one 32-byte load:
11865 // (insert_subvector (insert_subvector undef, (load addr), 0),
11866 // (load addr + 16), Elts/2)
11868 if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
11869 Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
11870 OpVT.is256BitVector() && SubVecVT.is128BitVector()) {
11871 auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2));
11872 if (Idx2 && Idx2->getZExtValue() == 0) {
11873 SDValue SubVec2 = Vec.getOperand(1);
11874 // If needed, look through a bitcast to get to the load.
11875 if (SubVec2.getNode() && SubVec2.getOpcode() == ISD::BITCAST)
11876 SubVec2 = SubVec2.getOperand(0);
11878 if (auto *FirstLd = dyn_cast<LoadSDNode>(SubVec2)) {
11880 unsigned Alignment = FirstLd->getAlignment();
11881 unsigned AS = FirstLd->getAddressSpace();
11882 const X86TargetLowering *TLI = Subtarget->getTargetLowering();
11883 if (TLI->allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(),
11884 OpVT, AS, Alignment, &Fast) && Fast) {
11885 SDValue Ops[] = { SubVec2, SubVec };
11886 if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
11893 if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
11894 SubVecVT.is128BitVector())
11895 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11897 if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
11898 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11900 if (OpVT.getVectorElementType() == MVT::i1)
11901 return Insert1BitVector(Op, DAG);
11906 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11907 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11908 // one of the above mentioned nodes. It has to be wrapped because otherwise
11909 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11910 // be used to form addressing mode. These wrapped nodes will be selected
11913 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11914 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11916 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11917 // global base reg.
11918 unsigned char OpFlag = 0;
11919 unsigned WrapperKind = X86ISD::Wrapper;
11920 CodeModel::Model M = DAG.getTarget().getCodeModel();
11922 if (Subtarget->isPICStyleRIPRel() &&
11923 (M == CodeModel::Small || M == CodeModel::Kernel))
11924 WrapperKind = X86ISD::WrapperRIP;
11925 else if (Subtarget->isPICStyleGOT())
11926 OpFlag = X86II::MO_GOTOFF;
11927 else if (Subtarget->isPICStyleStubPIC())
11928 OpFlag = X86II::MO_PIC_BASE_OFFSET;
11930 auto PtrVT = getPointerTy(DAG.getDataLayout());
11931 SDValue Result = DAG.getTargetConstantPool(
11932 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
11934 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11935 // With PIC, the address is actually $g + Offset.
11938 DAG.getNode(ISD::ADD, DL, PtrVT,
11939 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11945 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11946 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11948 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11949 // global base reg.
11950 unsigned char OpFlag = 0;
11951 unsigned WrapperKind = X86ISD::Wrapper;
11952 CodeModel::Model M = DAG.getTarget().getCodeModel();
11954 if (Subtarget->isPICStyleRIPRel() &&
11955 (M == CodeModel::Small || M == CodeModel::Kernel))
11956 WrapperKind = X86ISD::WrapperRIP;
11957 else if (Subtarget->isPICStyleGOT())
11958 OpFlag = X86II::MO_GOTOFF;
11959 else if (Subtarget->isPICStyleStubPIC())
11960 OpFlag = X86II::MO_PIC_BASE_OFFSET;
11962 auto PtrVT = getPointerTy(DAG.getDataLayout());
11963 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
11965 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11967 // With PIC, the address is actually $g + Offset.
11970 DAG.getNode(ISD::ADD, DL, PtrVT,
11971 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11977 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11978 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11980 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11981 // global base reg.
11982 unsigned char OpFlag = 0;
11983 unsigned WrapperKind = X86ISD::Wrapper;
11984 CodeModel::Model M = DAG.getTarget().getCodeModel();
11986 if (Subtarget->isPICStyleRIPRel() &&
11987 (M == CodeModel::Small || M == CodeModel::Kernel)) {
11988 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11989 OpFlag = X86II::MO_GOTPCREL;
11990 WrapperKind = X86ISD::WrapperRIP;
11991 } else if (Subtarget->isPICStyleGOT()) {
11992 OpFlag = X86II::MO_GOT;
11993 } else if (Subtarget->isPICStyleStubPIC()) {
11994 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11995 } else if (Subtarget->isPICStyleStubNoDynamic()) {
11996 OpFlag = X86II::MO_DARWIN_NONLAZY;
11999 auto PtrVT = getPointerTy(DAG.getDataLayout());
12000 SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
12003 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12005 // With PIC, the address is actually $g + Offset.
12006 if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
12007 !Subtarget->is64Bit()) {
12009 DAG.getNode(ISD::ADD, DL, PtrVT,
12010 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
12013 // For symbols that require a load from a stub to get the address, emit the
12015 if (isGlobalStubReference(OpFlag))
12016 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
12017 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12018 false, false, false, 0);
12024 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
12025 // Create the TargetBlockAddressAddress node.
12026 unsigned char OpFlags =
12027 Subtarget->ClassifyBlockAddressReference();
12028 CodeModel::Model M = DAG.getTarget().getCodeModel();
12029 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
12030 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
12032 auto PtrVT = getPointerTy(DAG.getDataLayout());
12033 SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
12035 if (Subtarget->isPICStyleRIPRel() &&
12036 (M == CodeModel::Small || M == CodeModel::Kernel))
12037 Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
12039 Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
12041 // With PIC, the address is actually $g + Offset.
12042 if (isGlobalRelativeToPICBase(OpFlags)) {
12043 Result = DAG.getNode(ISD::ADD, dl, PtrVT,
12044 DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
12051 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
12052 int64_t Offset, SelectionDAG &DAG) const {
12053 // Create the TargetGlobalAddress node, folding in the constant
12054 // offset if it is legal.
12055 unsigned char OpFlags =
12056 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
12057 CodeModel::Model M = DAG.getTarget().getCodeModel();
12058 auto PtrVT = getPointerTy(DAG.getDataLayout());
12060 if (OpFlags == X86II::MO_NO_FLAG &&
12061 X86::isOffsetSuitableForCodeModel(Offset, M)) {
12062 // A direct static reference to a global.
12063 Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
12066 Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
12069 if (Subtarget->isPICStyleRIPRel() &&
12070 (M == CodeModel::Small || M == CodeModel::Kernel))
12071 Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
12073 Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
12075 // With PIC, the address is actually $g + Offset.
12076 if (isGlobalRelativeToPICBase(OpFlags)) {
12077 Result = DAG.getNode(ISD::ADD, dl, PtrVT,
12078 DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
12081 // For globals that require a load from a stub to get the address, emit the
12083 if (isGlobalStubReference(OpFlags))
12084 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
12085 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12086 false, false, false, 0);
12088 // If there was a non-zero offset that we didn't fold, create an explicit
12089 // addition for it.
12091 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
12092 DAG.getConstant(Offset, dl, PtrVT));
12098 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
12099 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
12100 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
12101 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
12105 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
12106 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
12107 unsigned char OperandFlags, bool LocalDynamic = false) {
12108 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12109 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12111 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12112 GA->getValueType(0),
12116 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
12120 SDValue Ops[] = { Chain, TGA, *InFlag };
12121 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
12123 SDValue Ops[] = { Chain, TGA };
12124 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
12127 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
12128 MFI->setAdjustsStack(true);
12129 MFI->setHasCalls(true);
12131 SDValue Flag = Chain.getValue(1);
12132 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
12135 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
12137 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12140 SDLoc dl(GA); // ? function entry point might be better
12141 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
12142 DAG.getNode(X86ISD::GlobalBaseReg,
12143 SDLoc(), PtrVT), InFlag);
12144 InFlag = Chain.getValue(1);
12146 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
12149 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
12151 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12153 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
12154 X86::RAX, X86II::MO_TLSGD);
12157 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
12163 // Get the start address of the TLS block for this module.
12164 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
12165 .getInfo<X86MachineFunctionInfo>();
12166 MFI->incNumLocalDynamicTLSAccesses();
12170 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
12171 X86II::MO_TLSLD, /*LocalDynamic=*/true);
12174 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
12175 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
12176 InFlag = Chain.getValue(1);
12177 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
12178 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
12181 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
12185 unsigned char OperandFlags = X86II::MO_DTPOFF;
12186 unsigned WrapperKind = X86ISD::Wrapper;
12187 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12188 GA->getValueType(0),
12189 GA->getOffset(), OperandFlags);
12190 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
12192 // Add x@dtpoff with the base.
12193 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
12196 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
12197 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12198 const EVT PtrVT, TLSModel::Model model,
12199 bool is64Bit, bool isPIC) {
12202 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
12203 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
12204 is64Bit ? 257 : 256));
12206 SDValue ThreadPointer =
12207 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
12208 MachinePointerInfo(Ptr), false, false, false, 0);
12210 unsigned char OperandFlags = 0;
12211 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
12213 unsigned WrapperKind = X86ISD::Wrapper;
12214 if (model == TLSModel::LocalExec) {
12215 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
12216 } else if (model == TLSModel::InitialExec) {
12218 OperandFlags = X86II::MO_GOTTPOFF;
12219 WrapperKind = X86ISD::WrapperRIP;
12221 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
12224 llvm_unreachable("Unexpected model");
12227 // emit "addl x@ntpoff,%eax" (local exec)
12228 // or "addl x@indntpoff,%eax" (initial exec)
12229 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
12231 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
12232 GA->getOffset(), OperandFlags);
12233 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
12235 if (model == TLSModel::InitialExec) {
12236 if (isPIC && !is64Bit) {
12237 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
12238 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12242 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
12243 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
12244 false, false, false, 0);
12247 // The address of the thread local variable is the add of the thread
12248 // pointer with the offset of the variable.
12249 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
12253 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
12255 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
12256 const GlobalValue *GV = GA->getGlobal();
12257 auto PtrVT = getPointerTy(DAG.getDataLayout());
12259 if (Subtarget->isTargetELF()) {
12260 if (DAG.getTarget().Options.EmulatedTLS)
12261 return LowerToTLSEmulatedModel(GA, DAG);
12262 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
12264 case TLSModel::GeneralDynamic:
12265 if (Subtarget->is64Bit())
12266 return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
12267 return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
12268 case TLSModel::LocalDynamic:
12269 return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
12270 Subtarget->is64Bit());
12271 case TLSModel::InitialExec:
12272 case TLSModel::LocalExec:
12273 return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
12274 DAG.getTarget().getRelocationModel() ==
12277 llvm_unreachable("Unknown TLS model.");
12280 if (Subtarget->isTargetDarwin()) {
12281 // Darwin only has one model of TLS. Lower to that.
12282 unsigned char OpFlag = 0;
12283 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
12284 X86ISD::WrapperRIP : X86ISD::Wrapper;
12286 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12287 // global base reg.
12288 bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
12289 !Subtarget->is64Bit();
12291 OpFlag = X86II::MO_TLVP_PIC_BASE;
12293 OpFlag = X86II::MO_TLVP;
12295 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
12296 GA->getValueType(0),
12297 GA->getOffset(), OpFlag);
12298 SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
12300 // With PIC32, the address is actually $g + Offset.
12302 Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
12303 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12306 // Lowering the machine isd will make sure everything is in the right
12308 SDValue Chain = DAG.getEntryNode();
12309 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12310 SDValue Args[] = { Chain, Offset };
12311 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
12313 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
12314 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12315 MFI->setAdjustsStack(true);
12317 // And our return value (tls address) is in the standard call return value
12319 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12320 return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
12323 if (Subtarget->isTargetKnownWindowsMSVC() ||
12324 Subtarget->isTargetWindowsGNU()) {
12325 // Just use the implicit TLS architecture
12326 // Need to generate someting similar to:
12327 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
12329 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
12330 // mov rcx, qword [rdx+rcx*8]
12331 // mov eax, .tls$:tlsvar
12332 // [rax+rcx] contains the address
12333 // Windows 64bit: gs:0x58
12334 // Windows 32bit: fs:__tls_array
12337 SDValue Chain = DAG.getEntryNode();
12339 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
12340 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
12341 // use its literal value of 0x2C.
12342 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
12343 ? Type::getInt8PtrTy(*DAG.getContext(),
12345 : Type::getInt32PtrTy(*DAG.getContext(),
12348 SDValue TlsArray = Subtarget->is64Bit()
12349 ? DAG.getIntPtrConstant(0x58, dl)
12350 : (Subtarget->isTargetWindowsGNU()
12351 ? DAG.getIntPtrConstant(0x2C, dl)
12352 : DAG.getExternalSymbol("_tls_array", PtrVT));
12354 SDValue ThreadPointer =
12355 DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
12359 if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
12360 res = ThreadPointer;
12362 // Load the _tls_index variable
12363 SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
12364 if (Subtarget->is64Bit())
12365 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
12366 MachinePointerInfo(), MVT::i32, false, false,
12369 IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
12372 auto &DL = DAG.getDataLayout();
12374 DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
12375 IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
12377 res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
12380 res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
12383 // Get the offset of start of .tls section
12384 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12385 GA->getValueType(0),
12386 GA->getOffset(), X86II::MO_SECREL);
12387 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
12389 // The address of the thread local variable is the add of the thread
12390 // pointer with the offset of the variable.
12391 return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
12394 llvm_unreachable("TLS not implemented for this target.");
12397 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
12398 /// and take a 2 x i32 value to shift plus a shift amount.
12399 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
12400 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
12401 MVT VT = Op.getSimpleValueType();
12402 unsigned VTBits = VT.getSizeInBits();
12404 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
12405 SDValue ShOpLo = Op.getOperand(0);
12406 SDValue ShOpHi = Op.getOperand(1);
12407 SDValue ShAmt = Op.getOperand(2);
12408 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
12409 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
12411 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12412 DAG.getConstant(VTBits - 1, dl, MVT::i8));
12413 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
12414 DAG.getConstant(VTBits - 1, dl, MVT::i8))
12415 : DAG.getConstant(0, dl, VT);
12417 SDValue Tmp2, Tmp3;
12418 if (Op.getOpcode() == ISD::SHL_PARTS) {
12419 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
12420 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
12422 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
12423 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
12426 // If the shift amount is larger or equal than the width of a part we can't
12427 // rely on the results of shld/shrd. Insert a test and select the appropriate
12428 // values for large shift amounts.
12429 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12430 DAG.getConstant(VTBits, dl, MVT::i8));
12431 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
12432 AndNode, DAG.getConstant(0, dl, MVT::i8));
12435 SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
12436 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
12437 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
12439 if (Op.getOpcode() == ISD::SHL_PARTS) {
12440 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12441 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12443 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12444 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12447 SDValue Ops[2] = { Lo, Hi };
12448 return DAG.getMergeValues(Ops, dl);
12451 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
12452 SelectionDAG &DAG) const {
12453 SDValue Src = Op.getOperand(0);
12454 MVT SrcVT = Src.getSimpleValueType();
12455 MVT VT = Op.getSimpleValueType();
12458 if (SrcVT.isVector()) {
12459 if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
12460 return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
12461 DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
12462 DAG.getUNDEF(SrcVT)));
12464 if (SrcVT.getVectorElementType() == MVT::i1) {
12465 MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
12466 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12467 DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
12472 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
12473 "Unknown SINT_TO_FP to lower!");
12475 // These are really Legal; return the operand so the caller accepts it as
12477 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
12479 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
12480 Subtarget->is64Bit()) {
12484 unsigned Size = SrcVT.getSizeInBits()/8;
12485 MachineFunction &MF = DAG.getMachineFunction();
12486 auto PtrVT = getPointerTy(MF.getDataLayout());
12487 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
12488 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12489 SDValue Chain = DAG.getStore(
12490 DAG.getEntryNode(), dl, Op.getOperand(0), StackSlot,
12491 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI), false,
12493 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
12496 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
12498 SelectionDAG &DAG) const {
12502 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
12504 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
12506 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
12508 unsigned ByteSize = SrcVT.getSizeInBits()/8;
12510 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
12511 MachineMemOperand *MMO;
12513 int SSFI = FI->getIndex();
12514 MMO = DAG.getMachineFunction().getMachineMemOperand(
12515 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12516 MachineMemOperand::MOLoad, ByteSize, ByteSize);
12518 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
12519 StackSlot = StackSlot.getOperand(1);
12521 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
12522 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
12524 Tys, Ops, SrcVT, MMO);
12527 Chain = Result.getValue(1);
12528 SDValue InFlag = Result.getValue(2);
12530 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
12531 // shouldn't be necessary except that RFP cannot be live across
12532 // multiple blocks. When stackifier is fixed, they can be uncoupled.
12533 MachineFunction &MF = DAG.getMachineFunction();
12534 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
12535 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
12536 auto PtrVT = getPointerTy(MF.getDataLayout());
12537 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12538 Tys = DAG.getVTList(MVT::Other);
12540 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
12542 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12543 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12544 MachineMemOperand::MOStore, SSFISize, SSFISize);
12546 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
12547 Ops, Op.getValueType(), MMO);
12548 Result = DAG.getLoad(
12549 Op.getValueType(), DL, Chain, StackSlot,
12550 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12551 false, false, false, 0);
12557 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
12558 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
12559 SelectionDAG &DAG) const {
12560 // This algorithm is not obvious. Here it is what we're trying to output:
12563 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
12564 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
12566 haddpd %xmm0, %xmm0
12568 pshufd $0x4e, %xmm0, %xmm1
12574 LLVMContext *Context = DAG.getContext();
12576 // Build some magic constants.
12577 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
12578 Constant *C0 = ConstantDataVector::get(*Context, CV0);
12579 auto PtrVT = getPointerTy(DAG.getDataLayout());
12580 SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
12582 SmallVector<Constant*,2> CV1;
12584 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12585 APInt(64, 0x4330000000000000ULL))));
12587 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12588 APInt(64, 0x4530000000000000ULL))));
12589 Constant *C1 = ConstantVector::get(CV1);
12590 SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
12592 // Load the 64-bit value into an XMM register.
12593 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
12596 DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
12597 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12598 false, false, false, 16);
12600 getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
12603 DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
12604 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
12605 false, false, false, 16);
12606 SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
12607 // TODO: Are there any fast-math-flags to propagate here?
12608 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
12611 if (Subtarget->hasSSE3()) {
12612 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
12613 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
12615 SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
12616 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
12618 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
12619 DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
12622 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
12623 DAG.getIntPtrConstant(0, dl));
12626 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
12627 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
12628 SelectionDAG &DAG) const {
12630 // FP constant to bias correct the final result.
12631 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
12634 // Load the 32-bit value into an XMM register.
12635 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12638 // Zero out the upper parts of the register.
12639 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12641 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12642 DAG.getBitcast(MVT::v2f64, Load),
12643 DAG.getIntPtrConstant(0, dl));
12645 // Or the load with the bias.
12646 SDValue Or = DAG.getNode(
12647 ISD::OR, dl, MVT::v2i64,
12648 DAG.getBitcast(MVT::v2i64,
12649 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12650 DAG.getBitcast(MVT::v2i64,
12651 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12653 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12654 DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12656 // Subtract the bias.
12657 // TODO: Are there any fast-math-flags to propagate here?
12658 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12660 // Handle final rounding.
12661 MVT DestVT = Op.getSimpleValueType();
12663 if (DestVT.bitsLT(MVT::f64))
12664 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12665 DAG.getIntPtrConstant(0, dl));
12666 if (DestVT.bitsGT(MVT::f64))
12667 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12669 // Handle final rounding.
12673 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12674 const X86Subtarget &Subtarget) {
12675 // The algorithm is the following:
12676 // #ifdef __SSE4_1__
12677 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12678 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12679 // (uint4) 0x53000000, 0xaa);
12681 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12682 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
12684 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12685 // return (float4) lo + fhi;
12687 // We shouldn't use it when unsafe-fp-math is enabled though: we might later
12688 // reassociate the two FADDs, and if we do that, the algorithm fails
12689 // spectacularly (PR24512).
12690 // FIXME: If we ever have some kind of Machine FMF, this should be marked
12691 // as non-fast and always be enabled. Why isn't SDAG FMF enough? Because
12692 // there's also the MachineCombiner reassociations happening on Machine IR.
12693 if (DAG.getTarget().Options.UnsafeFPMath)
12697 SDValue V = Op->getOperand(0);
12698 MVT VecIntVT = V.getSimpleValueType();
12699 bool Is128 = VecIntVT == MVT::v4i32;
12700 MVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12701 // If we convert to something else than the supported type, e.g., to v4f64,
12703 if (VecFloatVT != Op->getSimpleValueType(0))
12706 unsigned NumElts = VecIntVT.getVectorNumElements();
12707 assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12708 "Unsupported custom type");
12709 assert(NumElts <= 8 && "The size of the constant array must be fixed");
12711 // In the #idef/#else code, we have in common:
12712 // - The vector of constants:
12718 // Create the splat vector for 0x4b000000.
12719 SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12720 SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12721 CstLow, CstLow, CstLow, CstLow};
12722 SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12723 makeArrayRef(&CstLowArray[0], NumElts));
12724 // Create the splat vector for 0x53000000.
12725 SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12726 SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12727 CstHigh, CstHigh, CstHigh, CstHigh};
12728 SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12729 makeArrayRef(&CstHighArray[0], NumElts));
12731 // Create the right shift.
12732 SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12733 SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12734 CstShift, CstShift, CstShift, CstShift};
12735 SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12736 makeArrayRef(&CstShiftArray[0], NumElts));
12737 SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12740 if (Subtarget.hasSSE41()) {
12741 MVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12742 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12743 SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12744 SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12745 // Low will be bitcasted right away, so do not bother bitcasting back to its
12747 Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12748 VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12749 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12750 // (uint4) 0x53000000, 0xaa);
12751 SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12752 SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12753 // High will be bitcasted right away, so do not bother bitcasting back to
12754 // its original type.
12755 High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12756 VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12758 SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12759 SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12760 CstMask, CstMask, CstMask);
12761 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12762 SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12763 Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12765 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
12766 High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12769 // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12770 SDValue CstFAdd = DAG.getConstantFP(
12771 APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12772 SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12773 CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12774 SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12775 makeArrayRef(&CstFAddArray[0], NumElts));
12777 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12778 SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12779 // TODO: Are there any fast-math-flags to propagate here?
12781 DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12782 // return (float4) lo + fhi;
12783 SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12784 return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12787 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12788 SelectionDAG &DAG) const {
12789 SDValue N0 = Op.getOperand(0);
12790 MVT SVT = N0.getSimpleValueType();
12793 switch (SVT.SimpleTy) {
12795 llvm_unreachable("Custom UINT_TO_FP is not supported!");
12800 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12801 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12802 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12806 return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
12809 assert(Subtarget->hasAVX512());
12810 return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
12811 DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
12815 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12816 SelectionDAG &DAG) const {
12817 SDValue N0 = Op.getOperand(0);
12819 auto PtrVT = getPointerTy(DAG.getDataLayout());
12821 if (Op.getSimpleValueType().isVector())
12822 return lowerUINT_TO_FP_vec(Op, DAG);
12824 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
12825 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
12826 // the optimization here.
12827 if (DAG.SignBitIsZero(N0))
12828 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
12830 MVT SrcVT = N0.getSimpleValueType();
12831 MVT DstVT = Op.getSimpleValueType();
12833 if (Subtarget->hasAVX512() && isScalarFPTypeInSSEReg(DstVT) &&
12834 (SrcVT == MVT::i32 || (SrcVT == MVT::i64 && Subtarget->is64Bit()))) {
12835 // Conversions from unsigned i32 to f32/f64 are legal,
12836 // using VCVTUSI2SS/SD. Same for i64 in 64-bit mode.
12840 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
12841 return LowerUINT_TO_FP_i64(Op, DAG);
12842 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
12843 return LowerUINT_TO_FP_i32(Op, DAG);
12844 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
12847 // Make a 64-bit buffer, and use it to build an FILD.
12848 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
12849 if (SrcVT == MVT::i32) {
12850 SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
12851 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
12852 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12853 StackSlot, MachinePointerInfo(),
12855 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
12856 OffsetSlot, MachinePointerInfo(),
12858 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
12862 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
12863 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12864 StackSlot, MachinePointerInfo(),
12866 // For i64 source, we need to add the appropriate power of 2 if the input
12867 // was negative. This is the same as the optimization in
12868 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
12869 // we must be careful to do the computation in x87 extended precision, not
12870 // in SSE. (The generic code can't know it's OK to do this, or how to.)
12871 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
12872 MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
12873 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SSFI),
12874 MachineMemOperand::MOLoad, 8, 8);
12876 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
12877 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
12878 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
12881 APInt FF(32, 0x5F800000ULL);
12883 // Check whether the sign bit is set.
12884 SDValue SignSet = DAG.getSetCC(
12885 dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
12886 Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
12888 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
12889 SDValue FudgePtr = DAG.getConstantPool(
12890 ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
12892 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
12893 SDValue Zero = DAG.getIntPtrConstant(0, dl);
12894 SDValue Four = DAG.getIntPtrConstant(4, dl);
12895 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
12897 FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
12899 // Load the value out, extending it from f32 to f80.
12900 // FIXME: Avoid the extend by constructing the right constant pool?
12901 SDValue Fudge = DAG.getExtLoad(
12902 ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(), FudgePtr,
12903 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
12904 false, false, false, 4);
12905 // Extend everything to 80 bits to force it to be done on x87.
12906 // TODO: Are there any fast-math-flags to propagate here?
12907 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
12908 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
12909 DAG.getIntPtrConstant(0, dl));
12912 // If the given FP_TO_SINT (IsSigned) or FP_TO_UINT (!IsSigned) operation
12913 // is legal, or has an fp128 or f16 source (which needs to be promoted to f32),
12914 // just return an <SDValue(), SDValue()> pair.
12915 // Otherwise it is assumed to be a conversion from one of f32, f64 or f80
12916 // to i16, i32 or i64, and we lower it to a legal sequence.
12917 // If lowered to the final integer result we return a <result, SDValue()> pair.
12918 // Otherwise we lower it to a sequence ending with a FIST, return a
12919 // <FIST, StackSlot> pair, and the caller is responsible for loading
12920 // the final integer result from StackSlot.
12921 std::pair<SDValue,SDValue>
12922 X86TargetLowering::FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
12923 bool IsSigned, bool IsReplace) const {
12926 EVT DstTy = Op.getValueType();
12927 EVT TheVT = Op.getOperand(0).getValueType();
12928 auto PtrVT = getPointerTy(DAG.getDataLayout());
12930 if (TheVT != MVT::f32 && TheVT != MVT::f64 && TheVT != MVT::f80) {
12931 // f16 must be promoted before using the lowering in this routine.
12932 // fp128 does not use this lowering.
12933 return std::make_pair(SDValue(), SDValue());
12936 // If using FIST to compute an unsigned i64, we'll need some fixup
12937 // to handle values above the maximum signed i64. A FIST is always
12938 // used for the 32-bit subtarget, but also for f80 on a 64-bit target.
12939 bool UnsignedFixup = !IsSigned &&
12940 DstTy == MVT::i64 &&
12941 (!Subtarget->is64Bit() ||
12942 !isScalarFPTypeInSSEReg(TheVT));
12944 if (!IsSigned && DstTy != MVT::i64 && !Subtarget->hasAVX512()) {
12945 // Replace the fp-to-uint32 operation with an fp-to-sint64 FIST.
12946 // The low 32 bits of the fist result will have the correct uint32 result.
12947 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
12951 assert(DstTy.getSimpleVT() <= MVT::i64 &&
12952 DstTy.getSimpleVT() >= MVT::i16 &&
12953 "Unknown FP_TO_INT to lower!");
12955 // These are really Legal.
12956 if (DstTy == MVT::i32 &&
12957 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12958 return std::make_pair(SDValue(), SDValue());
12959 if (Subtarget->is64Bit() &&
12960 DstTy == MVT::i64 &&
12961 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12962 return std::make_pair(SDValue(), SDValue());
12964 // We lower FP->int64 into FISTP64 followed by a load from a temporary
12966 MachineFunction &MF = DAG.getMachineFunction();
12967 unsigned MemSize = DstTy.getSizeInBits()/8;
12968 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12969 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12972 switch (DstTy.getSimpleVT().SimpleTy) {
12973 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12974 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12975 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12976 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12979 SDValue Chain = DAG.getEntryNode();
12980 SDValue Value = Op.getOperand(0);
12981 SDValue Adjust; // 0x0 or 0x80000000, for result sign bit adjustment.
12983 if (UnsignedFixup) {
12985 // Conversion to unsigned i64 is implemented with a select,
12986 // depending on whether the source value fits in the range
12987 // of a signed i64. Let Thresh be the FP equivalent of
12988 // 0x8000000000000000ULL.
12990 // Adjust i32 = (Value < Thresh) ? 0 : 0x80000000;
12991 // FistSrc = (Value < Thresh) ? Value : (Value - Thresh);
12992 // Fist-to-mem64 FistSrc
12993 // Add 0 or 0x800...0ULL to the 64-bit result, which is equivalent
12994 // to XOR'ing the high 32 bits with Adjust.
12996 // Being a power of 2, Thresh is exactly representable in all FP formats.
12997 // For X87 we'd like to use the smallest FP type for this constant, but
12998 // for DAG type consistency we have to match the FP operand type.
13000 APFloat Thresh(APFloat::IEEEsingle, APInt(32, 0x5f000000));
13001 LLVM_ATTRIBUTE_UNUSED APFloat::opStatus Status = APFloat::opOK;
13002 bool LosesInfo = false;
13003 if (TheVT == MVT::f64)
13004 // The rounding mode is irrelevant as the conversion should be exact.
13005 Status = Thresh.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
13007 else if (TheVT == MVT::f80)
13008 Status = Thresh.convert(APFloat::x87DoubleExtended,
13009 APFloat::rmNearestTiesToEven, &LosesInfo);
13011 assert(Status == APFloat::opOK && !LosesInfo &&
13012 "FP conversion should have been exact");
13014 SDValue ThreshVal = DAG.getConstantFP(Thresh, DL, TheVT);
13016 SDValue Cmp = DAG.getSetCC(DL,
13017 getSetCCResultType(DAG.getDataLayout(),
13018 *DAG.getContext(), TheVT),
13019 Value, ThreshVal, ISD::SETLT);
13020 Adjust = DAG.getSelect(DL, MVT::i32, Cmp,
13021 DAG.getConstant(0, DL, MVT::i32),
13022 DAG.getConstant(0x80000000, DL, MVT::i32));
13023 SDValue Sub = DAG.getNode(ISD::FSUB, DL, TheVT, Value, ThreshVal);
13024 Cmp = DAG.getSetCC(DL, getSetCCResultType(DAG.getDataLayout(),
13025 *DAG.getContext(), TheVT),
13026 Value, ThreshVal, ISD::SETLT);
13027 Value = DAG.getSelect(DL, TheVT, Cmp, Value, Sub);
13030 // FIXME This causes a redundant load/store if the SSE-class value is already
13031 // in memory, such as if it is on the callstack.
13032 if (isScalarFPTypeInSSEReg(TheVT)) {
13033 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
13034 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
13035 MachinePointerInfo::getFixedStack(MF, SSFI), false,
13037 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
13039 Chain, StackSlot, DAG.getValueType(TheVT)
13042 MachineMemOperand *MMO =
13043 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
13044 MachineMemOperand::MOLoad, MemSize, MemSize);
13045 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
13046 Chain = Value.getValue(1);
13047 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
13048 StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
13051 MachineMemOperand *MMO =
13052 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
13053 MachineMemOperand::MOStore, MemSize, MemSize);
13055 if (UnsignedFixup) {
13057 // Insert the FIST, load its result as two i32's,
13058 // and XOR the high i32 with Adjust.
13060 SDValue FistOps[] = { Chain, Value, StackSlot };
13061 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
13062 FistOps, DstTy, MMO);
13064 SDValue Low32 = DAG.getLoad(MVT::i32, DL, FIST, StackSlot,
13065 MachinePointerInfo(),
13066 false, false, false, 0);
13067 SDValue HighAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackSlot,
13068 DAG.getConstant(4, DL, PtrVT));
13070 SDValue High32 = DAG.getLoad(MVT::i32, DL, FIST, HighAddr,
13071 MachinePointerInfo(),
13072 false, false, false, 0);
13073 High32 = DAG.getNode(ISD::XOR, DL, MVT::i32, High32, Adjust);
13075 if (Subtarget->is64Bit()) {
13076 // Join High32 and Low32 into a 64-bit result.
13077 // (High32 << 32) | Low32
13078 Low32 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Low32);
13079 High32 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, High32);
13080 High32 = DAG.getNode(ISD::SHL, DL, MVT::i64, High32,
13081 DAG.getConstant(32, DL, MVT::i8));
13082 SDValue Result = DAG.getNode(ISD::OR, DL, MVT::i64, High32, Low32);
13083 return std::make_pair(Result, SDValue());
13086 SDValue ResultOps[] = { Low32, High32 };
13088 SDValue pair = IsReplace
13089 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResultOps)
13090 : DAG.getMergeValues(ResultOps, DL);
13091 return std::make_pair(pair, SDValue());
13093 // Build the FP_TO_INT*_IN_MEM
13094 SDValue Ops[] = { Chain, Value, StackSlot };
13095 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
13097 return std::make_pair(FIST, StackSlot);
13101 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
13102 const X86Subtarget *Subtarget) {
13103 MVT VT = Op->getSimpleValueType(0);
13104 SDValue In = Op->getOperand(0);
13105 MVT InVT = In.getSimpleValueType();
13108 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13109 return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
13111 // Optimize vectors in AVX mode:
13114 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
13115 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
13116 // Concat upper and lower parts.
13119 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
13120 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
13121 // Concat upper and lower parts.
13124 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
13125 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
13126 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
13129 if (Subtarget->hasInt256())
13130 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
13132 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
13133 SDValue Undef = DAG.getUNDEF(InVT);
13134 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
13135 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
13136 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
13138 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
13139 VT.getVectorNumElements()/2);
13141 OpLo = DAG.getBitcast(HVT, OpLo);
13142 OpHi = DAG.getBitcast(HVT, OpHi);
13144 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13147 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
13148 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
13149 MVT VT = Op->getSimpleValueType(0);
13150 SDValue In = Op->getOperand(0);
13151 MVT InVT = In.getSimpleValueType();
13153 unsigned int NumElts = VT.getVectorNumElements();
13154 if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
13157 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
13158 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
13160 assert(InVT.getVectorElementType() == MVT::i1);
13161 MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
13163 DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
13165 DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
13167 SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
13168 if (VT.is512BitVector())
13170 return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
13173 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13174 SelectionDAG &DAG) {
13175 if (Subtarget->hasFp256())
13176 if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
13182 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13183 SelectionDAG &DAG) {
13185 MVT VT = Op.getSimpleValueType();
13186 SDValue In = Op.getOperand(0);
13187 MVT SVT = In.getSimpleValueType();
13189 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
13190 return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
13192 if (Subtarget->hasFp256())
13193 if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
13196 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
13197 VT.getVectorNumElements() != SVT.getVectorNumElements());
13201 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
13203 MVT VT = Op.getSimpleValueType();
13204 SDValue In = Op.getOperand(0);
13205 MVT InVT = In.getSimpleValueType();
13207 if (VT == MVT::i1) {
13208 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
13209 "Invalid scalar TRUNCATE operation");
13210 if (InVT.getSizeInBits() >= 32)
13212 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
13213 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
13215 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
13216 "Invalid TRUNCATE operation");
13218 // move vector to mask - truncate solution for SKX
13219 if (VT.getVectorElementType() == MVT::i1) {
13220 if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
13221 Subtarget->hasBWI())
13222 return Op; // legal, will go to VPMOVB2M, VPMOVW2M
13223 if ((InVT.is256BitVector() || InVT.is128BitVector())
13224 && InVT.getScalarSizeInBits() <= 16 &&
13225 Subtarget->hasBWI() && Subtarget->hasVLX())
13226 return Op; // legal, will go to VPMOVB2M, VPMOVW2M
13227 if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
13228 Subtarget->hasDQI())
13229 return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
13230 if ((InVT.is256BitVector() || InVT.is128BitVector())
13231 && InVT.getScalarSizeInBits() >= 32 &&
13232 Subtarget->hasDQI() && Subtarget->hasVLX())
13233 return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
13236 if (VT.getVectorElementType() == MVT::i1) {
13237 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13238 unsigned NumElts = InVT.getVectorNumElements();
13239 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
13240 if (InVT.getSizeInBits() < 512) {
13241 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
13242 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
13247 DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
13248 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
13249 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
13252 // vpmovqb/w/d, vpmovdb/w, vpmovwb
13253 if (Subtarget->hasAVX512()) {
13254 // word to byte only under BWI
13255 if (InVT == MVT::v16i16 && !Subtarget->hasBWI()) // v16i16 -> v16i8
13256 return DAG.getNode(X86ISD::VTRUNC, DL, VT,
13257 DAG.getNode(X86ISD::VSEXT, DL, MVT::v16i32, In));
13258 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
13260 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
13261 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
13262 if (Subtarget->hasInt256()) {
13263 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13264 In = DAG.getBitcast(MVT::v8i32, In);
13265 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
13267 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
13268 DAG.getIntPtrConstant(0, DL));
13271 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13272 DAG.getIntPtrConstant(0, DL));
13273 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13274 DAG.getIntPtrConstant(2, DL));
13275 OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13276 OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13277 static const int ShufMask[] = {0, 2, 4, 6};
13278 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
13281 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
13282 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
13283 if (Subtarget->hasInt256()) {
13284 In = DAG.getBitcast(MVT::v32i8, In);
13286 SmallVector<SDValue,32> pshufbMask;
13287 for (unsigned i = 0; i < 2; ++i) {
13288 pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
13289 pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
13290 pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
13291 pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
13292 pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
13293 pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
13294 pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
13295 pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
13296 for (unsigned j = 0; j < 8; ++j)
13297 pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
13299 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
13300 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
13301 In = DAG.getBitcast(MVT::v4i64, In);
13303 static const int ShufMask[] = {0, 2, -1, -1};
13304 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
13306 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13307 DAG.getIntPtrConstant(0, DL));
13308 return DAG.getBitcast(VT, In);
13311 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13312 DAG.getIntPtrConstant(0, DL));
13314 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13315 DAG.getIntPtrConstant(4, DL));
13317 OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
13318 OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
13320 // The PSHUFB mask:
13321 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
13322 -1, -1, -1, -1, -1, -1, -1, -1};
13324 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
13325 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
13326 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
13328 OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
13329 OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
13331 // The MOVLHPS Mask:
13332 static const int ShufMask2[] = {0, 1, 4, 5};
13333 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
13334 return DAG.getBitcast(MVT::v8i16, res);
13337 // Handle truncation of V256 to V128 using shuffles.
13338 if (!VT.is128BitVector() || !InVT.is256BitVector())
13341 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
13343 unsigned NumElems = VT.getVectorNumElements();
13344 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
13346 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
13347 // Prepare truncation shuffle mask
13348 for (unsigned i = 0; i != NumElems; ++i)
13349 MaskVec[i] = i * 2;
13350 SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
13351 DAG.getUNDEF(NVT), &MaskVec[0]);
13352 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
13353 DAG.getIntPtrConstant(0, DL));
13356 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
13357 SelectionDAG &DAG) const {
13358 assert(!Op.getSimpleValueType().isVector());
13360 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13361 /*IsSigned=*/ true, /*IsReplace=*/ false);
13362 SDValue FIST = Vals.first, StackSlot = Vals.second;
13363 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13364 if (!FIST.getNode())
13367 if (StackSlot.getNode())
13368 // Load the result.
13369 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13370 FIST, StackSlot, MachinePointerInfo(),
13371 false, false, false, 0);
13373 // The node is the result.
13377 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
13378 SelectionDAG &DAG) const {
13379 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13380 /*IsSigned=*/ false, /*IsReplace=*/ false);
13381 SDValue FIST = Vals.first, StackSlot = Vals.second;
13382 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13383 if (!FIST.getNode())
13386 if (StackSlot.getNode())
13387 // Load the result.
13388 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13389 FIST, StackSlot, MachinePointerInfo(),
13390 false, false, false, 0);
13392 // The node is the result.
13396 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
13398 MVT VT = Op.getSimpleValueType();
13399 SDValue In = Op.getOperand(0);
13400 MVT SVT = In.getSimpleValueType();
13402 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
13404 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
13405 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
13406 In, DAG.getUNDEF(SVT)));
13409 /// The only differences between FABS and FNEG are the mask and the logic op.
13410 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
13411 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
13412 assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
13413 "Wrong opcode for lowering FABS or FNEG.");
13415 bool IsFABS = (Op.getOpcode() == ISD::FABS);
13417 // If this is a FABS and it has an FNEG user, bail out to fold the combination
13418 // into an FNABS. We'll lower the FABS after that if it is still in use.
13420 for (SDNode *User : Op->uses())
13421 if (User->getOpcode() == ISD::FNEG)
13425 MVT VT = Op.getSimpleValueType();
13427 bool IsF128 = (VT == MVT::f128);
13429 // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
13430 // decide if we should generate a 16-byte constant mask when we only need 4 or
13431 // 8 bytes for the scalar case.
13437 if (VT.isVector()) {
13439 EltVT = VT.getVectorElementType();
13440 NumElts = VT.getVectorNumElements();
13441 } else if (IsF128) {
13442 // SSE instructions are used for optimized f128 logical operations.
13443 LogicVT = MVT::f128;
13447 // There are no scalar bitwise logical SSE/AVX instructions, so we
13448 // generate a 16-byte vector constant and logic op even for the scalar case.
13449 // Using a 16-byte mask allows folding the load of the mask with
13450 // the logic op, so it can save (~4 bytes) on code size.
13451 LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
13453 NumElts = (VT == MVT::f64) ? 2 : 4;
13456 unsigned EltBits = EltVT.getSizeInBits();
13457 LLVMContext *Context = DAG.getContext();
13458 // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
13460 IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
13461 Constant *C = ConstantInt::get(*Context, MaskElt);
13462 C = ConstantVector::getSplat(NumElts, C);
13463 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13464 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
13465 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13467 DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13468 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13469 false, false, false, Alignment);
13471 SDValue Op0 = Op.getOperand(0);
13472 bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
13474 IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
13475 SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
13477 if (VT.isVector() || IsF128)
13478 return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13480 // For the scalar case extend to a 128-bit vector, perform the logic op,
13481 // and extract the scalar result back out.
13482 Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
13483 SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
13484 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
13485 DAG.getIntPtrConstant(0, dl));
13488 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
13489 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13490 LLVMContext *Context = DAG.getContext();
13491 SDValue Op0 = Op.getOperand(0);
13492 SDValue Op1 = Op.getOperand(1);
13494 MVT VT = Op.getSimpleValueType();
13495 MVT SrcVT = Op1.getSimpleValueType();
13496 bool IsF128 = (VT == MVT::f128);
13498 // If second operand is smaller, extend it first.
13499 if (SrcVT.bitsLT(VT)) {
13500 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
13503 // And if it is bigger, shrink it first.
13504 if (SrcVT.bitsGT(VT)) {
13505 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
13509 // At this point the operands and the result should have the same
13510 // type, and that won't be f80 since that is not custom lowered.
13511 assert((VT == MVT::f64 || VT == MVT::f32 || IsF128) &&
13512 "Unexpected type in LowerFCOPYSIGN");
13514 const fltSemantics &Sem =
13515 VT == MVT::f64 ? APFloat::IEEEdouble :
13516 (IsF128 ? APFloat::IEEEquad : APFloat::IEEEsingle);
13517 const unsigned SizeInBits = VT.getSizeInBits();
13519 SmallVector<Constant *, 4> CV(
13520 VT == MVT::f64 ? 2 : (IsF128 ? 1 : 4),
13521 ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
13523 // First, clear all bits but the sign bit from the second operand (sign).
13524 CV[0] = ConstantFP::get(*Context,
13525 APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
13526 Constant *C = ConstantVector::get(CV);
13527 auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
13528 SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13530 // Perform all logic operations as 16-byte vectors because there are no
13531 // scalar FP logic instructions in SSE. This allows load folding of the
13532 // constants into the logic instructions.
13533 MVT LogicVT = (VT == MVT::f64) ? MVT::v2f64 : (IsF128 ? MVT::f128 : MVT::v4f32);
13535 DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13536 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13537 false, false, false, 16);
13539 Op1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op1);
13540 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op1, Mask1);
13542 // Next, clear the sign bit from the first operand (magnitude).
13543 // If it's a constant, we can clear it here.
13544 if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
13545 APFloat APF = Op0CN->getValueAPF();
13546 // If the magnitude is a positive zero, the sign bit alone is enough.
13547 if (APF.isPosZero())
13548 return IsF128 ? SignBit :
13549 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, SignBit,
13550 DAG.getIntPtrConstant(0, dl));
13552 CV[0] = ConstantFP::get(*Context, APF);
13554 CV[0] = ConstantFP::get(
13556 APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
13558 C = ConstantVector::get(CV);
13559 CPIdx = DAG.getConstantPool(C, PtrVT, 16);
13561 DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
13562 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13563 false, false, false, 16);
13564 // If the magnitude operand wasn't a constant, we need to AND out the sign.
13565 if (!isa<ConstantFPSDNode>(Op0)) {
13567 Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op0);
13568 Val = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op0, Val);
13570 // OR the magnitude value with the sign bit.
13571 Val = DAG.getNode(X86ISD::FOR, dl, LogicVT, Val, SignBit);
13572 return IsF128 ? Val :
13573 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, Val,
13574 DAG.getIntPtrConstant(0, dl));
13577 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
13578 SDValue N0 = Op.getOperand(0);
13580 MVT VT = Op.getSimpleValueType();
13582 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
13583 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
13584 DAG.getConstant(1, dl, VT));
13585 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
13588 // Check whether an OR'd tree is PTEST-able.
13589 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
13590 SelectionDAG &DAG) {
13591 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
13593 if (!Subtarget->hasSSE41())
13596 if (!Op->hasOneUse())
13599 SDNode *N = Op.getNode();
13602 SmallVector<SDValue, 8> Opnds;
13603 DenseMap<SDValue, unsigned> VecInMap;
13604 SmallVector<SDValue, 8> VecIns;
13605 EVT VT = MVT::Other;
13607 // Recognize a special case where a vector is casted into wide integer to
13609 Opnds.push_back(N->getOperand(0));
13610 Opnds.push_back(N->getOperand(1));
13612 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
13613 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
13614 // BFS traverse all OR'd operands.
13615 if (I->getOpcode() == ISD::OR) {
13616 Opnds.push_back(I->getOperand(0));
13617 Opnds.push_back(I->getOperand(1));
13618 // Re-evaluate the number of nodes to be traversed.
13619 e += 2; // 2 more nodes (LHS and RHS) are pushed.
13623 // Quit if a non-EXTRACT_VECTOR_ELT
13624 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13627 // Quit if without a constant index.
13628 SDValue Idx = I->getOperand(1);
13629 if (!isa<ConstantSDNode>(Idx))
13632 SDValue ExtractedFromVec = I->getOperand(0);
13633 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
13634 if (M == VecInMap.end()) {
13635 VT = ExtractedFromVec.getValueType();
13636 // Quit if not 128/256-bit vector.
13637 if (!VT.is128BitVector() && !VT.is256BitVector())
13639 // Quit if not the same type.
13640 if (VecInMap.begin() != VecInMap.end() &&
13641 VT != VecInMap.begin()->first.getValueType())
13643 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
13644 VecIns.push_back(ExtractedFromVec);
13646 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
13649 assert((VT.is128BitVector() || VT.is256BitVector()) &&
13650 "Not extracted from 128-/256-bit vector.");
13652 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
13654 for (DenseMap<SDValue, unsigned>::const_iterator
13655 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
13656 // Quit if not all elements are used.
13657 if (I->second != FullMask)
13661 MVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
13663 // Cast all vectors into TestVT for PTEST.
13664 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
13665 VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
13667 // If more than one full vectors are evaluated, OR them first before PTEST.
13668 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
13669 // Each iteration will OR 2 nodes and append the result until there is only
13670 // 1 node left, i.e. the final OR'd value of all vectors.
13671 SDValue LHS = VecIns[Slot];
13672 SDValue RHS = VecIns[Slot + 1];
13673 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
13676 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
13677 VecIns.back(), VecIns.back());
13680 /// \brief return true if \c Op has a use that doesn't just read flags.
13681 static bool hasNonFlagsUse(SDValue Op) {
13682 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
13684 SDNode *User = *UI;
13685 unsigned UOpNo = UI.getOperandNo();
13686 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
13687 // Look pass truncate.
13688 UOpNo = User->use_begin().getOperandNo();
13689 User = *User->use_begin();
13692 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
13693 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
13699 /// Emit nodes that will be selected as "test Op0,Op0", or something
13701 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
13702 SelectionDAG &DAG) const {
13703 if (Op.getValueType() == MVT::i1) {
13704 SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
13705 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
13706 DAG.getConstant(0, dl, MVT::i8));
13708 // CF and OF aren't always set the way we want. Determine which
13709 // of these we need.
13710 bool NeedCF = false;
13711 bool NeedOF = false;
13714 case X86::COND_A: case X86::COND_AE:
13715 case X86::COND_B: case X86::COND_BE:
13718 case X86::COND_G: case X86::COND_GE:
13719 case X86::COND_L: case X86::COND_LE:
13720 case X86::COND_O: case X86::COND_NO: {
13721 // Check if we really need to set the
13722 // Overflow flag. If NoSignedWrap is present
13723 // that is not actually needed.
13724 switch (Op->getOpcode()) {
13729 const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
13730 if (BinNode->Flags.hasNoSignedWrap())
13740 // See if we can use the EFLAGS value from the operand instead of
13741 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
13742 // we prove that the arithmetic won't overflow, we can't use OF or CF.
13743 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
13744 // Emit a CMP with 0, which is the TEST pattern.
13745 //if (Op.getValueType() == MVT::i1)
13746 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
13747 // DAG.getConstant(0, MVT::i1));
13748 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13749 DAG.getConstant(0, dl, Op.getValueType()));
13751 unsigned Opcode = 0;
13752 unsigned NumOperands = 0;
13754 // Truncate operations may prevent the merge of the SETCC instruction
13755 // and the arithmetic instruction before it. Attempt to truncate the operands
13756 // of the arithmetic instruction and use a reduced bit-width instruction.
13757 bool NeedTruncation = false;
13758 SDValue ArithOp = Op;
13759 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
13760 SDValue Arith = Op->getOperand(0);
13761 // Both the trunc and the arithmetic op need to have one user each.
13762 if (Arith->hasOneUse())
13763 switch (Arith.getOpcode()) {
13770 NeedTruncation = true;
13776 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
13777 // which may be the result of a CAST. We use the variable 'Op', which is the
13778 // non-casted variable when we check for possible users.
13779 switch (ArithOp.getOpcode()) {
13781 // Due to an isel shortcoming, be conservative if this add is likely to be
13782 // selected as part of a load-modify-store instruction. When the root node
13783 // in a match is a store, isel doesn't know how to remap non-chain non-flag
13784 // uses of other nodes in the match, such as the ADD in this case. This
13785 // leads to the ADD being left around and reselected, with the result being
13786 // two adds in the output. Alas, even if none our users are stores, that
13787 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
13788 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
13789 // climbing the DAG back to the root, and it doesn't seem to be worth the
13791 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13792 UE = Op.getNode()->use_end(); UI != UE; ++UI)
13793 if (UI->getOpcode() != ISD::CopyToReg &&
13794 UI->getOpcode() != ISD::SETCC &&
13795 UI->getOpcode() != ISD::STORE)
13798 if (ConstantSDNode *C =
13799 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
13800 // An add of one will be selected as an INC.
13801 if (C->isOne() && !Subtarget->slowIncDec()) {
13802 Opcode = X86ISD::INC;
13807 // An add of negative one (subtract of one) will be selected as a DEC.
13808 if (C->isAllOnesValue() && !Subtarget->slowIncDec()) {
13809 Opcode = X86ISD::DEC;
13815 // Otherwise use a regular EFLAGS-setting add.
13816 Opcode = X86ISD::ADD;
13821 // If we have a constant logical shift that's only used in a comparison
13822 // against zero turn it into an equivalent AND. This allows turning it into
13823 // a TEST instruction later.
13824 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
13825 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
13826 EVT VT = Op.getValueType();
13827 unsigned BitWidth = VT.getSizeInBits();
13828 unsigned ShAmt = Op->getConstantOperandVal(1);
13829 if (ShAmt >= BitWidth) // Avoid undefined shifts.
13831 APInt Mask = ArithOp.getOpcode() == ISD::SRL
13832 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
13833 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
13834 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
13836 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
13837 DAG.getConstant(Mask, dl, VT));
13838 DAG.ReplaceAllUsesWith(Op, New);
13844 // If the primary and result isn't used, don't bother using X86ISD::AND,
13845 // because a TEST instruction will be better.
13846 if (!hasNonFlagsUse(Op))
13852 // Due to the ISEL shortcoming noted above, be conservative if this op is
13853 // likely to be selected as part of a load-modify-store instruction.
13854 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13855 UE = Op.getNode()->use_end(); UI != UE; ++UI)
13856 if (UI->getOpcode() == ISD::STORE)
13859 // Otherwise use a regular EFLAGS-setting instruction.
13860 switch (ArithOp.getOpcode()) {
13861 default: llvm_unreachable("unexpected operator!");
13862 case ISD::SUB: Opcode = X86ISD::SUB; break;
13863 case ISD::XOR: Opcode = X86ISD::XOR; break;
13864 case ISD::AND: Opcode = X86ISD::AND; break;
13866 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
13867 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
13868 if (EFLAGS.getNode())
13871 Opcode = X86ISD::OR;
13885 return SDValue(Op.getNode(), 1);
13891 // If we found that truncation is beneficial, perform the truncation and
13893 if (NeedTruncation) {
13894 EVT VT = Op.getValueType();
13895 SDValue WideVal = Op->getOperand(0);
13896 EVT WideVT = WideVal.getValueType();
13897 unsigned ConvertedOp = 0;
13898 // Use a target machine opcode to prevent further DAGCombine
13899 // optimizations that may separate the arithmetic operations
13900 // from the setcc node.
13901 switch (WideVal.getOpcode()) {
13903 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
13904 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
13905 case ISD::AND: ConvertedOp = X86ISD::AND; break;
13906 case ISD::OR: ConvertedOp = X86ISD::OR; break;
13907 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
13911 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13912 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
13913 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
13914 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
13915 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
13921 // Emit a CMP with 0, which is the TEST pattern.
13922 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13923 DAG.getConstant(0, dl, Op.getValueType()));
13925 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
13926 SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
13928 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
13929 DAG.ReplaceAllUsesWith(Op, New);
13930 return SDValue(New.getNode(), 1);
13933 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
13935 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
13936 SDLoc dl, SelectionDAG &DAG) const {
13937 if (isNullConstant(Op1))
13938 return EmitTest(Op0, X86CC, dl, DAG);
13940 assert(!(isa<ConstantSDNode>(Op1) && Op0.getValueType() == MVT::i1) &&
13941 "Unexpected comparison operation for MVT::i1 operands");
13943 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
13944 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
13945 // Do the comparison at i32 if it's smaller, besides the Atom case.
13946 // This avoids subregister aliasing issues. Keep the smaller reference
13947 // if we're optimizing for size, however, as that'll allow better folding
13948 // of memory operations.
13949 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
13950 !DAG.getMachineFunction().getFunction()->optForMinSize() &&
13951 !Subtarget->isAtom()) {
13952 unsigned ExtendOp =
13953 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
13954 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
13955 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
13957 // Use SUB instead of CMP to enable CSE between SUB and CMP.
13958 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
13959 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
13961 return SDValue(Sub.getNode(), 1);
13963 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
13966 /// Convert a comparison if required by the subtarget.
13967 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
13968 SelectionDAG &DAG) const {
13969 // If the subtarget does not support the FUCOMI instruction, floating-point
13970 // comparisons have to be converted.
13971 if (Subtarget->hasCMov() ||
13972 Cmp.getOpcode() != X86ISD::CMP ||
13973 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
13974 !Cmp.getOperand(1).getValueType().isFloatingPoint())
13977 // The instruction selector will select an FUCOM instruction instead of
13978 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
13979 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
13980 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
13982 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
13983 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
13984 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
13985 DAG.getConstant(8, dl, MVT::i8));
13986 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
13988 // Some 64-bit targets lack SAHF support, but they do support FCOMI.
13989 assert(Subtarget->hasLAHFSAHF() && "Target doesn't support SAHF or FCOMI?");
13990 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
13993 /// The minimum architected relative accuracy is 2^-12. We need one
13994 /// Newton-Raphson step to have a good float result (24 bits of precision).
13995 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
13996 DAGCombinerInfo &DCI,
13997 unsigned &RefinementSteps,
13998 bool &UseOneConstNR) const {
13999 EVT VT = Op.getValueType();
14000 const char *RecipOp;
14002 // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
14003 // TODO: Add support for AVX512 (v16f32).
14004 // It is likely not profitable to do this for f64 because a double-precision
14005 // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
14006 // instructions: convert to single, rsqrtss, convert back to double, refine
14007 // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
14008 // along with FMA, this could be a throughput win.
14009 if (VT == MVT::f32 && Subtarget->hasSSE1())
14011 else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
14012 (VT == MVT::v8f32 && Subtarget->hasAVX()))
14013 RecipOp = "vec-sqrtf";
14017 TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
14018 if (!Recips.isEnabled(RecipOp))
14021 RefinementSteps = Recips.getRefinementSteps(RecipOp);
14022 UseOneConstNR = false;
14023 return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
14026 /// The minimum architected relative accuracy is 2^-12. We need one
14027 /// Newton-Raphson step to have a good float result (24 bits of precision).
14028 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
14029 DAGCombinerInfo &DCI,
14030 unsigned &RefinementSteps) const {
14031 EVT VT = Op.getValueType();
14032 const char *RecipOp;
14034 // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
14035 // TODO: Add support for AVX512 (v16f32).
14036 // It is likely not profitable to do this for f64 because a double-precision
14037 // reciprocal estimate with refinement on x86 prior to FMA requires
14038 // 15 instructions: convert to single, rcpss, convert back to double, refine
14039 // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
14040 // along with FMA, this could be a throughput win.
14041 if (VT == MVT::f32 && Subtarget->hasSSE1())
14043 else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
14044 (VT == MVT::v8f32 && Subtarget->hasAVX()))
14045 RecipOp = "vec-divf";
14049 TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
14050 if (!Recips.isEnabled(RecipOp))
14053 RefinementSteps = Recips.getRefinementSteps(RecipOp);
14054 return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
14057 /// If we have at least two divisions that use the same divisor, convert to
14058 /// multplication by a reciprocal. This may need to be adjusted for a given
14059 /// CPU if a division's cost is not at least twice the cost of a multiplication.
14060 /// This is because we still need one division to calculate the reciprocal and
14061 /// then we need two multiplies by that reciprocal as replacements for the
14062 /// original divisions.
14063 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
14067 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
14068 /// if it's possible.
14069 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
14070 SDLoc dl, SelectionDAG &DAG) const {
14071 SDValue Op0 = And.getOperand(0);
14072 SDValue Op1 = And.getOperand(1);
14073 if (Op0.getOpcode() == ISD::TRUNCATE)
14074 Op0 = Op0.getOperand(0);
14075 if (Op1.getOpcode() == ISD::TRUNCATE)
14076 Op1 = Op1.getOperand(0);
14079 if (Op1.getOpcode() == ISD::SHL)
14080 std::swap(Op0, Op1);
14081 if (Op0.getOpcode() == ISD::SHL) {
14082 if (isOneConstant(Op0.getOperand(0))) {
14083 // If we looked past a truncate, check that it's only truncating away
14085 unsigned BitWidth = Op0.getValueSizeInBits();
14086 unsigned AndBitWidth = And.getValueSizeInBits();
14087 if (BitWidth > AndBitWidth) {
14089 DAG.computeKnownBits(Op0, Zeros, Ones);
14090 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
14094 RHS = Op0.getOperand(1);
14096 } else if (Op1.getOpcode() == ISD::Constant) {
14097 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
14098 uint64_t AndRHSVal = AndRHS->getZExtValue();
14099 SDValue AndLHS = Op0;
14101 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
14102 LHS = AndLHS.getOperand(0);
14103 RHS = AndLHS.getOperand(1);
14106 // Use BT if the immediate can't be encoded in a TEST instruction.
14107 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
14109 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
14113 if (LHS.getNode()) {
14114 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
14115 // instruction. Since the shift amount is in-range-or-undefined, we know
14116 // that doing a bittest on the i32 value is ok. We extend to i32 because
14117 // the encoding for the i16 version is larger than the i32 version.
14118 // Also promote i16 to i32 for performance / code size reason.
14119 if (LHS.getValueType() == MVT::i8 ||
14120 LHS.getValueType() == MVT::i16)
14121 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
14123 // If the operand types disagree, extend the shift amount to match. Since
14124 // BT ignores high bits (like shifts) we can use anyextend.
14125 if (LHS.getValueType() != RHS.getValueType())
14126 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
14128 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
14129 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
14130 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14131 DAG.getConstant(Cond, dl, MVT::i8), BT);
14137 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
14139 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
14144 // SSE Condition code mapping:
14153 switch (SetCCOpcode) {
14154 default: llvm_unreachable("Unexpected SETCC condition");
14156 case ISD::SETEQ: SSECC = 0; break;
14158 case ISD::SETGT: Swap = true; // Fallthrough
14160 case ISD::SETOLT: SSECC = 1; break;
14162 case ISD::SETGE: Swap = true; // Fallthrough
14164 case ISD::SETOLE: SSECC = 2; break;
14165 case ISD::SETUO: SSECC = 3; break;
14167 case ISD::SETNE: SSECC = 4; break;
14168 case ISD::SETULE: Swap = true; // Fallthrough
14169 case ISD::SETUGE: SSECC = 5; break;
14170 case ISD::SETULT: Swap = true; // Fallthrough
14171 case ISD::SETUGT: SSECC = 6; break;
14172 case ISD::SETO: SSECC = 7; break;
14174 case ISD::SETONE: SSECC = 8; break;
14177 std::swap(Op0, Op1);
14182 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
14183 // ones, and then concatenate the result back.
14184 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
14185 MVT VT = Op.getSimpleValueType();
14187 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
14188 "Unsupported value type for operation");
14190 unsigned NumElems = VT.getVectorNumElements();
14192 SDValue CC = Op.getOperand(2);
14194 // Extract the LHS vectors
14195 SDValue LHS = Op.getOperand(0);
14196 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14197 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14199 // Extract the RHS vectors
14200 SDValue RHS = Op.getOperand(1);
14201 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
14202 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
14204 // Issue the operation on the smaller types and concatenate the result back
14205 MVT EltVT = VT.getVectorElementType();
14206 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14207 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
14208 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
14209 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
14212 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
14213 SDValue Op0 = Op.getOperand(0);
14214 SDValue Op1 = Op.getOperand(1);
14215 SDValue CC = Op.getOperand(2);
14216 MVT VT = Op.getSimpleValueType();
14219 assert(Op0.getSimpleValueType().getVectorElementType() == MVT::i1 &&
14220 "Unexpected type for boolean compare operation");
14221 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14222 SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
14223 DAG.getConstant(-1, dl, VT));
14224 SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
14225 DAG.getConstant(-1, dl, VT));
14226 switch (SetCCOpcode) {
14227 default: llvm_unreachable("Unexpected SETCC condition");
14229 // (x == y) -> ~(x ^ y)
14230 return DAG.getNode(ISD::XOR, dl, VT,
14231 DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
14232 DAG.getConstant(-1, dl, VT));
14234 // (x != y) -> (x ^ y)
14235 return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
14238 // (x > y) -> (x & ~y)
14239 return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
14242 // (x < y) -> (~x & y)
14243 return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
14246 // (x <= y) -> (~x | y)
14247 return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
14250 // (x >=y) -> (x | ~y)
14251 return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
14255 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
14256 const X86Subtarget *Subtarget) {
14257 SDValue Op0 = Op.getOperand(0);
14258 SDValue Op1 = Op.getOperand(1);
14259 SDValue CC = Op.getOperand(2);
14260 MVT VT = Op.getSimpleValueType();
14263 assert(Op0.getSimpleValueType().getVectorElementType().getSizeInBits() >= 8 &&
14264 Op.getSimpleValueType().getVectorElementType() == MVT::i1 &&
14265 "Cannot set masked compare for this operation");
14267 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14269 bool Unsigned = false;
14272 switch (SetCCOpcode) {
14273 default: llvm_unreachable("Unexpected SETCC condition");
14274 case ISD::SETNE: SSECC = 4; break;
14275 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
14276 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
14277 case ISD::SETLT: Swap = true; //fall-through
14278 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
14279 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
14280 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
14281 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
14282 case ISD::SETULE: Unsigned = true; //fall-through
14283 case ISD::SETLE: SSECC = 2; break;
14287 std::swap(Op0, Op1);
14289 return DAG.getNode(Opc, dl, VT, Op0, Op1);
14290 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
14291 return DAG.getNode(Opc, dl, VT, Op0, Op1,
14292 DAG.getConstant(SSECC, dl, MVT::i8));
14295 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
14296 /// operand \p Op1. If non-trivial (for example because it's not constant)
14297 /// return an empty value.
14298 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
14300 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
14304 MVT VT = Op1.getSimpleValueType();
14305 MVT EVT = VT.getVectorElementType();
14306 unsigned n = VT.getVectorNumElements();
14307 SmallVector<SDValue, 8> ULTOp1;
14309 for (unsigned i = 0; i < n; ++i) {
14310 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
14311 if (!Elt || Elt->isOpaque() || Elt->getSimpleValueType(0) != EVT)
14314 // Avoid underflow.
14315 APInt Val = Elt->getAPIntValue();
14319 ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
14322 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
14325 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
14326 SelectionDAG &DAG) {
14327 SDValue Op0 = Op.getOperand(0);
14328 SDValue Op1 = Op.getOperand(1);
14329 SDValue CC = Op.getOperand(2);
14330 MVT VT = Op.getSimpleValueType();
14331 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
14332 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
14337 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
14338 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
14341 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
14342 unsigned Opc = X86ISD::CMPP;
14343 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
14344 assert(VT.getVectorNumElements() <= 16);
14345 Opc = X86ISD::CMPM;
14347 // In the two special cases we can't handle, emit two comparisons.
14350 unsigned CombineOpc;
14351 if (SetCCOpcode == ISD::SETUEQ) {
14352 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
14354 assert(SetCCOpcode == ISD::SETONE);
14355 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
14358 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14359 DAG.getConstant(CC0, dl, MVT::i8));
14360 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
14361 DAG.getConstant(CC1, dl, MVT::i8));
14362 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
14364 // Handle all other FP comparisons here.
14365 return DAG.getNode(Opc, dl, VT, Op0, Op1,
14366 DAG.getConstant(SSECC, dl, MVT::i8));
14369 MVT VTOp0 = Op0.getSimpleValueType();
14370 assert(VTOp0 == Op1.getSimpleValueType() &&
14371 "Expected operands with same type!");
14372 assert(VT.getVectorNumElements() == VTOp0.getVectorNumElements() &&
14373 "Invalid number of packed elements for source and destination!");
14375 if (VT.is128BitVector() && VTOp0.is256BitVector()) {
14376 // On non-AVX512 targets, a vector of MVT::i1 is promoted by the type
14377 // legalizer to a wider vector type. In the case of 'vsetcc' nodes, the
14378 // legalizer firstly checks if the first operand in input to the setcc has
14379 // a legal type. If so, then it promotes the return type to that same type.
14380 // Otherwise, the return type is promoted to the 'next legal type' which,
14381 // for a vector of MVT::i1 is always a 128-bit integer vector type.
14383 // We reach this code only if the following two conditions are met:
14384 // 1. Both return type and operand type have been promoted to wider types
14385 // by the type legalizer.
14386 // 2. The original operand type has been promoted to a 256-bit vector.
14388 // Note that condition 2. only applies for AVX targets.
14389 SDValue NewOp = DAG.getSetCC(dl, VTOp0, Op0, Op1, SetCCOpcode);
14390 return DAG.getZExtOrTrunc(NewOp, dl, VT);
14393 // The non-AVX512 code below works under the assumption that source and
14394 // destination types are the same.
14395 assert((Subtarget->hasAVX512() || (VT == VTOp0)) &&
14396 "Value types for source and destination must be the same!");
14398 // Break 256-bit integer vector compare into smaller ones.
14399 if (VT.is256BitVector() && !Subtarget->hasInt256())
14400 return Lower256IntVSETCC(Op, DAG);
14402 MVT OpVT = Op1.getSimpleValueType();
14403 if (OpVT.getVectorElementType() == MVT::i1)
14404 return LowerBoolVSETCC_AVX512(Op, DAG);
14406 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
14407 if (Subtarget->hasAVX512()) {
14408 if (Op1.getSimpleValueType().is512BitVector() ||
14409 (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
14410 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
14411 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
14413 // In AVX-512 architecture setcc returns mask with i1 elements,
14414 // But there is no compare instruction for i8 and i16 elements in KNL.
14415 // We are not talking about 512-bit operands in this case, these
14416 // types are illegal.
14418 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
14419 OpVT.getVectorElementType().getSizeInBits() >= 8))
14420 return DAG.getNode(ISD::TRUNCATE, dl, VT,
14421 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
14424 // Lower using XOP integer comparisons.
14425 if ((VT == MVT::v16i8 || VT == MVT::v8i16 ||
14426 VT == MVT::v4i32 || VT == MVT::v2i64) && Subtarget->hasXOP()) {
14427 // Translate compare code to XOP PCOM compare mode.
14428 unsigned CmpMode = 0;
14429 switch (SetCCOpcode) {
14430 default: llvm_unreachable("Unexpected SETCC condition");
14432 case ISD::SETLT: CmpMode = 0x00; break;
14434 case ISD::SETLE: CmpMode = 0x01; break;
14436 case ISD::SETGT: CmpMode = 0x02; break;
14438 case ISD::SETGE: CmpMode = 0x03; break;
14439 case ISD::SETEQ: CmpMode = 0x04; break;
14440 case ISD::SETNE: CmpMode = 0x05; break;
14443 // Are we comparing unsigned or signed integers?
14444 unsigned Opc = ISD::isUnsignedIntSetCC(SetCCOpcode)
14445 ? X86ISD::VPCOMU : X86ISD::VPCOM;
14447 return DAG.getNode(Opc, dl, VT, Op0, Op1,
14448 DAG.getConstant(CmpMode, dl, MVT::i8));
14451 // We are handling one of the integer comparisons here. Since SSE only has
14452 // GT and EQ comparisons for integer, swapping operands and multiple
14453 // operations may be required for some comparisons.
14455 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
14456 bool Subus = false;
14458 switch (SetCCOpcode) {
14459 default: llvm_unreachable("Unexpected SETCC condition");
14460 case ISD::SETNE: Invert = true;
14461 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
14462 case ISD::SETLT: Swap = true;
14463 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
14464 case ISD::SETGE: Swap = true;
14465 case ISD::SETLE: Opc = X86ISD::PCMPGT;
14466 Invert = true; break;
14467 case ISD::SETULT: Swap = true;
14468 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
14469 FlipSigns = true; break;
14470 case ISD::SETUGE: Swap = true;
14471 case ISD::SETULE: Opc = X86ISD::PCMPGT;
14472 FlipSigns = true; Invert = true; break;
14475 // Special case: Use min/max operations for SETULE/SETUGE
14476 MVT VET = VT.getVectorElementType();
14478 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
14479 || (Subtarget->hasSSE2() && (VET == MVT::i8));
14482 switch (SetCCOpcode) {
14484 case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
14485 case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
14488 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
14491 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
14492 if (!MinMax && hasSubus) {
14493 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
14495 // t = psubus Op0, Op1
14496 // pcmpeq t, <0..0>
14497 switch (SetCCOpcode) {
14499 case ISD::SETULT: {
14500 // If the comparison is against a constant we can turn this into a
14501 // setule. With psubus, setule does not require a swap. This is
14502 // beneficial because the constant in the register is no longer
14503 // destructed as the destination so it can be hoisted out of a loop.
14504 // Only do this pre-AVX since vpcmp* is no longer destructive.
14505 if (Subtarget->hasAVX())
14507 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
14508 if (ULEOp1.getNode()) {
14510 Subus = true; Invert = false; Swap = false;
14514 // Psubus is better than flip-sign because it requires no inversion.
14515 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
14516 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
14520 Opc = X86ISD::SUBUS;
14526 std::swap(Op0, Op1);
14528 // Check that the operation in question is available (most are plain SSE2,
14529 // but PCMPGTQ and PCMPEQQ have different requirements).
14530 if (VT == MVT::v2i64) {
14531 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
14532 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
14534 // First cast everything to the right type.
14535 Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14536 Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14538 // Since SSE has no unsigned integer comparisons, we need to flip the sign
14539 // bits of the inputs before performing those operations. The lower
14540 // compare is always unsigned.
14543 SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
14545 SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
14546 SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
14547 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
14548 Sign, Zero, Sign, Zero);
14550 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
14551 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
14553 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
14554 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
14555 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
14557 // Create masks for only the low parts/high parts of the 64 bit integers.
14558 static const int MaskHi[] = { 1, 1, 3, 3 };
14559 static const int MaskLo[] = { 0, 0, 2, 2 };
14560 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
14561 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
14562 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
14564 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
14565 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
14568 Result = DAG.getNOT(dl, Result, MVT::v4i32);
14570 return DAG.getBitcast(VT, Result);
14573 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
14574 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
14575 // pcmpeqd + pshufd + pand.
14576 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
14578 // First cast everything to the right type.
14579 Op0 = DAG.getBitcast(MVT::v4i32, Op0);
14580 Op1 = DAG.getBitcast(MVT::v4i32, Op1);
14583 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
14585 // Make sure the lower and upper halves are both all-ones.
14586 static const int Mask[] = { 1, 0, 3, 2 };
14587 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
14588 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
14591 Result = DAG.getNOT(dl, Result, MVT::v4i32);
14593 return DAG.getBitcast(VT, Result);
14597 // Since SSE has no unsigned integer comparisons, we need to flip the sign
14598 // bits of the inputs before performing those operations.
14600 MVT EltVT = VT.getVectorElementType();
14601 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
14603 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
14604 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
14607 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
14609 // If the logical-not of the result is required, perform that now.
14611 Result = DAG.getNOT(dl, Result, VT);
14614 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
14617 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
14618 getZeroVector(VT, Subtarget, DAG, dl));
14623 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
14625 MVT VT = Op.getSimpleValueType();
14627 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
14629 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
14630 && "SetCC type must be 8-bit or 1-bit integer");
14631 SDValue Op0 = Op.getOperand(0);
14632 SDValue Op1 = Op.getOperand(1);
14634 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
14636 // Optimize to BT if possible.
14637 // Lower (X & (1 << N)) == 0 to BT(X, N).
14638 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
14639 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
14640 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
14641 isNullConstant(Op1) &&
14642 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14643 if (SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG)) {
14645 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
14650 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
14652 if ((isOneConstant(Op1) || isNullConstant(Op1)) &&
14653 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14655 // If the input is a setcc, then reuse the input setcc or use a new one with
14656 // the inverted condition.
14657 if (Op0.getOpcode() == X86ISD::SETCC) {
14658 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
14659 bool Invert = (CC == ISD::SETNE) ^ isNullConstant(Op1);
14663 CCode = X86::GetOppositeBranchCondition(CCode);
14664 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14665 DAG.getConstant(CCode, dl, MVT::i8),
14666 Op0.getOperand(1));
14668 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14672 if ((Op0.getValueType() == MVT::i1) && isOneConstant(Op1) &&
14673 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14675 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
14676 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
14679 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
14680 unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
14681 if (X86CC == X86::COND_INVALID)
14684 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
14685 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
14686 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14687 DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
14689 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14693 SDValue X86TargetLowering::LowerSETCCE(SDValue Op, SelectionDAG &DAG) const {
14694 SDValue LHS = Op.getOperand(0);
14695 SDValue RHS = Op.getOperand(1);
14696 SDValue Carry = Op.getOperand(2);
14697 SDValue Cond = Op.getOperand(3);
14700 assert(LHS.getSimpleValueType().isInteger() && "SETCCE is integer only.");
14701 X86::CondCode CC = TranslateIntegerX86CC(cast<CondCodeSDNode>(Cond)->get());
14703 assert(Carry.getOpcode() != ISD::CARRY_FALSE);
14704 SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14705 SDValue Cmp = DAG.getNode(X86ISD::SBB, DL, VTs, LHS, RHS, Carry);
14706 return DAG.getNode(X86ISD::SETCC, DL, Op.getValueType(),
14707 DAG.getConstant(CC, DL, MVT::i8), Cmp.getValue(1));
14710 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
14711 static bool isX86LogicalCmp(SDValue Op) {
14712 unsigned Opc = Op.getNode()->getOpcode();
14713 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
14714 Opc == X86ISD::SAHF)
14716 if (Op.getResNo() == 1 &&
14717 (Opc == X86ISD::ADD ||
14718 Opc == X86ISD::SUB ||
14719 Opc == X86ISD::ADC ||
14720 Opc == X86ISD::SBB ||
14721 Opc == X86ISD::SMUL ||
14722 Opc == X86ISD::UMUL ||
14723 Opc == X86ISD::INC ||
14724 Opc == X86ISD::DEC ||
14725 Opc == X86ISD::OR ||
14726 Opc == X86ISD::XOR ||
14727 Opc == X86ISD::AND))
14730 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
14736 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
14737 if (V.getOpcode() != ISD::TRUNCATE)
14740 SDValue VOp0 = V.getOperand(0);
14741 unsigned InBits = VOp0.getValueSizeInBits();
14742 unsigned Bits = V.getValueSizeInBits();
14743 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
14746 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
14747 bool addTest = true;
14748 SDValue Cond = Op.getOperand(0);
14749 SDValue Op1 = Op.getOperand(1);
14750 SDValue Op2 = Op.getOperand(2);
14752 MVT VT = Op1.getSimpleValueType();
14755 // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
14756 // are available or VBLENDV if AVX is available.
14757 // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
14758 if (Cond.getOpcode() == ISD::SETCC &&
14759 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
14760 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
14761 VT == Cond.getOperand(0).getSimpleValueType() && Cond->hasOneUse()) {
14762 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
14763 int SSECC = translateX86FSETCC(
14764 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
14767 if (Subtarget->hasAVX512()) {
14768 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
14769 DAG.getConstant(SSECC, DL, MVT::i8));
14770 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
14773 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
14774 DAG.getConstant(SSECC, DL, MVT::i8));
14776 // If we have AVX, we can use a variable vector select (VBLENDV) instead
14777 // of 3 logic instructions for size savings and potentially speed.
14778 // Unfortunately, there is no scalar form of VBLENDV.
14780 // If either operand is a constant, don't try this. We can expect to
14781 // optimize away at least one of the logic instructions later in that
14782 // case, so that sequence would be faster than a variable blend.
14784 // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
14785 // uses XMM0 as the selection register. That may need just as many
14786 // instructions as the AND/ANDN/OR sequence due to register moves, so
14789 if (Subtarget->hasAVX() &&
14790 !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
14792 // Convert to vectors, do a VSELECT, and convert back to scalar.
14793 // All of the conversions should be optimized away.
14795 MVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
14796 SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
14797 SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
14798 SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
14800 MVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
14801 VCmp = DAG.getBitcast(VCmpVT, VCmp);
14803 SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
14805 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
14806 VSel, DAG.getIntPtrConstant(0, DL));
14808 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
14809 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
14810 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
14814 if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
14816 if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
14817 Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
14818 else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
14819 Op1Scalar = Op1.getOperand(0);
14821 if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
14822 Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
14823 else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
14824 Op2Scalar = Op2.getOperand(0);
14825 if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
14826 SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
14827 Op1Scalar.getValueType(),
14828 Cond, Op1Scalar, Op2Scalar);
14829 if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
14830 return DAG.getBitcast(VT, newSelect);
14831 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
14832 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
14833 DAG.getIntPtrConstant(0, DL));
14837 if (VT == MVT::v4i1 || VT == MVT::v2i1) {
14838 SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
14839 Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14840 DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
14841 Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14842 DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
14843 SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
14845 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
14848 if (Cond.getOpcode() == ISD::SETCC) {
14849 SDValue NewCond = LowerSETCC(Cond, DAG);
14850 if (NewCond.getNode())
14854 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
14855 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
14856 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
14857 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
14858 if (Cond.getOpcode() == X86ISD::SETCC &&
14859 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
14860 isNullConstant(Cond.getOperand(1).getOperand(1))) {
14861 SDValue Cmp = Cond.getOperand(1);
14863 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
14865 if ((isAllOnesConstant(Op1) || isAllOnesConstant(Op2)) &&
14866 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
14867 SDValue Y = isAllOnesConstant(Op2) ? Op1 : Op2;
14869 SDValue CmpOp0 = Cmp.getOperand(0);
14870 // Apply further optimizations for special cases
14871 // (select (x != 0), -1, 0) -> neg & sbb
14872 // (select (x == 0), 0, -1) -> neg & sbb
14873 if (isNullConstant(Y) &&
14874 (isAllOnesConstant(Op1) == (CondCode == X86::COND_NE))) {
14875 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
14876 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
14877 DAG.getConstant(0, DL,
14878 CmpOp0.getValueType()),
14880 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14881 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14882 SDValue(Neg.getNode(), 1));
14886 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
14887 CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
14888 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14890 SDValue Res = // Res = 0 or -1.
14891 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14892 DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
14894 if (isAllOnesConstant(Op1) != (CondCode == X86::COND_E))
14895 Res = DAG.getNOT(DL, Res, Res.getValueType());
14897 if (!isNullConstant(Op2))
14898 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
14903 // Look past (and (setcc_carry (cmp ...)), 1).
14904 if (Cond.getOpcode() == ISD::AND &&
14905 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY &&
14906 isOneConstant(Cond.getOperand(1)))
14907 Cond = Cond.getOperand(0);
14909 // If condition flag is set by a X86ISD::CMP, then use it as the condition
14910 // setting operand in place of the X86ISD::SETCC.
14911 unsigned CondOpcode = Cond.getOpcode();
14912 if (CondOpcode == X86ISD::SETCC ||
14913 CondOpcode == X86ISD::SETCC_CARRY) {
14914 CC = Cond.getOperand(0);
14916 SDValue Cmp = Cond.getOperand(1);
14917 unsigned Opc = Cmp.getOpcode();
14918 MVT VT = Op.getSimpleValueType();
14920 bool IllegalFPCMov = false;
14921 if (VT.isFloatingPoint() && !VT.isVector() &&
14922 !isScalarFPTypeInSSEReg(VT)) // FPStack?
14923 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
14925 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
14926 Opc == X86ISD::BT) { // FIXME
14930 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14931 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14932 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14933 Cond.getOperand(0).getValueType() != MVT::i8)) {
14934 SDValue LHS = Cond.getOperand(0);
14935 SDValue RHS = Cond.getOperand(1);
14936 unsigned X86Opcode;
14939 switch (CondOpcode) {
14940 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14941 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14942 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14943 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14944 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14945 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14946 default: llvm_unreachable("unexpected overflowing operator");
14948 if (CondOpcode == ISD::UMULO)
14949 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14952 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14954 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
14956 if (CondOpcode == ISD::UMULO)
14957 Cond = X86Op.getValue(2);
14959 Cond = X86Op.getValue(1);
14961 CC = DAG.getConstant(X86Cond, DL, MVT::i8);
14966 // Look past the truncate if the high bits are known zero.
14967 if (isTruncWithZeroHighBitsInput(Cond, DAG))
14968 Cond = Cond.getOperand(0);
14970 // We know the result of AND is compared against zero. Try to match
14972 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14973 if (SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG)) {
14974 CC = NewSetCC.getOperand(0);
14975 Cond = NewSetCC.getOperand(1);
14982 CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
14983 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
14986 // a < b ? -1 : 0 -> RES = ~setcc_carry
14987 // a < b ? 0 : -1 -> RES = setcc_carry
14988 // a >= b ? -1 : 0 -> RES = setcc_carry
14989 // a >= b ? 0 : -1 -> RES = ~setcc_carry
14990 if (Cond.getOpcode() == X86ISD::SUB) {
14991 Cond = ConvertCmpIfNecessary(Cond, DAG);
14992 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
14994 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
14995 (isAllOnesConstant(Op1) || isAllOnesConstant(Op2)) &&
14996 (isNullConstant(Op1) || isNullConstant(Op2))) {
14997 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14998 DAG.getConstant(X86::COND_B, DL, MVT::i8),
15000 if (isAllOnesConstant(Op1) != (CondCode == X86::COND_B))
15001 return DAG.getNOT(DL, Res, Res.getValueType());
15006 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
15007 // widen the cmov and push the truncate through. This avoids introducing a new
15008 // branch during isel and doesn't add any extensions.
15009 if (Op.getValueType() == MVT::i8 &&
15010 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
15011 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
15012 if (T1.getValueType() == T2.getValueType() &&
15013 // Blacklist CopyFromReg to avoid partial register stalls.
15014 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
15015 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
15016 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
15017 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
15021 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
15022 // condition is true.
15023 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
15024 SDValue Ops[] = { Op2, Op1, CC, Cond };
15025 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
15028 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
15029 const X86Subtarget *Subtarget,
15030 SelectionDAG &DAG) {
15031 MVT VT = Op->getSimpleValueType(0);
15032 SDValue In = Op->getOperand(0);
15033 MVT InVT = In.getSimpleValueType();
15034 MVT VTElt = VT.getVectorElementType();
15035 MVT InVTElt = InVT.getVectorElementType();
15039 if ((InVTElt == MVT::i1) &&
15040 (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
15041 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
15043 ((Subtarget->hasBWI() && VT.is512BitVector() &&
15044 VTElt.getSizeInBits() <= 16)) ||
15046 ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
15047 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
15049 ((Subtarget->hasDQI() && VT.is512BitVector() &&
15050 VTElt.getSizeInBits() >= 32))))
15051 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15053 unsigned int NumElts = VT.getVectorNumElements();
15055 if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
15058 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
15059 if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
15060 return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
15061 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15064 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
15065 MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
15067 DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
15070 DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
15072 SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
15073 if (VT.is512BitVector())
15075 return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
15078 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
15079 const X86Subtarget *Subtarget,
15080 SelectionDAG &DAG) {
15081 SDValue In = Op->getOperand(0);
15082 MVT VT = Op->getSimpleValueType(0);
15083 MVT InVT = In.getSimpleValueType();
15084 assert(VT.getSizeInBits() == InVT.getSizeInBits());
15086 MVT InSVT = InVT.getVectorElementType();
15087 assert(VT.getVectorElementType().getSizeInBits() > InSVT.getSizeInBits());
15089 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
15091 if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
15096 // SSE41 targets can use the pmovsx* instructions directly.
15097 if (Subtarget->hasSSE41())
15098 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15100 // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
15104 // As SRAI is only available on i16/i32 types, we expand only up to i32
15105 // and handle i64 separately.
15106 while (CurrVT != VT && CurrVT.getVectorElementType() != MVT::i32) {
15107 Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
15108 MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
15109 CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
15110 Curr = DAG.getBitcast(CurrVT, Curr);
15113 SDValue SignExt = Curr;
15114 if (CurrVT != InVT) {
15115 unsigned SignExtShift =
15116 CurrVT.getVectorElementType().getSizeInBits() - InSVT.getSizeInBits();
15117 SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
15118 DAG.getConstant(SignExtShift, dl, MVT::i8));
15124 if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
15125 SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
15126 DAG.getConstant(31, dl, MVT::i8));
15127 SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
15128 return DAG.getBitcast(VT, Ext);
15134 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
15135 SelectionDAG &DAG) {
15136 MVT VT = Op->getSimpleValueType(0);
15137 SDValue In = Op->getOperand(0);
15138 MVT InVT = In.getSimpleValueType();
15141 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
15142 return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
15144 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
15145 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
15146 (VT != MVT::v16i16 || InVT != MVT::v16i8))
15149 if (Subtarget->hasInt256())
15150 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
15152 // Optimize vectors in AVX mode
15153 // Sign extend v8i16 to v8i32 and
15156 // Divide input vector into two parts
15157 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15158 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15159 // concat the vectors to original VT
15161 unsigned NumElems = InVT.getVectorNumElements();
15162 SDValue Undef = DAG.getUNDEF(InVT);
15164 SmallVector<int,8> ShufMask1(NumElems, -1);
15165 for (unsigned i = 0; i != NumElems/2; ++i)
15168 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
15170 SmallVector<int,8> ShufMask2(NumElems, -1);
15171 for (unsigned i = 0; i != NumElems/2; ++i)
15172 ShufMask2[i] = i + NumElems/2;
15174 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
15176 MVT HalfVT = MVT::getVectorVT(VT.getVectorElementType(),
15177 VT.getVectorNumElements()/2);
15179 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
15180 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
15182 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15185 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
15186 // may emit an illegal shuffle but the expansion is still better than scalar
15187 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
15188 // we'll emit a shuffle and a arithmetic shift.
15189 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
15190 // TODO: It is possible to support ZExt by zeroing the undef values during
15191 // the shuffle phase or after the shuffle.
15192 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
15193 SelectionDAG &DAG) {
15194 MVT RegVT = Op.getSimpleValueType();
15195 assert(RegVT.isVector() && "We only custom lower vector sext loads.");
15196 assert(RegVT.isInteger() &&
15197 "We only custom lower integer vector sext loads.");
15199 // Nothing useful we can do without SSE2 shuffles.
15200 assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
15202 LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
15204 EVT MemVT = Ld->getMemoryVT();
15205 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15206 unsigned RegSz = RegVT.getSizeInBits();
15208 ISD::LoadExtType Ext = Ld->getExtensionType();
15210 assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
15211 && "Only anyext and sext are currently implemented.");
15212 assert(MemVT != RegVT && "Cannot extend to the same type");
15213 assert(MemVT.isVector() && "Must load a vector from memory");
15215 unsigned NumElems = RegVT.getVectorNumElements();
15216 unsigned MemSz = MemVT.getSizeInBits();
15217 assert(RegSz > MemSz && "Register size must be greater than the mem size");
15219 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
15220 // The only way in which we have a legal 256-bit vector result but not the
15221 // integer 256-bit operations needed to directly lower a sextload is if we
15222 // have AVX1 but not AVX2. In that case, we can always emit a sextload to
15223 // a 128-bit vector and a normal sign_extend to 256-bits that should get
15224 // correctly legalized. We do this late to allow the canonical form of
15225 // sextload to persist throughout the rest of the DAG combiner -- it wants
15226 // to fold together any extensions it can, and so will fuse a sign_extend
15227 // of an sextload into a sextload targeting a wider value.
15229 if (MemSz == 128) {
15230 // Just switch this to a normal load.
15231 assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
15232 "it must be a legal 128-bit vector "
15234 Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
15235 Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
15236 Ld->isInvariant(), Ld->getAlignment());
15238 assert(MemSz < 128 &&
15239 "Can't extend a type wider than 128 bits to a 256 bit vector!");
15240 // Do an sext load to a 128-bit vector type. We want to use the same
15241 // number of elements, but elements half as wide. This will end up being
15242 // recursively lowered by this routine, but will succeed as we definitely
15243 // have all the necessary features if we're using AVX1.
15245 EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
15246 EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
15248 DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
15249 Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
15250 Ld->isNonTemporal(), Ld->isInvariant(),
15251 Ld->getAlignment());
15254 // Replace chain users with the new chain.
15255 assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
15256 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
15258 // Finally, do a normal sign-extend to the desired register.
15259 return DAG.getSExtOrTrunc(Load, dl, RegVT);
15262 // All sizes must be a power of two.
15263 assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
15264 "Non-power-of-two elements are not custom lowered!");
15266 // Attempt to load the original value using scalar loads.
15267 // Find the largest scalar type that divides the total loaded size.
15268 MVT SclrLoadTy = MVT::i8;
15269 for (MVT Tp : MVT::integer_valuetypes()) {
15270 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15275 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15276 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15278 SclrLoadTy = MVT::f64;
15280 // Calculate the number of scalar loads that we need to perform
15281 // in order to load our vector from memory.
15282 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15284 assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
15285 "Can only lower sext loads with a single scalar load!");
15287 unsigned loadRegZize = RegSz;
15288 if (Ext == ISD::SEXTLOAD && RegSz >= 256)
15291 // Represent our vector as a sequence of elements which are the
15292 // largest scalar that we can load.
15293 EVT LoadUnitVecVT = EVT::getVectorVT(
15294 *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
15296 // Represent the data using the same element type that is stored in
15297 // memory. In practice, we ''widen'' MemVT.
15299 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15300 loadRegZize / MemVT.getScalarSizeInBits());
15302 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15303 "Invalid vector type");
15305 // We can't shuffle using an illegal type.
15306 assert(TLI.isTypeLegal(WideVecVT) &&
15307 "We only lower types that form legal widened vector types");
15309 SmallVector<SDValue, 8> Chains;
15310 SDValue Ptr = Ld->getBasePtr();
15311 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
15312 TLI.getPointerTy(DAG.getDataLayout()));
15313 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15315 for (unsigned i = 0; i < NumLoads; ++i) {
15316 // Perform a single load.
15317 SDValue ScalarLoad =
15318 DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
15319 Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
15320 Ld->getAlignment());
15321 Chains.push_back(ScalarLoad.getValue(1));
15322 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15323 // another round of DAGCombining.
15325 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15327 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15328 ScalarLoad, DAG.getIntPtrConstant(i, dl));
15330 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15333 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
15335 // Bitcast the loaded value to a vector of the original element type, in
15336 // the size of the target vector type.
15337 SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
15338 unsigned SizeRatio = RegSz / MemSz;
15340 if (Ext == ISD::SEXTLOAD) {
15341 // If we have SSE4.1, we can directly emit a VSEXT node.
15342 if (Subtarget->hasSSE41()) {
15343 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
15344 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15348 // Otherwise we'll use SIGN_EXTEND_VECTOR_INREG to sign extend the lowest
15350 assert(TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND_VECTOR_INREG, RegVT) &&
15351 "We can't implement a sext load without SIGN_EXTEND_VECTOR_INREG!");
15353 SDValue Shuff = DAG.getSignExtendVectorInReg(SlicedVec, dl, RegVT);
15354 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15358 // Redistribute the loaded elements into the different locations.
15359 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
15360 for (unsigned i = 0; i != NumElems; ++i)
15361 ShuffleVec[i * SizeRatio] = i;
15363 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15364 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
15366 // Bitcast to the requested type.
15367 Shuff = DAG.getBitcast(RegVT, Shuff);
15368 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
15372 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
15373 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
15374 // from the AND / OR.
15375 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
15376 Opc = Op.getOpcode();
15377 if (Opc != ISD::OR && Opc != ISD::AND)
15379 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15380 Op.getOperand(0).hasOneUse() &&
15381 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
15382 Op.getOperand(1).hasOneUse());
15385 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
15386 // 1 and that the SETCC node has a single use.
15387 static bool isXor1OfSetCC(SDValue Op) {
15388 if (Op.getOpcode() != ISD::XOR)
15390 if (isOneConstant(Op.getOperand(1)))
15391 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
15392 Op.getOperand(0).hasOneUse();
15396 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
15397 bool addTest = true;
15398 SDValue Chain = Op.getOperand(0);
15399 SDValue Cond = Op.getOperand(1);
15400 SDValue Dest = Op.getOperand(2);
15403 bool Inverted = false;
15405 if (Cond.getOpcode() == ISD::SETCC) {
15406 // Check for setcc([su]{add,sub,mul}o == 0).
15407 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
15408 isNullConstant(Cond.getOperand(1)) &&
15409 Cond.getOperand(0).getResNo() == 1 &&
15410 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
15411 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
15412 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
15413 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
15414 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
15415 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
15417 Cond = Cond.getOperand(0);
15419 SDValue NewCond = LowerSETCC(Cond, DAG);
15420 if (NewCond.getNode())
15425 // FIXME: LowerXALUO doesn't handle these!!
15426 else if (Cond.getOpcode() == X86ISD::ADD ||
15427 Cond.getOpcode() == X86ISD::SUB ||
15428 Cond.getOpcode() == X86ISD::SMUL ||
15429 Cond.getOpcode() == X86ISD::UMUL)
15430 Cond = LowerXALUO(Cond, DAG);
15433 // Look pass (and (setcc_carry (cmp ...)), 1).
15434 if (Cond.getOpcode() == ISD::AND &&
15435 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY &&
15436 isOneConstant(Cond.getOperand(1)))
15437 Cond = Cond.getOperand(0);
15439 // If condition flag is set by a X86ISD::CMP, then use it as the condition
15440 // setting operand in place of the X86ISD::SETCC.
15441 unsigned CondOpcode = Cond.getOpcode();
15442 if (CondOpcode == X86ISD::SETCC ||
15443 CondOpcode == X86ISD::SETCC_CARRY) {
15444 CC = Cond.getOperand(0);
15446 SDValue Cmp = Cond.getOperand(1);
15447 unsigned Opc = Cmp.getOpcode();
15448 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
15449 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
15453 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
15457 // These can only come from an arithmetic instruction with overflow,
15458 // e.g. SADDO, UADDO.
15459 Cond = Cond.getNode()->getOperand(1);
15465 CondOpcode = Cond.getOpcode();
15466 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
15467 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
15468 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
15469 Cond.getOperand(0).getValueType() != MVT::i8)) {
15470 SDValue LHS = Cond.getOperand(0);
15471 SDValue RHS = Cond.getOperand(1);
15472 unsigned X86Opcode;
15475 // Keep this in sync with LowerXALUO, otherwise we might create redundant
15476 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
15478 switch (CondOpcode) {
15479 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
15481 if (isOneConstant(RHS)) {
15482 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
15485 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
15486 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
15488 if (isOneConstant(RHS)) {
15489 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
15492 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
15493 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
15494 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
15495 default: llvm_unreachable("unexpected overflowing operator");
15498 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
15499 if (CondOpcode == ISD::UMULO)
15500 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
15503 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
15505 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
15507 if (CondOpcode == ISD::UMULO)
15508 Cond = X86Op.getValue(2);
15510 Cond = X86Op.getValue(1);
15512 CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15516 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
15517 SDValue Cmp = Cond.getOperand(0).getOperand(1);
15518 if (CondOpc == ISD::OR) {
15519 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
15520 // two branches instead of an explicit OR instruction with a
15522 if (Cmp == Cond.getOperand(1).getOperand(1) &&
15523 isX86LogicalCmp(Cmp)) {
15524 CC = Cond.getOperand(0).getOperand(0);
15525 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15526 Chain, Dest, CC, Cmp);
15527 CC = Cond.getOperand(1).getOperand(0);
15531 } else { // ISD::AND
15532 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
15533 // two branches instead of an explicit AND instruction with a
15534 // separate test. However, we only do this if this block doesn't
15535 // have a fall-through edge, because this requires an explicit
15536 // jmp when the condition is false.
15537 if (Cmp == Cond.getOperand(1).getOperand(1) &&
15538 isX86LogicalCmp(Cmp) &&
15539 Op.getNode()->hasOneUse()) {
15540 X86::CondCode CCode =
15541 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15542 CCode = X86::GetOppositeBranchCondition(CCode);
15543 CC = DAG.getConstant(CCode, dl, MVT::i8);
15544 SDNode *User = *Op.getNode()->use_begin();
15545 // Look for an unconditional branch following this conditional branch.
15546 // We need this because we need to reverse the successors in order
15547 // to implement FCMP_OEQ.
15548 if (User->getOpcode() == ISD::BR) {
15549 SDValue FalseBB = User->getOperand(1);
15551 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15552 assert(NewBR == User);
15556 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15557 Chain, Dest, CC, Cmp);
15558 X86::CondCode CCode =
15559 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
15560 CCode = X86::GetOppositeBranchCondition(CCode);
15561 CC = DAG.getConstant(CCode, dl, MVT::i8);
15567 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
15568 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
15569 // It should be transformed during dag combiner except when the condition
15570 // is set by a arithmetics with overflow node.
15571 X86::CondCode CCode =
15572 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
15573 CCode = X86::GetOppositeBranchCondition(CCode);
15574 CC = DAG.getConstant(CCode, dl, MVT::i8);
15575 Cond = Cond.getOperand(0).getOperand(1);
15577 } else if (Cond.getOpcode() == ISD::SETCC &&
15578 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
15579 // For FCMP_OEQ, we can emit
15580 // two branches instead of an explicit AND instruction with a
15581 // separate test. However, we only do this if this block doesn't
15582 // have a fall-through edge, because this requires an explicit
15583 // jmp when the condition is false.
15584 if (Op.getNode()->hasOneUse()) {
15585 SDNode *User = *Op.getNode()->use_begin();
15586 // Look for an unconditional branch following this conditional branch.
15587 // We need this because we need to reverse the successors in order
15588 // to implement FCMP_OEQ.
15589 if (User->getOpcode() == ISD::BR) {
15590 SDValue FalseBB = User->getOperand(1);
15592 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15593 assert(NewBR == User);
15597 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15598 Cond.getOperand(0), Cond.getOperand(1));
15599 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15600 CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15601 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15602 Chain, Dest, CC, Cmp);
15603 CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
15608 } else if (Cond.getOpcode() == ISD::SETCC &&
15609 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
15610 // For FCMP_UNE, we can emit
15611 // two branches instead of an explicit AND instruction with a
15612 // separate test. However, we only do this if this block doesn't
15613 // have a fall-through edge, because this requires an explicit
15614 // jmp when the condition is false.
15615 if (Op.getNode()->hasOneUse()) {
15616 SDNode *User = *Op.getNode()->use_begin();
15617 // Look for an unconditional branch following this conditional branch.
15618 // We need this because we need to reverse the successors in order
15619 // to implement FCMP_UNE.
15620 if (User->getOpcode() == ISD::BR) {
15621 SDValue FalseBB = User->getOperand(1);
15623 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15624 assert(NewBR == User);
15627 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15628 Cond.getOperand(0), Cond.getOperand(1));
15629 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15630 CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
15631 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15632 Chain, Dest, CC, Cmp);
15633 CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
15643 // Look pass the truncate if the high bits are known zero.
15644 if (isTruncWithZeroHighBitsInput(Cond, DAG))
15645 Cond = Cond.getOperand(0);
15647 // We know the result of AND is compared against zero. Try to match
15649 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15650 if (SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG)) {
15651 CC = NewSetCC.getOperand(0);
15652 Cond = NewSetCC.getOperand(1);
15659 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
15660 CC = DAG.getConstant(X86Cond, dl, MVT::i8);
15661 Cond = EmitTest(Cond, X86Cond, dl, DAG);
15663 Cond = ConvertCmpIfNecessary(Cond, DAG);
15664 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15665 Chain, Dest, CC, Cond);
15668 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
15669 // Calls to _alloca are needed to probe the stack when allocating more than 4k
15670 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
15671 // that the guard pages used by the OS virtual memory manager are allocated in
15672 // correct sequence.
15674 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
15675 SelectionDAG &DAG) const {
15676 MachineFunction &MF = DAG.getMachineFunction();
15677 bool SplitStack = MF.shouldSplitStack();
15678 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
15683 SDNode *Node = Op.getNode();
15684 SDValue Chain = Op.getOperand(0);
15685 SDValue Size = Op.getOperand(1);
15686 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
15687 EVT VT = Node->getValueType(0);
15689 // Chain the dynamic stack allocation so that it doesn't modify the stack
15690 // pointer when other instructions are using the stack.
15691 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true), dl);
15693 bool Is64Bit = Subtarget->is64Bit();
15694 MVT SPTy = getPointerTy(DAG.getDataLayout());
15698 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15699 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
15700 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
15701 " not tell us which reg is the stack pointer!");
15702 EVT VT = Node->getValueType(0);
15703 SDValue Tmp3 = Node->getOperand(2);
15705 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
15706 Chain = SP.getValue(1);
15707 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
15708 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
15709 unsigned StackAlign = TFI.getStackAlignment();
15710 Result = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
15711 if (Align > StackAlign)
15712 Result = DAG.getNode(ISD::AND, dl, VT, Result,
15713 DAG.getConstant(-(uint64_t)Align, dl, VT));
15714 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Result); // Output chain
15715 } else if (SplitStack) {
15716 MachineRegisterInfo &MRI = MF.getRegInfo();
15719 // The 64 bit implementation of segmented stacks needs to clobber both r10
15720 // r11. This makes it impossible to use it along with nested parameters.
15721 const Function *F = MF.getFunction();
15723 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
15725 if (I->hasNestAttr())
15726 report_fatal_error("Cannot use segmented stacks with functions that "
15727 "have nested arguments.");
15730 const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
15731 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
15732 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
15733 Result = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
15734 DAG.getRegister(Vreg, SPTy));
15737 const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
15739 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
15740 Flag = Chain.getValue(1);
15741 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
15743 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
15745 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15746 unsigned SPReg = RegInfo->getStackRegister();
15747 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
15748 Chain = SP.getValue(1);
15751 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
15752 DAG.getConstant(-(uint64_t)Align, dl, VT));
15753 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
15759 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
15760 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
15762 SDValue Ops[2] = {Result, Chain};
15763 return DAG.getMergeValues(Ops, dl);
15766 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
15767 MachineFunction &MF = DAG.getMachineFunction();
15768 auto PtrVT = getPointerTy(MF.getDataLayout());
15769 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15771 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15774 if (!Subtarget->is64Bit() ||
15775 Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv())) {
15776 // vastart just stores the address of the VarArgsFrameIndex slot into the
15777 // memory location argument.
15778 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15779 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
15780 MachinePointerInfo(SV), false, false, 0);
15784 // gp_offset (0 - 6 * 8)
15785 // fp_offset (48 - 48 + 8 * 16)
15786 // overflow_arg_area (point to parameters coming in memory).
15788 SmallVector<SDValue, 8> MemOps;
15789 SDValue FIN = Op.getOperand(1);
15791 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
15792 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
15794 FIN, MachinePointerInfo(SV), false, false, 0);
15795 MemOps.push_back(Store);
15798 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15799 Store = DAG.getStore(Op.getOperand(0), DL,
15800 DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
15802 FIN, MachinePointerInfo(SV, 4), false, false, 0);
15803 MemOps.push_back(Store);
15805 // Store ptr to overflow_arg_area
15806 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15807 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15808 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
15809 MachinePointerInfo(SV, 8),
15811 MemOps.push_back(Store);
15813 // Store ptr to reg_save_area.
15814 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(
15815 Subtarget->isTarget64BitLP64() ? 8 : 4, DL));
15816 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
15817 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN, MachinePointerInfo(
15818 SV, Subtarget->isTarget64BitLP64() ? 16 : 12), false, false, 0);
15819 MemOps.push_back(Store);
15820 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
15823 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
15824 assert(Subtarget->is64Bit() &&
15825 "LowerVAARG only handles 64-bit va_arg!");
15826 assert(Op.getNode()->getNumOperands() == 4);
15828 MachineFunction &MF = DAG.getMachineFunction();
15829 if (Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv()))
15830 // The Win64 ABI uses char* instead of a structure.
15831 return DAG.expandVAArg(Op.getNode());
15833 SDValue Chain = Op.getOperand(0);
15834 SDValue SrcPtr = Op.getOperand(1);
15835 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15836 unsigned Align = Op.getConstantOperandVal(3);
15839 EVT ArgVT = Op.getNode()->getValueType(0);
15840 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15841 uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
15844 // Decide which area this value should be read from.
15845 // TODO: Implement the AMD64 ABI in its entirety. This simple
15846 // selection mechanism works only for the basic types.
15847 if (ArgVT == MVT::f80) {
15848 llvm_unreachable("va_arg for f80 not yet implemented");
15849 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
15850 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
15851 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
15852 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
15854 llvm_unreachable("Unhandled argument type in LowerVAARG");
15857 if (ArgMode == 2) {
15858 // Sanity Check: Make sure using fp_offset makes sense.
15859 assert(!Subtarget->useSoftFloat() &&
15860 !(MF.getFunction()->hasFnAttribute(Attribute::NoImplicitFloat)) &&
15861 Subtarget->hasSSE1());
15864 // Insert VAARG_64 node into the DAG
15865 // VAARG_64 returns two values: Variable Argument Address, Chain
15866 SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
15867 DAG.getConstant(ArgMode, dl, MVT::i8),
15868 DAG.getConstant(Align, dl, MVT::i32)};
15869 SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
15870 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
15871 VTs, InstOps, MVT::i64,
15872 MachinePointerInfo(SV),
15874 /*Volatile=*/false,
15876 /*WriteMem=*/true);
15877 Chain = VAARG.getValue(1);
15879 // Load the next argument and return it
15880 return DAG.getLoad(ArgVT, dl,
15883 MachinePointerInfo(),
15884 false, false, false, 0);
15887 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
15888 SelectionDAG &DAG) {
15889 // X86-64 va_list is a struct { i32, i32, i8*, i8* }, except on Windows,
15890 // where a va_list is still an i8*.
15891 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
15892 if (Subtarget->isCallingConvWin64(
15893 DAG.getMachineFunction().getFunction()->getCallingConv()))
15894 // Probably a Win64 va_copy.
15895 return DAG.expandVACopy(Op.getNode());
15897 SDValue Chain = Op.getOperand(0);
15898 SDValue DstPtr = Op.getOperand(1);
15899 SDValue SrcPtr = Op.getOperand(2);
15900 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
15901 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15904 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
15905 DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
15907 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
15910 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
15911 // amount is a constant. Takes immediate version of shift as input.
15912 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
15913 SDValue SrcOp, uint64_t ShiftAmt,
15914 SelectionDAG &DAG) {
15915 MVT ElementType = VT.getVectorElementType();
15917 // Fold this packed shift into its first operand if ShiftAmt is 0.
15921 // Check for ShiftAmt >= element width
15922 if (ShiftAmt >= ElementType.getSizeInBits()) {
15923 if (Opc == X86ISD::VSRAI)
15924 ShiftAmt = ElementType.getSizeInBits() - 1;
15926 return DAG.getConstant(0, dl, VT);
15929 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
15930 && "Unknown target vector shift-by-constant node");
15932 // Fold this packed vector shift into a build vector if SrcOp is a
15933 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
15934 if (VT == SrcOp.getSimpleValueType() &&
15935 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
15936 SmallVector<SDValue, 8> Elts;
15937 unsigned NumElts = SrcOp->getNumOperands();
15938 ConstantSDNode *ND;
15941 default: llvm_unreachable(nullptr);
15942 case X86ISD::VSHLI:
15943 for (unsigned i=0; i!=NumElts; ++i) {
15944 SDValue CurrentOp = SrcOp->getOperand(i);
15945 if (CurrentOp->getOpcode() == ISD::UNDEF) {
15946 Elts.push_back(CurrentOp);
15949 ND = cast<ConstantSDNode>(CurrentOp);
15950 const APInt &C = ND->getAPIntValue();
15951 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
15954 case X86ISD::VSRLI:
15955 for (unsigned i=0; i!=NumElts; ++i) {
15956 SDValue CurrentOp = SrcOp->getOperand(i);
15957 if (CurrentOp->getOpcode() == ISD::UNDEF) {
15958 Elts.push_back(CurrentOp);
15961 ND = cast<ConstantSDNode>(CurrentOp);
15962 const APInt &C = ND->getAPIntValue();
15963 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
15966 case X86ISD::VSRAI:
15967 for (unsigned i=0; i!=NumElts; ++i) {
15968 SDValue CurrentOp = SrcOp->getOperand(i);
15969 if (CurrentOp->getOpcode() == ISD::UNDEF) {
15970 Elts.push_back(CurrentOp);
15973 ND = cast<ConstantSDNode>(CurrentOp);
15974 const APInt &C = ND->getAPIntValue();
15975 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
15980 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15983 return DAG.getNode(Opc, dl, VT, SrcOp,
15984 DAG.getConstant(ShiftAmt, dl, MVT::i8));
15987 // getTargetVShiftNode - Handle vector element shifts where the shift amount
15988 // may or may not be a constant. Takes immediate version of shift as input.
15989 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
15990 SDValue SrcOp, SDValue ShAmt,
15991 SelectionDAG &DAG) {
15992 MVT SVT = ShAmt.getSimpleValueType();
15993 assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
15995 // Catch shift-by-constant.
15996 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
15997 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
15998 CShAmt->getZExtValue(), DAG);
16000 // Change opcode to non-immediate version
16002 default: llvm_unreachable("Unknown target vector shift node");
16003 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
16004 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
16005 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
16008 const X86Subtarget &Subtarget =
16009 static_cast<const X86Subtarget &>(DAG.getSubtarget());
16010 if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
16011 ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
16012 // Let the shuffle legalizer expand this shift amount node.
16013 SDValue Op0 = ShAmt.getOperand(0);
16014 Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
16015 ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
16017 // Need to build a vector containing shift amount.
16018 // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
16019 SmallVector<SDValue, 4> ShOps;
16020 ShOps.push_back(ShAmt);
16021 if (SVT == MVT::i32) {
16022 ShOps.push_back(DAG.getConstant(0, dl, SVT));
16023 ShOps.push_back(DAG.getUNDEF(SVT));
16025 ShOps.push_back(DAG.getUNDEF(SVT));
16027 MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
16028 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
16031 // The return type has to be a 128-bit type with the same element
16032 // type as the input type.
16033 MVT EltVT = VT.getVectorElementType();
16034 MVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
16036 ShAmt = DAG.getBitcast(ShVT, ShAmt);
16037 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
16040 /// \brief Return Mask with the necessary casting or extending
16041 /// for \p Mask according to \p MaskVT when lowering masking intrinsics
16042 static SDValue getMaskNode(SDValue Mask, MVT MaskVT,
16043 const X86Subtarget *Subtarget,
16044 SelectionDAG &DAG, SDLoc dl) {
16046 if (MaskVT.bitsGT(Mask.getSimpleValueType())) {
16047 // Mask should be extended
16048 Mask = DAG.getNode(ISD::ANY_EXTEND, dl,
16049 MVT::getIntegerVT(MaskVT.getSizeInBits()), Mask);
16052 if (Mask.getSimpleValueType() == MVT::i64 && Subtarget->is32Bit()) {
16053 if (MaskVT == MVT::v64i1) {
16054 assert(Subtarget->hasBWI() && "Expected AVX512BW target!");
16055 // In case 32bit mode, bitcast i64 is illegal, extend/split it.
16057 Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Mask,
16058 DAG.getConstant(0, dl, MVT::i32));
16059 Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Mask,
16060 DAG.getConstant(1, dl, MVT::i32));
16062 Lo = DAG.getBitcast(MVT::v32i1, Lo);
16063 Hi = DAG.getBitcast(MVT::v32i1, Hi);
16065 return DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, Lo, Hi);
16067 // MaskVT require < 64bit. Truncate mask (should succeed in any case),
16069 MVT TruncVT = MVT::getIntegerVT(MaskVT.getSizeInBits());
16070 return DAG.getBitcast(MaskVT,
16071 DAG.getNode(ISD::TRUNCATE, dl, TruncVT, Mask));
16075 MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16076 Mask.getSimpleValueType().getSizeInBits());
16077 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16078 // are extracted by EXTRACT_SUBVECTOR.
16079 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16080 DAG.getBitcast(BitcastVT, Mask),
16081 DAG.getIntPtrConstant(0, dl));
16085 /// \brief Return (and \p Op, \p Mask) for compare instructions or
16086 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
16087 /// necessary casting or extending for \p Mask when lowering masking intrinsics
16088 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
16089 SDValue PreservedSrc,
16090 const X86Subtarget *Subtarget,
16091 SelectionDAG &DAG) {
16092 MVT VT = Op.getSimpleValueType();
16093 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16094 unsigned OpcodeSelect = ISD::VSELECT;
16097 if (isAllOnesConstant(Mask))
16100 SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
16102 switch (Op.getOpcode()) {
16104 case X86ISD::PCMPEQM:
16105 case X86ISD::PCMPGTM:
16107 case X86ISD::CMPMU:
16108 return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
16109 case X86ISD::VFPCLASS:
16110 case X86ISD::VFPCLASSS:
16111 return DAG.getNode(ISD::OR, dl, VT, Op, VMask);
16112 case X86ISD::VTRUNC:
16113 case X86ISD::VTRUNCS:
16114 case X86ISD::VTRUNCUS:
16115 // We can't use ISD::VSELECT here because it is not always "Legal"
16116 // for the destination type. For example vpmovqb require only AVX512
16117 // and vselect that can operate on byte element type require BWI
16118 OpcodeSelect = X86ISD::SELECT;
16121 if (PreservedSrc.getOpcode() == ISD::UNDEF)
16122 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
16123 return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
16126 /// \brief Creates an SDNode for a predicated scalar operation.
16127 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
16128 /// The mask is coming as MVT::i8 and it should be truncated
16129 /// to MVT::i1 while lowering masking intrinsics.
16130 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
16131 /// "X86select" instead of "vselect". We just can't create the "vselect" node
16132 /// for a scalar instruction.
16133 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
16134 SDValue PreservedSrc,
16135 const X86Subtarget *Subtarget,
16136 SelectionDAG &DAG) {
16137 if (isAllOnesConstant(Mask))
16140 MVT VT = Op.getSimpleValueType();
16142 // The mask should be of type MVT::i1
16143 SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
16145 if (Op.getOpcode() == X86ISD::FSETCC)
16146 return DAG.getNode(ISD::AND, dl, VT, Op, IMask);
16147 if (Op.getOpcode() == X86ISD::VFPCLASS ||
16148 Op.getOpcode() == X86ISD::VFPCLASSS)
16149 return DAG.getNode(ISD::OR, dl, VT, Op, IMask);
16151 if (PreservedSrc.getOpcode() == ISD::UNDEF)
16152 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
16153 return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
16156 static int getSEHRegistrationNodeSize(const Function *Fn) {
16157 if (!Fn->hasPersonalityFn())
16158 report_fatal_error(
16159 "querying registration node size for function without personality");
16160 // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
16161 // WinEHStatePass for the full struct definition.
16162 switch (classifyEHPersonality(Fn->getPersonalityFn())) {
16163 case EHPersonality::MSVC_X86SEH: return 24;
16164 case EHPersonality::MSVC_CXX: return 16;
16167 report_fatal_error("can only recover FP for MSVC EH personality functions");
16170 /// When the 32-bit MSVC runtime transfers control to us, either to an outlined
16171 /// function or when returning to a parent frame after catching an exception, we
16172 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
16173 /// Here's the math:
16174 /// RegNodeBase = EntryEBP - RegNodeSize
16175 /// ParentFP = RegNodeBase - RegNodeFrameOffset
16176 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
16177 /// subtracting the offset (negative on x86) takes us back to the parent FP.
16178 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
16179 SDValue EntryEBP) {
16180 MachineFunction &MF = DAG.getMachineFunction();
16183 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16184 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
16186 // It's possible that the parent function no longer has a personality function
16187 // if the exceptional code was optimized away, in which case we just return
16188 // the incoming EBP.
16189 if (!Fn->hasPersonalityFn())
16192 int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16194 // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
16196 MCSymbol *OffsetSym =
16197 MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
16198 GlobalValue::getRealLinkageName(Fn->getName()));
16199 SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
16200 SDValue RegNodeFrameOffset =
16201 DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
16203 // RegNodeBase = EntryEBP - RegNodeSize
16204 // ParentFP = RegNodeBase - RegNodeFrameOffset
16205 SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
16206 DAG.getConstant(RegNodeSize, dl, PtrVT));
16207 return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, RegNodeFrameOffset);
16210 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16211 SelectionDAG &DAG) {
16213 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16214 MVT VT = Op.getSimpleValueType();
16215 const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
16217 switch(IntrData->Type) {
16218 case INTR_TYPE_1OP:
16219 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
16220 case INTR_TYPE_2OP:
16221 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16223 case INTR_TYPE_2OP_IMM8:
16224 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16225 DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(2)));
16226 case INTR_TYPE_3OP:
16227 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16228 Op.getOperand(2), Op.getOperand(3));
16229 case INTR_TYPE_4OP:
16230 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
16231 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
16232 case INTR_TYPE_1OP_MASK_RM: {
16233 SDValue Src = Op.getOperand(1);
16234 SDValue PassThru = Op.getOperand(2);
16235 SDValue Mask = Op.getOperand(3);
16236 SDValue RoundingMode;
16237 // We allways add rounding mode to the Node.
16238 // If the rounding mode is not specified, we add the
16239 // "current direction" mode.
16240 if (Op.getNumOperands() == 4)
16242 DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16244 RoundingMode = Op.getOperand(4);
16245 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16246 if (IntrWithRoundingModeOpcode != 0)
16247 if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
16248 X86::STATIC_ROUNDING::CUR_DIRECTION)
16249 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16250 dl, Op.getValueType(), Src, RoundingMode),
16251 Mask, PassThru, Subtarget, DAG);
16252 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
16254 Mask, PassThru, Subtarget, DAG);
16256 case INTR_TYPE_1OP_MASK: {
16257 SDValue Src = Op.getOperand(1);
16258 SDValue PassThru = Op.getOperand(2);
16259 SDValue Mask = Op.getOperand(3);
16260 // We add rounding mode to the Node when
16261 // - RM Opcode is specified and
16262 // - RM is not "current direction".
16263 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16264 if (IntrWithRoundingModeOpcode != 0) {
16265 SDValue Rnd = Op.getOperand(4);
16266 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16267 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16268 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16269 dl, Op.getValueType(),
16271 Mask, PassThru, Subtarget, DAG);
16274 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
16275 Mask, PassThru, Subtarget, DAG);
16277 case INTR_TYPE_SCALAR_MASK: {
16278 SDValue Src1 = Op.getOperand(1);
16279 SDValue Src2 = Op.getOperand(2);
16280 SDValue passThru = Op.getOperand(3);
16281 SDValue Mask = Op.getOperand(4);
16282 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2),
16283 Mask, passThru, Subtarget, DAG);
16285 case INTR_TYPE_SCALAR_MASK_RM: {
16286 SDValue Src1 = Op.getOperand(1);
16287 SDValue Src2 = Op.getOperand(2);
16288 SDValue Src0 = Op.getOperand(3);
16289 SDValue Mask = Op.getOperand(4);
16290 // There are 2 kinds of intrinsics in this group:
16291 // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
16292 // (2) With rounding mode and sae - 7 operands.
16293 if (Op.getNumOperands() == 6) {
16294 SDValue Sae = Op.getOperand(5);
16295 unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
16296 return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
16298 Mask, Src0, Subtarget, DAG);
16300 assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
16301 SDValue RoundingMode = Op.getOperand(5);
16302 SDValue Sae = Op.getOperand(6);
16303 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
16304 RoundingMode, Sae),
16305 Mask, Src0, Subtarget, DAG);
16307 case INTR_TYPE_2OP_MASK:
16308 case INTR_TYPE_2OP_IMM8_MASK: {
16309 SDValue Src1 = Op.getOperand(1);
16310 SDValue Src2 = Op.getOperand(2);
16311 SDValue PassThru = Op.getOperand(3);
16312 SDValue Mask = Op.getOperand(4);
16314 if (IntrData->Type == INTR_TYPE_2OP_IMM8_MASK)
16315 Src2 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src2);
16317 // We specify 2 possible opcodes for intrinsics with rounding modes.
16318 // First, we check if the intrinsic may have non-default rounding mode,
16319 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16320 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16321 if (IntrWithRoundingModeOpcode != 0) {
16322 SDValue Rnd = Op.getOperand(5);
16323 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16324 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16325 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16326 dl, Op.getValueType(),
16328 Mask, PassThru, Subtarget, DAG);
16331 // TODO: Intrinsics should have fast-math-flags to propagate.
16332 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,Src1,Src2),
16333 Mask, PassThru, Subtarget, DAG);
16335 case INTR_TYPE_2OP_MASK_RM: {
16336 SDValue Src1 = Op.getOperand(1);
16337 SDValue Src2 = Op.getOperand(2);
16338 SDValue PassThru = Op.getOperand(3);
16339 SDValue Mask = Op.getOperand(4);
16340 // We specify 2 possible modes for intrinsics, with/without rounding
16342 // First, we check if the intrinsic have rounding mode (6 operands),
16343 // if not, we set rounding mode to "current".
16345 if (Op.getNumOperands() == 6)
16346 Rnd = Op.getOperand(5);
16348 Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16349 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16351 Mask, PassThru, Subtarget, DAG);
16353 case INTR_TYPE_3OP_SCALAR_MASK_RM: {
16354 SDValue Src1 = Op.getOperand(1);
16355 SDValue Src2 = Op.getOperand(2);
16356 SDValue Src3 = Op.getOperand(3);
16357 SDValue PassThru = Op.getOperand(4);
16358 SDValue Mask = Op.getOperand(5);
16359 SDValue Sae = Op.getOperand(6);
16361 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1,
16363 Mask, PassThru, Subtarget, DAG);
16365 case INTR_TYPE_3OP_MASK_RM: {
16366 SDValue Src1 = Op.getOperand(1);
16367 SDValue Src2 = Op.getOperand(2);
16368 SDValue Imm = Op.getOperand(3);
16369 SDValue PassThru = Op.getOperand(4);
16370 SDValue Mask = Op.getOperand(5);
16371 // We specify 2 possible modes for intrinsics, with/without rounding
16373 // First, we check if the intrinsic have rounding mode (7 operands),
16374 // if not, we set rounding mode to "current".
16376 if (Op.getNumOperands() == 7)
16377 Rnd = Op.getOperand(6);
16379 Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
16380 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16381 Src1, Src2, Imm, Rnd),
16382 Mask, PassThru, Subtarget, DAG);
16384 case INTR_TYPE_3OP_IMM8_MASK:
16385 case INTR_TYPE_3OP_MASK:
16386 case INSERT_SUBVEC: {
16387 SDValue Src1 = Op.getOperand(1);
16388 SDValue Src2 = Op.getOperand(2);
16389 SDValue Src3 = Op.getOperand(3);
16390 SDValue PassThru = Op.getOperand(4);
16391 SDValue Mask = Op.getOperand(5);
16393 if (IntrData->Type == INTR_TYPE_3OP_IMM8_MASK)
16394 Src3 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Src3);
16395 else if (IntrData->Type == INSERT_SUBVEC) {
16396 // imm should be adapted to ISD::INSERT_SUBVECTOR behavior
16397 assert(isa<ConstantSDNode>(Src3) && "Expected a ConstantSDNode here!");
16398 unsigned Imm = cast<ConstantSDNode>(Src3)->getZExtValue();
16399 Imm *= Src2.getSimpleValueType().getVectorNumElements();
16400 Src3 = DAG.getTargetConstant(Imm, dl, MVT::i32);
16403 // We specify 2 possible opcodes for intrinsics with rounding modes.
16404 // First, we check if the intrinsic may have non-default rounding mode,
16405 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16406 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16407 if (IntrWithRoundingModeOpcode != 0) {
16408 SDValue Rnd = Op.getOperand(6);
16409 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
16410 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
16411 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16412 dl, Op.getValueType(),
16413 Src1, Src2, Src3, Rnd),
16414 Mask, PassThru, Subtarget, DAG);
16417 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16419 Mask, PassThru, Subtarget, DAG);
16421 case VPERM_3OP_MASKZ:
16422 case VPERM_3OP_MASK:{
16423 // Src2 is the PassThru
16424 SDValue Src1 = Op.getOperand(1);
16425 SDValue Src2 = Op.getOperand(2);
16426 SDValue Src3 = Op.getOperand(3);
16427 SDValue Mask = Op.getOperand(4);
16428 MVT VT = Op.getSimpleValueType();
16429 SDValue PassThru = SDValue();
16431 // set PassThru element
16432 if (IntrData->Type == VPERM_3OP_MASKZ)
16433 PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16435 PassThru = DAG.getBitcast(VT, Src2);
16437 // Swap Src1 and Src2 in the node creation
16438 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
16439 dl, Op.getValueType(),
16441 Mask, PassThru, Subtarget, DAG);
16445 case FMA_OP_MASK: {
16446 SDValue Src1 = Op.getOperand(1);
16447 SDValue Src2 = Op.getOperand(2);
16448 SDValue Src3 = Op.getOperand(3);
16449 SDValue Mask = Op.getOperand(4);
16450 MVT VT = Op.getSimpleValueType();
16451 SDValue PassThru = SDValue();
16453 // set PassThru element
16454 if (IntrData->Type == FMA_OP_MASKZ)
16455 PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16456 else if (IntrData->Type == FMA_OP_MASK3)
16461 // We specify 2 possible opcodes for intrinsics with rounding modes.
16462 // First, we check if the intrinsic may have non-default rounding mode,
16463 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16464 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
16465 if (IntrWithRoundingModeOpcode != 0) {
16466 SDValue Rnd = Op.getOperand(5);
16467 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16468 X86::STATIC_ROUNDING::CUR_DIRECTION)
16469 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
16470 dl, Op.getValueType(),
16471 Src1, Src2, Src3, Rnd),
16472 Mask, PassThru, Subtarget, DAG);
16474 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
16475 dl, Op.getValueType(),
16477 Mask, PassThru, Subtarget, DAG);
16479 case TERLOG_OP_MASK:
16480 case TERLOG_OP_MASKZ: {
16481 SDValue Src1 = Op.getOperand(1);
16482 SDValue Src2 = Op.getOperand(2);
16483 SDValue Src3 = Op.getOperand(3);
16484 SDValue Src4 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(4));
16485 SDValue Mask = Op.getOperand(5);
16486 MVT VT = Op.getSimpleValueType();
16487 SDValue PassThru = Src1;
16488 // Set PassThru element.
16489 if (IntrData->Type == TERLOG_OP_MASKZ)
16490 PassThru = getZeroVector(VT, Subtarget, DAG, dl);
16492 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16493 Src1, Src2, Src3, Src4),
16494 Mask, PassThru, Subtarget, DAG);
16497 // FPclass intrinsics with mask
16498 SDValue Src1 = Op.getOperand(1);
16499 MVT VT = Src1.getSimpleValueType();
16500 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16501 SDValue Imm = Op.getOperand(2);
16502 SDValue Mask = Op.getOperand(3);
16503 MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16504 Mask.getSimpleValueType().getSizeInBits());
16505 SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MaskVT, Src1, Imm);
16506 SDValue FPclassMask = getVectorMaskingNode(FPclass, Mask,
16507 DAG.getTargetConstant(0, dl, MaskVT),
16509 SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16510 DAG.getUNDEF(BitcastVT), FPclassMask,
16511 DAG.getIntPtrConstant(0, dl));
16512 return DAG.getBitcast(Op.getValueType(), Res);
16515 SDValue Src1 = Op.getOperand(1);
16516 SDValue Imm = Op.getOperand(2);
16517 SDValue Mask = Op.getOperand(3);
16518 SDValue FPclass = DAG.getNode(IntrData->Opc0, dl, MVT::i1, Src1, Imm);
16519 SDValue FPclassMask = getScalarMaskingNode(FPclass, Mask,
16520 DAG.getTargetConstant(0, dl, MVT::i1), Subtarget, DAG);
16521 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i8, FPclassMask);
16524 case CMP_MASK_CC: {
16525 // Comparison intrinsics with masks.
16526 // Example of transformation:
16527 // (i8 (int_x86_avx512_mask_pcmpeq_q_128
16528 // (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
16530 // (v8i1 (insert_subvector undef,
16531 // (v2i1 (and (PCMPEQM %a, %b),
16532 // (extract_subvector
16533 // (v8i1 (bitcast %mask)), 0))), 0))))
16534 MVT VT = Op.getOperand(1).getSimpleValueType();
16535 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16536 SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
16537 MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16538 Mask.getSimpleValueType().getSizeInBits());
16540 if (IntrData->Type == CMP_MASK_CC) {
16541 SDValue CC = Op.getOperand(3);
16542 CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
16543 // We specify 2 possible opcodes for intrinsics with rounding modes.
16544 // First, we check if the intrinsic may have non-default rounding mode,
16545 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
16546 if (IntrData->Opc1 != 0) {
16547 SDValue Rnd = Op.getOperand(5);
16548 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16549 X86::STATIC_ROUNDING::CUR_DIRECTION)
16550 Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
16551 Op.getOperand(2), CC, Rnd);
16553 //default rounding mode
16555 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16556 Op.getOperand(2), CC);
16559 assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
16560 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
16563 SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
16564 DAG.getTargetConstant(0, dl,
16567 SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
16568 DAG.getUNDEF(BitcastVT), CmpMask,
16569 DAG.getIntPtrConstant(0, dl));
16570 return DAG.getBitcast(Op.getValueType(), Res);
16572 case CMP_MASK_SCALAR_CC: {
16573 SDValue Src1 = Op.getOperand(1);
16574 SDValue Src2 = Op.getOperand(2);
16575 SDValue CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op.getOperand(3));
16576 SDValue Mask = Op.getOperand(4);
16579 if (IntrData->Opc1 != 0) {
16580 SDValue Rnd = Op.getOperand(5);
16581 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
16582 X86::STATIC_ROUNDING::CUR_DIRECTION)
16583 Cmp = DAG.getNode(IntrData->Opc1, dl, MVT::i1, Src1, Src2, CC, Rnd);
16585 //default rounding mode
16587 Cmp = DAG.getNode(IntrData->Opc0, dl, MVT::i1, Src1, Src2, CC);
16589 SDValue CmpMask = getScalarMaskingNode(Cmp, Mask,
16590 DAG.getTargetConstant(0, dl,
16594 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i8,
16595 DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i8, CmpMask),
16596 DAG.getValueType(MVT::i1));
16598 case COMI: { // Comparison intrinsics
16599 ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
16600 SDValue LHS = Op.getOperand(1);
16601 SDValue RHS = Op.getOperand(2);
16602 unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
16603 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
16604 SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
16605 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16606 DAG.getConstant(X86CC, dl, MVT::i8), Cond);
16607 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16609 case COMI_RM: { // Comparison intrinsics with Sae
16610 SDValue LHS = Op.getOperand(1);
16611 SDValue RHS = Op.getOperand(2);
16612 SDValue CC = Op.getOperand(3);
16613 SDValue Sae = Op.getOperand(4);
16614 auto ComiType = TranslateX86ConstCondToX86CC(CC);
16615 // choose between ordered and unordered (comi/ucomi)
16616 unsigned comiOp = std::get<0>(ComiType) ? IntrData->Opc0 : IntrData->Opc1;
16618 if (cast<ConstantSDNode>(Sae)->getZExtValue() !=
16619 X86::STATIC_ROUNDING::CUR_DIRECTION)
16620 Cond = DAG.getNode(comiOp, dl, MVT::i32, LHS, RHS, Sae);
16622 Cond = DAG.getNode(comiOp, dl, MVT::i32, LHS, RHS);
16623 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16624 DAG.getConstant(std::get<1>(ComiType), dl, MVT::i8), Cond);
16625 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16628 return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
16629 Op.getOperand(1), Op.getOperand(2), DAG);
16631 return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
16632 Op.getSimpleValueType(),
16634 Op.getOperand(2), DAG),
16635 Op.getOperand(4), Op.getOperand(3), Subtarget,
16637 case COMPRESS_EXPAND_IN_REG: {
16638 SDValue Mask = Op.getOperand(3);
16639 SDValue DataToCompress = Op.getOperand(1);
16640 SDValue PassThru = Op.getOperand(2);
16641 if (isAllOnesConstant(Mask)) // return data as is
16642 return Op.getOperand(1);
16644 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
16646 Mask, PassThru, Subtarget, DAG);
16649 SDValue Mask = Op.getOperand(1);
16650 MVT MaskVT = MVT::getVectorVT(MVT::i1, Mask.getSimpleValueType().getSizeInBits());
16651 Mask = DAG.getBitcast(MaskVT, Mask);
16652 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Mask);
16655 SDValue Mask = Op.getOperand(3);
16656 MVT VT = Op.getSimpleValueType();
16657 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
16658 SDValue VMask = getMaskNode(Mask, MaskVT, Subtarget, DAG, dl);
16659 return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
16663 MVT VT = Op.getSimpleValueType();
16664 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getSizeInBits()/2);
16666 SDValue Src1 = getMaskNode(Op.getOperand(1), MaskVT, Subtarget, DAG, dl);
16667 SDValue Src2 = getMaskNode(Op.getOperand(2), MaskVT, Subtarget, DAG, dl);
16668 // Arguments should be swapped.
16669 SDValue Res = DAG.getNode(IntrData->Opc0, dl,
16670 MVT::getVectorVT(MVT::i1, VT.getSizeInBits()),
16672 return DAG.getBitcast(VT, Res);
16680 default: return SDValue(); // Don't custom lower most intrinsics.
16682 case Intrinsic::x86_avx2_permd:
16683 case Intrinsic::x86_avx2_permps:
16684 // Operands intentionally swapped. Mask is last operand to intrinsic,
16685 // but second operand for node/instruction.
16686 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
16687 Op.getOperand(2), Op.getOperand(1));
16689 // ptest and testp intrinsics. The intrinsic these come from are designed to
16690 // return an integer value, not just an instruction so lower it to the ptest
16691 // or testp pattern and a setcc for the result.
16692 case Intrinsic::x86_sse41_ptestz:
16693 case Intrinsic::x86_sse41_ptestc:
16694 case Intrinsic::x86_sse41_ptestnzc:
16695 case Intrinsic::x86_avx_ptestz_256:
16696 case Intrinsic::x86_avx_ptestc_256:
16697 case Intrinsic::x86_avx_ptestnzc_256:
16698 case Intrinsic::x86_avx_vtestz_ps:
16699 case Intrinsic::x86_avx_vtestc_ps:
16700 case Intrinsic::x86_avx_vtestnzc_ps:
16701 case Intrinsic::x86_avx_vtestz_pd:
16702 case Intrinsic::x86_avx_vtestc_pd:
16703 case Intrinsic::x86_avx_vtestnzc_pd:
16704 case Intrinsic::x86_avx_vtestz_ps_256:
16705 case Intrinsic::x86_avx_vtestc_ps_256:
16706 case Intrinsic::x86_avx_vtestnzc_ps_256:
16707 case Intrinsic::x86_avx_vtestz_pd_256:
16708 case Intrinsic::x86_avx_vtestc_pd_256:
16709 case Intrinsic::x86_avx_vtestnzc_pd_256: {
16710 bool IsTestPacked = false;
16713 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
16714 case Intrinsic::x86_avx_vtestz_ps:
16715 case Intrinsic::x86_avx_vtestz_pd:
16716 case Intrinsic::x86_avx_vtestz_ps_256:
16717 case Intrinsic::x86_avx_vtestz_pd_256:
16718 IsTestPacked = true; // Fallthrough
16719 case Intrinsic::x86_sse41_ptestz:
16720 case Intrinsic::x86_avx_ptestz_256:
16722 X86CC = X86::COND_E;
16724 case Intrinsic::x86_avx_vtestc_ps:
16725 case Intrinsic::x86_avx_vtestc_pd:
16726 case Intrinsic::x86_avx_vtestc_ps_256:
16727 case Intrinsic::x86_avx_vtestc_pd_256:
16728 IsTestPacked = true; // Fallthrough
16729 case Intrinsic::x86_sse41_ptestc:
16730 case Intrinsic::x86_avx_ptestc_256:
16732 X86CC = X86::COND_B;
16734 case Intrinsic::x86_avx_vtestnzc_ps:
16735 case Intrinsic::x86_avx_vtestnzc_pd:
16736 case Intrinsic::x86_avx_vtestnzc_ps_256:
16737 case Intrinsic::x86_avx_vtestnzc_pd_256:
16738 IsTestPacked = true; // Fallthrough
16739 case Intrinsic::x86_sse41_ptestnzc:
16740 case Intrinsic::x86_avx_ptestnzc_256:
16742 X86CC = X86::COND_A;
16746 SDValue LHS = Op.getOperand(1);
16747 SDValue RHS = Op.getOperand(2);
16748 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
16749 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
16750 SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
16751 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
16752 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16754 case Intrinsic::x86_avx512_kortestz_w:
16755 case Intrinsic::x86_avx512_kortestc_w: {
16756 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
16757 SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
16758 SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
16759 SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
16760 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
16761 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
16762 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16765 case Intrinsic::x86_sse42_pcmpistria128:
16766 case Intrinsic::x86_sse42_pcmpestria128:
16767 case Intrinsic::x86_sse42_pcmpistric128:
16768 case Intrinsic::x86_sse42_pcmpestric128:
16769 case Intrinsic::x86_sse42_pcmpistrio128:
16770 case Intrinsic::x86_sse42_pcmpestrio128:
16771 case Intrinsic::x86_sse42_pcmpistris128:
16772 case Intrinsic::x86_sse42_pcmpestris128:
16773 case Intrinsic::x86_sse42_pcmpistriz128:
16774 case Intrinsic::x86_sse42_pcmpestriz128: {
16778 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
16779 case Intrinsic::x86_sse42_pcmpistria128:
16780 Opcode = X86ISD::PCMPISTRI;
16781 X86CC = X86::COND_A;
16783 case Intrinsic::x86_sse42_pcmpestria128:
16784 Opcode = X86ISD::PCMPESTRI;
16785 X86CC = X86::COND_A;
16787 case Intrinsic::x86_sse42_pcmpistric128:
16788 Opcode = X86ISD::PCMPISTRI;
16789 X86CC = X86::COND_B;
16791 case Intrinsic::x86_sse42_pcmpestric128:
16792 Opcode = X86ISD::PCMPESTRI;
16793 X86CC = X86::COND_B;
16795 case Intrinsic::x86_sse42_pcmpistrio128:
16796 Opcode = X86ISD::PCMPISTRI;
16797 X86CC = X86::COND_O;
16799 case Intrinsic::x86_sse42_pcmpestrio128:
16800 Opcode = X86ISD::PCMPESTRI;
16801 X86CC = X86::COND_O;
16803 case Intrinsic::x86_sse42_pcmpistris128:
16804 Opcode = X86ISD::PCMPISTRI;
16805 X86CC = X86::COND_S;
16807 case Intrinsic::x86_sse42_pcmpestris128:
16808 Opcode = X86ISD::PCMPESTRI;
16809 X86CC = X86::COND_S;
16811 case Intrinsic::x86_sse42_pcmpistriz128:
16812 Opcode = X86ISD::PCMPISTRI;
16813 X86CC = X86::COND_E;
16815 case Intrinsic::x86_sse42_pcmpestriz128:
16816 Opcode = X86ISD::PCMPESTRI;
16817 X86CC = X86::COND_E;
16820 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16821 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16822 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
16823 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16824 DAG.getConstant(X86CC, dl, MVT::i8),
16825 SDValue(PCMP.getNode(), 1));
16826 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
16829 case Intrinsic::x86_sse42_pcmpistri128:
16830 case Intrinsic::x86_sse42_pcmpestri128: {
16832 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
16833 Opcode = X86ISD::PCMPISTRI;
16835 Opcode = X86ISD::PCMPESTRI;
16837 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
16838 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
16839 return DAG.getNode(Opcode, dl, VTs, NewOps);
16842 case Intrinsic::x86_seh_lsda: {
16843 // Compute the symbol for the LSDA. We know it'll get emitted later.
16844 MachineFunction &MF = DAG.getMachineFunction();
16845 SDValue Op1 = Op.getOperand(1);
16846 auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
16847 MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
16848 GlobalValue::getRealLinkageName(Fn->getName()));
16850 // Generate a simple absolute symbol reference. This intrinsic is only
16851 // supported on 32-bit Windows, which isn't PIC.
16852 SDValue Result = DAG.getMCSymbol(LSDASym, VT);
16853 return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
16856 case Intrinsic::x86_seh_recoverfp: {
16857 SDValue FnOp = Op.getOperand(1);
16858 SDValue IncomingFPOp = Op.getOperand(2);
16859 GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
16860 auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
16862 report_fatal_error(
16863 "llvm.x86.seh.recoverfp must take a function as the first argument");
16864 return recoverFramePointer(DAG, Fn, IncomingFPOp);
16867 case Intrinsic::localaddress: {
16868 // Returns one of the stack, base, or frame pointer registers, depending on
16869 // which is used to reference local variables.
16870 MachineFunction &MF = DAG.getMachineFunction();
16871 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16873 if (RegInfo->hasBasePointer(MF))
16874 Reg = RegInfo->getBaseRegister();
16875 else // This function handles the SP or FP case.
16876 Reg = RegInfo->getPtrSizedFrameRegister(MF);
16877 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
16882 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16883 SDValue Src, SDValue Mask, SDValue Base,
16884 SDValue Index, SDValue ScaleOp, SDValue Chain,
16885 const X86Subtarget * Subtarget) {
16887 auto *C = cast<ConstantSDNode>(ScaleOp);
16888 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16889 MVT MaskVT = MVT::getVectorVT(MVT::i1,
16890 Index.getSimpleValueType().getVectorNumElements());
16892 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16894 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16896 MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16897 Mask.getSimpleValueType().getSizeInBits());
16899 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16900 // are extracted by EXTRACT_SUBVECTOR.
16901 MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16902 DAG.getBitcast(BitcastVT, Mask),
16903 DAG.getIntPtrConstant(0, dl));
16905 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
16906 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16907 SDValue Segment = DAG.getRegister(0, MVT::i32);
16908 if (Src.getOpcode() == ISD::UNDEF)
16909 Src = getZeroVector(Op.getSimpleValueType(), Subtarget, DAG, dl);
16910 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16911 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16912 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
16913 return DAG.getMergeValues(RetOps, dl);
16916 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16917 SDValue Src, SDValue Mask, SDValue Base,
16918 SDValue Index, SDValue ScaleOp, SDValue Chain) {
16920 auto *C = cast<ConstantSDNode>(ScaleOp);
16921 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16922 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16923 SDValue Segment = DAG.getRegister(0, MVT::i32);
16924 MVT MaskVT = MVT::getVectorVT(MVT::i1,
16925 Index.getSimpleValueType().getVectorNumElements());
16927 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16929 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16931 MVT BitcastVT = MVT::getVectorVT(MVT::i1,
16932 Mask.getSimpleValueType().getSizeInBits());
16934 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16935 // are extracted by EXTRACT_SUBVECTOR.
16936 MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16937 DAG.getBitcast(BitcastVT, Mask),
16938 DAG.getIntPtrConstant(0, dl));
16940 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
16941 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
16942 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
16943 return SDValue(Res, 1);
16946 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
16947 SDValue Mask, SDValue Base, SDValue Index,
16948 SDValue ScaleOp, SDValue Chain) {
16950 auto *C = cast<ConstantSDNode>(ScaleOp);
16951 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
16952 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
16953 SDValue Segment = DAG.getRegister(0, MVT::i32);
16955 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
16957 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
16959 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
16961 MaskInReg = DAG.getBitcast(MaskVT, Mask);
16962 //SDVTList VTs = DAG.getVTList(MVT::Other);
16963 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
16964 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
16965 return SDValue(Res, 0);
16968 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
16969 // read performance monitor counters (x86_rdpmc).
16970 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
16971 SelectionDAG &DAG, const X86Subtarget *Subtarget,
16972 SmallVectorImpl<SDValue> &Results) {
16973 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16974 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16977 // The ECX register is used to select the index of the performance counter
16979 SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
16981 SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
16983 // Reads the content of a 64-bit performance counter and returns it in the
16984 // registers EDX:EAX.
16985 if (Subtarget->is64Bit()) {
16986 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16987 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16990 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16991 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16994 Chain = HI.getValue(1);
16996 if (Subtarget->is64Bit()) {
16997 // The EAX register is loaded with the low-order 32 bits. The EDX register
16998 // is loaded with the supported high-order bits of the counter.
16999 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
17000 DAG.getConstant(32, DL, MVT::i8));
17001 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
17002 Results.push_back(Chain);
17006 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
17007 SDValue Ops[] = { LO, HI };
17008 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
17009 Results.push_back(Pair);
17010 Results.push_back(Chain);
17013 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
17014 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
17015 // also used to custom lower READCYCLECOUNTER nodes.
17016 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
17017 SelectionDAG &DAG, const X86Subtarget *Subtarget,
17018 SmallVectorImpl<SDValue> &Results) {
17019 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17020 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
17023 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
17024 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
17025 // and the EAX register is loaded with the low-order 32 bits.
17026 if (Subtarget->is64Bit()) {
17027 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
17028 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
17031 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
17032 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
17035 SDValue Chain = HI.getValue(1);
17037 if (Opcode == X86ISD::RDTSCP_DAG) {
17038 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
17040 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
17041 // the ECX register. Add 'ecx' explicitly to the chain.
17042 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
17044 // Explicitly store the content of ECX at the location passed in input
17045 // to the 'rdtscp' intrinsic.
17046 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
17047 MachinePointerInfo(), false, false, 0);
17050 if (Subtarget->is64Bit()) {
17051 // The EDX register is loaded with the high-order 32 bits of the MSR, and
17052 // the EAX register is loaded with the low-order 32 bits.
17053 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
17054 DAG.getConstant(32, DL, MVT::i8));
17055 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
17056 Results.push_back(Chain);
17060 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
17061 SDValue Ops[] = { LO, HI };
17062 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
17063 Results.push_back(Pair);
17064 Results.push_back(Chain);
17067 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
17068 SelectionDAG &DAG) {
17069 SmallVector<SDValue, 2> Results;
17071 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
17073 return DAG.getMergeValues(Results, DL);
17076 static SDValue LowerSEHRESTOREFRAME(SDValue Op, const X86Subtarget *Subtarget,
17077 SelectionDAG &DAG) {
17078 MachineFunction &MF = DAG.getMachineFunction();
17079 const Function *Fn = MF.getFunction();
17081 SDValue Chain = Op.getOperand(0);
17083 assert(Subtarget->getFrameLowering()->hasFP(MF) &&
17084 "using llvm.x86.seh.restoreframe requires a frame pointer");
17086 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17087 MVT VT = TLI.getPointerTy(DAG.getDataLayout());
17089 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17090 unsigned FrameReg =
17091 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17092 unsigned SPReg = RegInfo->getStackRegister();
17093 unsigned SlotSize = RegInfo->getSlotSize();
17095 // Get incoming EBP.
17096 SDValue IncomingEBP =
17097 DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
17099 // SP is saved in the first field of every registration node, so load
17100 // [EBP-RegNodeSize] into SP.
17101 int RegNodeSize = getSEHRegistrationNodeSize(Fn);
17102 SDValue SPAddr = DAG.getNode(ISD::ADD, dl, VT, IncomingEBP,
17103 DAG.getConstant(-RegNodeSize, dl, VT));
17105 DAG.getLoad(VT, dl, Chain, SPAddr, MachinePointerInfo(), false, false,
17106 false, VT.getScalarSizeInBits() / 8);
17107 Chain = DAG.getCopyToReg(Chain, dl, SPReg, NewSP);
17109 if (!RegInfo->needsStackRealignment(MF)) {
17110 // Adjust EBP to point back to the original frame position.
17111 SDValue NewFP = recoverFramePointer(DAG, Fn, IncomingEBP);
17112 Chain = DAG.getCopyToReg(Chain, dl, FrameReg, NewFP);
17114 assert(RegInfo->hasBasePointer(MF) &&
17115 "functions with Win32 EH must use frame or base pointer register");
17117 // Reload the base pointer (ESI) with the adjusted incoming EBP.
17118 SDValue NewBP = recoverFramePointer(DAG, Fn, IncomingEBP);
17119 Chain = DAG.getCopyToReg(Chain, dl, RegInfo->getBaseRegister(), NewBP);
17121 // Reload the spilled EBP value, now that the stack and base pointers are
17123 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
17124 X86FI->setHasSEHFramePtrSave(true);
17125 int FI = MF.getFrameInfo()->CreateSpillStackObject(SlotSize, SlotSize);
17126 X86FI->setSEHFramePtrSaveIndex(FI);
17127 SDValue NewFP = DAG.getLoad(VT, dl, Chain, DAG.getFrameIndex(FI, VT),
17128 MachinePointerInfo(), false, false, false,
17129 VT.getScalarSizeInBits() / 8);
17130 Chain = DAG.getCopyToReg(NewFP, dl, FrameReg, NewFP);
17136 static SDValue MarkEHRegistrationNode(SDValue Op, SelectionDAG &DAG) {
17137 MachineFunction &MF = DAG.getMachineFunction();
17138 SDValue Chain = Op.getOperand(0);
17139 SDValue RegNode = Op.getOperand(2);
17140 WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
17142 report_fatal_error("EH registrations only live in functions using WinEH");
17144 // Cast the operand to an alloca, and remember the frame index.
17145 auto *FINode = dyn_cast<FrameIndexSDNode>(RegNode);
17147 report_fatal_error("llvm.x86.seh.ehregnode expects a static alloca");
17148 EHInfo->EHRegNodeFrameIndex = FINode->getIndex();
17150 // Return the chain operand without making any DAG nodes.
17154 /// \brief Lower intrinsics for TRUNCATE_TO_MEM case
17155 /// return truncate Store/MaskedStore Node
17156 static SDValue LowerINTRINSIC_TRUNCATE_TO_MEM(const SDValue & Op,
17160 SDValue Mask = Op.getOperand(4);
17161 SDValue DataToTruncate = Op.getOperand(3);
17162 SDValue Addr = Op.getOperand(2);
17163 SDValue Chain = Op.getOperand(0);
17165 MVT VT = DataToTruncate.getSimpleValueType();
17166 MVT SVT = MVT::getVectorVT(ElementType, VT.getVectorNumElements());
17168 if (isAllOnesConstant(Mask)) // return just a truncate store
17169 return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr,
17170 MachinePointerInfo(), SVT, false, false,
17171 SVT.getScalarSizeInBits()/8);
17173 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
17174 MVT BitcastVT = MVT::getVectorVT(MVT::i1,
17175 Mask.getSimpleValueType().getSizeInBits());
17176 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
17177 // are extracted by EXTRACT_SUBVECTOR.
17178 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
17179 DAG.getBitcast(BitcastVT, Mask),
17180 DAG.getIntPtrConstant(0, dl));
17182 MachineMemOperand *MMO = DAG.getMachineFunction().
17183 getMachineMemOperand(MachinePointerInfo(),
17184 MachineMemOperand::MOStore, SVT.getStoreSize(),
17185 SVT.getScalarSizeInBits()/8);
17187 return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr,
17188 VMask, SVT, MMO, true);
17191 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
17192 SelectionDAG &DAG) {
17193 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
17195 const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
17197 if (IntNo == llvm::Intrinsic::x86_seh_restoreframe)
17198 return LowerSEHRESTOREFRAME(Op, Subtarget, DAG);
17199 else if (IntNo == llvm::Intrinsic::x86_seh_ehregnode)
17200 return MarkEHRegistrationNode(Op, DAG);
17205 switch(IntrData->Type) {
17206 default: llvm_unreachable("Unknown Intrinsic Type");
17209 // Emit the node with the right value type.
17210 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
17211 SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17213 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
17214 // Otherwise return the value from Rand, which is always 0, casted to i32.
17215 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
17216 DAG.getConstant(1, dl, Op->getValueType(1)),
17217 DAG.getConstant(X86::COND_B, dl, MVT::i32),
17218 SDValue(Result.getNode(), 1) };
17219 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
17220 DAG.getVTList(Op->getValueType(1), MVT::Glue),
17223 // Return { result, isValid, chain }.
17224 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
17225 SDValue(Result.getNode(), 2));
17228 //gather(v1, mask, index, base, scale);
17229 SDValue Chain = Op.getOperand(0);
17230 SDValue Src = Op.getOperand(2);
17231 SDValue Base = Op.getOperand(3);
17232 SDValue Index = Op.getOperand(4);
17233 SDValue Mask = Op.getOperand(5);
17234 SDValue Scale = Op.getOperand(6);
17235 return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
17239 //scatter(base, mask, index, v1, scale);
17240 SDValue Chain = Op.getOperand(0);
17241 SDValue Base = Op.getOperand(2);
17242 SDValue Mask = Op.getOperand(3);
17243 SDValue Index = Op.getOperand(4);
17244 SDValue Src = Op.getOperand(5);
17245 SDValue Scale = Op.getOperand(6);
17246 return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
17250 SDValue Hint = Op.getOperand(6);
17251 unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
17252 assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
17253 unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
17254 SDValue Chain = Op.getOperand(0);
17255 SDValue Mask = Op.getOperand(2);
17256 SDValue Index = Op.getOperand(3);
17257 SDValue Base = Op.getOperand(4);
17258 SDValue Scale = Op.getOperand(5);
17259 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
17261 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
17263 SmallVector<SDValue, 2> Results;
17264 getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
17266 return DAG.getMergeValues(Results, dl);
17268 // Read Performance Monitoring Counters.
17270 SmallVector<SDValue, 2> Results;
17271 getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
17272 return DAG.getMergeValues(Results, dl);
17274 // XTEST intrinsics.
17276 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17277 SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
17278 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17279 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
17281 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
17282 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
17283 Ret, SDValue(InTrans.getNode(), 1));
17287 SmallVector<SDValue, 2> Results;
17288 SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
17289 SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
17290 SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
17291 DAG.getConstant(-1, dl, MVT::i8));
17292 SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
17293 Op.getOperand(4), GenCF.getValue(1));
17294 SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
17295 Op.getOperand(5), MachinePointerInfo(),
17297 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17298 DAG.getConstant(X86::COND_B, dl, MVT::i8),
17300 Results.push_back(SetCC);
17301 Results.push_back(Store);
17302 return DAG.getMergeValues(Results, dl);
17304 case COMPRESS_TO_MEM: {
17306 SDValue Mask = Op.getOperand(4);
17307 SDValue DataToCompress = Op.getOperand(3);
17308 SDValue Addr = Op.getOperand(2);
17309 SDValue Chain = Op.getOperand(0);
17311 MVT VT = DataToCompress.getSimpleValueType();
17312 if (isAllOnesConstant(Mask)) // return just a store
17313 return DAG.getStore(Chain, dl, DataToCompress, Addr,
17314 MachinePointerInfo(), false, false,
17315 VT.getScalarSizeInBits()/8);
17317 SDValue Compressed =
17318 getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
17319 Mask, DAG.getUNDEF(VT), Subtarget, DAG);
17320 return DAG.getStore(Chain, dl, Compressed, Addr,
17321 MachinePointerInfo(), false, false,
17322 VT.getScalarSizeInBits()/8);
17324 case TRUNCATE_TO_MEM_VI8:
17325 return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i8);
17326 case TRUNCATE_TO_MEM_VI16:
17327 return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i16);
17328 case TRUNCATE_TO_MEM_VI32:
17329 return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i32);
17330 case EXPAND_FROM_MEM: {
17332 SDValue Mask = Op.getOperand(4);
17333 SDValue PassThru = Op.getOperand(3);
17334 SDValue Addr = Op.getOperand(2);
17335 SDValue Chain = Op.getOperand(0);
17336 MVT VT = Op.getSimpleValueType();
17338 if (isAllOnesConstant(Mask)) // return just a load
17339 return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
17340 false, VT.getScalarSizeInBits()/8);
17342 SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
17343 false, false, false,
17344 VT.getScalarSizeInBits()/8);
17346 SDValue Results[] = {
17347 getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
17348 Mask, PassThru, Subtarget, DAG), Chain};
17349 return DAG.getMergeValues(Results, dl);
17354 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
17355 SelectionDAG &DAG) const {
17356 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
17357 MFI->setReturnAddressIsTaken(true);
17359 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
17362 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17364 EVT PtrVT = getPointerTy(DAG.getDataLayout());
17367 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
17368 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17369 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
17370 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17371 DAG.getNode(ISD::ADD, dl, PtrVT,
17372 FrameAddr, Offset),
17373 MachinePointerInfo(), false, false, false, 0);
17376 // Just load the return address.
17377 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
17378 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
17379 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
17382 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
17383 MachineFunction &MF = DAG.getMachineFunction();
17384 MachineFrameInfo *MFI = MF.getFrameInfo();
17385 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
17386 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17387 EVT VT = Op.getValueType();
17389 MFI->setFrameAddressIsTaken(true);
17391 if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
17392 // Depth > 0 makes no sense on targets which use Windows unwind codes. It
17393 // is not possible to crawl up the stack without looking at the unwind codes
17395 int FrameAddrIndex = FuncInfo->getFAIndex();
17396 if (!FrameAddrIndex) {
17397 // Set up a frame object for the return address.
17398 unsigned SlotSize = RegInfo->getSlotSize();
17399 FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
17400 SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
17401 FuncInfo->setFAIndex(FrameAddrIndex);
17403 return DAG.getFrameIndex(FrameAddrIndex, VT);
17406 unsigned FrameReg =
17407 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17408 SDLoc dl(Op); // FIXME probably not meaningful
17409 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17410 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
17411 (FrameReg == X86::EBP && VT == MVT::i32)) &&
17412 "Invalid Frame Register!");
17413 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
17415 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
17416 MachinePointerInfo(),
17417 false, false, false, 0);
17421 // FIXME? Maybe this could be a TableGen attribute on some registers and
17422 // this table could be generated automatically from RegInfo.
17423 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
17424 SelectionDAG &DAG) const {
17425 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17426 const MachineFunction &MF = DAG.getMachineFunction();
17428 unsigned Reg = StringSwitch<unsigned>(RegName)
17429 .Case("esp", X86::ESP)
17430 .Case("rsp", X86::RSP)
17431 .Case("ebp", X86::EBP)
17432 .Case("rbp", X86::RBP)
17435 if (Reg == X86::EBP || Reg == X86::RBP) {
17436 if (!TFI.hasFP(MF))
17437 report_fatal_error("register " + StringRef(RegName) +
17438 " is allocatable: function has no frame pointer");
17441 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17442 unsigned FrameReg =
17443 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
17444 assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
17445 "Invalid Frame Register!");
17453 report_fatal_error("Invalid register name global variable");
17456 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
17457 SelectionDAG &DAG) const {
17458 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17459 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
17462 unsigned X86TargetLowering::getExceptionPointerRegister(
17463 const Constant *PersonalityFn) const {
17464 if (classifyEHPersonality(PersonalityFn) == EHPersonality::CoreCLR)
17465 return Subtarget->isTarget64BitLP64() ? X86::RDX : X86::EDX;
17467 return Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX;
17470 unsigned X86TargetLowering::getExceptionSelectorRegister(
17471 const Constant *PersonalityFn) const {
17472 // Funclet personalities don't use selectors (the runtime does the selection).
17473 assert(!isFuncletEHPersonality(classifyEHPersonality(PersonalityFn)));
17474 return Subtarget->isTarget64BitLP64() ? X86::RDX : X86::EDX;
17477 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
17478 SDValue Chain = Op.getOperand(0);
17479 SDValue Offset = Op.getOperand(1);
17480 SDValue Handler = Op.getOperand(2);
17483 EVT PtrVT = getPointerTy(DAG.getDataLayout());
17484 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
17485 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
17486 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
17487 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
17488 "Invalid Frame Register!");
17489 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
17490 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
17492 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
17493 DAG.getIntPtrConstant(RegInfo->getSlotSize(),
17495 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
17496 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
17498 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
17500 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
17501 DAG.getRegister(StoreAddrReg, PtrVT));
17504 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
17505 SelectionDAG &DAG) const {
17507 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
17508 DAG.getVTList(MVT::i32, MVT::Other),
17509 Op.getOperand(0), Op.getOperand(1));
17512 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
17513 SelectionDAG &DAG) const {
17515 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
17516 Op.getOperand(0), Op.getOperand(1));
17519 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
17520 return Op.getOperand(0);
17523 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
17524 SelectionDAG &DAG) const {
17525 SDValue Root = Op.getOperand(0);
17526 SDValue Trmp = Op.getOperand(1); // trampoline
17527 SDValue FPtr = Op.getOperand(2); // nested function
17528 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
17531 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
17532 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
17534 if (Subtarget->is64Bit()) {
17535 SDValue OutChains[6];
17537 // Large code-model.
17538 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
17539 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
17541 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
17542 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
17544 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
17546 // Load the pointer to the nested function into R11.
17547 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
17548 SDValue Addr = Trmp;
17549 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17550 Addr, MachinePointerInfo(TrmpAddr),
17553 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17554 DAG.getConstant(2, dl, MVT::i64));
17555 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
17556 MachinePointerInfo(TrmpAddr, 2),
17559 // Load the 'nest' parameter value into R10.
17560 // R10 is specified in X86CallingConv.td
17561 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
17562 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17563 DAG.getConstant(10, dl, MVT::i64));
17564 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17565 Addr, MachinePointerInfo(TrmpAddr, 10),
17568 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17569 DAG.getConstant(12, dl, MVT::i64));
17570 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
17571 MachinePointerInfo(TrmpAddr, 12),
17574 // Jump to the nested function.
17575 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
17576 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17577 DAG.getConstant(20, dl, MVT::i64));
17578 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
17579 Addr, MachinePointerInfo(TrmpAddr, 20),
17582 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
17583 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
17584 DAG.getConstant(22, dl, MVT::i64));
17585 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
17586 Addr, MachinePointerInfo(TrmpAddr, 22),
17589 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17591 const Function *Func =
17592 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
17593 CallingConv::ID CC = Func->getCallingConv();
17598 llvm_unreachable("Unsupported calling convention");
17599 case CallingConv::C:
17600 case CallingConv::X86_StdCall: {
17601 // Pass 'nest' parameter in ECX.
17602 // Must be kept in sync with X86CallingConv.td
17603 NestReg = X86::ECX;
17605 // Check that ECX wasn't needed by an 'inreg' parameter.
17606 FunctionType *FTy = Func->getFunctionType();
17607 const AttributeSet &Attrs = Func->getAttributes();
17609 if (!Attrs.isEmpty() && !Func->isVarArg()) {
17610 unsigned InRegCount = 0;
17613 for (FunctionType::param_iterator I = FTy->param_begin(),
17614 E = FTy->param_end(); I != E; ++I, ++Idx)
17615 if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
17616 auto &DL = DAG.getDataLayout();
17617 // FIXME: should only count parameters that are lowered to integers.
17618 InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
17621 if (InRegCount > 2) {
17622 report_fatal_error("Nest register in use - reduce number of inreg"
17628 case CallingConv::X86_FastCall:
17629 case CallingConv::X86_ThisCall:
17630 case CallingConv::Fast:
17631 // Pass 'nest' parameter in EAX.
17632 // Must be kept in sync with X86CallingConv.td
17633 NestReg = X86::EAX;
17637 SDValue OutChains[4];
17638 SDValue Addr, Disp;
17640 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17641 DAG.getConstant(10, dl, MVT::i32));
17642 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
17644 // This is storing the opcode for MOV32ri.
17645 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
17646 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
17647 OutChains[0] = DAG.getStore(Root, dl,
17648 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
17649 Trmp, MachinePointerInfo(TrmpAddr),
17652 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17653 DAG.getConstant(1, dl, MVT::i32));
17654 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
17655 MachinePointerInfo(TrmpAddr, 1),
17658 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
17659 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17660 DAG.getConstant(5, dl, MVT::i32));
17661 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
17662 Addr, MachinePointerInfo(TrmpAddr, 5),
17665 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
17666 DAG.getConstant(6, dl, MVT::i32));
17667 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
17668 MachinePointerInfo(TrmpAddr, 6),
17671 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
17675 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
17676 SelectionDAG &DAG) const {
17678 The rounding mode is in bits 11:10 of FPSR, and has the following
17680 00 Round to nearest
17685 FLT_ROUNDS, on the other hand, expects the following:
17692 To perform the conversion, we do:
17693 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
17696 MachineFunction &MF = DAG.getMachineFunction();
17697 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
17698 unsigned StackAlignment = TFI.getStackAlignment();
17699 MVT VT = Op.getSimpleValueType();
17702 // Save FP Control Word to stack slot
17703 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
17704 SDValue StackSlot =
17705 DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
17707 MachineMemOperand *MMO =
17708 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, SSFI),
17709 MachineMemOperand::MOStore, 2, 2);
17711 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
17712 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
17713 DAG.getVTList(MVT::Other),
17714 Ops, MVT::i16, MMO);
17716 // Load FP Control Word from stack slot
17717 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
17718 MachinePointerInfo(), false, false, false, 0);
17720 // Transform as necessary
17722 DAG.getNode(ISD::SRL, DL, MVT::i16,
17723 DAG.getNode(ISD::AND, DL, MVT::i16,
17724 CWD, DAG.getConstant(0x800, DL, MVT::i16)),
17725 DAG.getConstant(11, DL, MVT::i8));
17727 DAG.getNode(ISD::SRL, DL, MVT::i16,
17728 DAG.getNode(ISD::AND, DL, MVT::i16,
17729 CWD, DAG.getConstant(0x400, DL, MVT::i16)),
17730 DAG.getConstant(9, DL, MVT::i8));
17733 DAG.getNode(ISD::AND, DL, MVT::i16,
17734 DAG.getNode(ISD::ADD, DL, MVT::i16,
17735 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
17736 DAG.getConstant(1, DL, MVT::i16)),
17737 DAG.getConstant(3, DL, MVT::i16));
17739 return DAG.getNode((VT.getSizeInBits() < 16 ?
17740 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
17743 /// \brief Lower a vector CTLZ using native supported vector CTLZ instruction.
17745 // 1. i32/i64 128/256-bit vector (native support require VLX) are expended
17746 // to 512-bit vector.
17747 // 2. i8/i16 vector implemented using dword LZCNT vector instruction
17748 // ( sub(trunc(lzcnt(zext32(x)))) ). In case zext32(x) is illegal,
17749 // split the vector, perform operation on it's Lo a Hi part and
17750 // concatenate the results.
17751 static SDValue LowerVectorCTLZ_AVX512(SDValue Op, SelectionDAG &DAG) {
17753 MVT VT = Op.getSimpleValueType();
17754 MVT EltVT = VT.getVectorElementType();
17755 unsigned NumElems = VT.getVectorNumElements();
17757 if (EltVT == MVT::i64 || EltVT == MVT::i32) {
17758 // Extend to 512 bit vector.
17759 assert((VT.is256BitVector() || VT.is128BitVector()) &&
17760 "Unsupported value type for operation");
17762 MVT NewVT = MVT::getVectorVT(EltVT, 512 / VT.getScalarSizeInBits());
17763 SDValue Vec512 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, NewVT,
17764 DAG.getUNDEF(NewVT),
17766 DAG.getIntPtrConstant(0, dl));
17767 SDValue CtlzNode = DAG.getNode(ISD::CTLZ, dl, NewVT, Vec512);
17769 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, CtlzNode,
17770 DAG.getIntPtrConstant(0, dl));
17773 assert((EltVT == MVT::i8 || EltVT == MVT::i16) &&
17774 "Unsupported element type");
17776 if (16 < NumElems) {
17777 // Split vector, it's Lo and Hi parts will be handled in next iteration.
17779 std::tie(Lo, Hi) = DAG.SplitVector(Op.getOperand(0), dl);
17780 MVT OutVT = MVT::getVectorVT(EltVT, NumElems/2);
17782 Lo = DAG.getNode(Op.getOpcode(), dl, OutVT, Lo);
17783 Hi = DAG.getNode(Op.getOpcode(), dl, OutVT, Hi);
17785 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lo, Hi);
17788 MVT NewVT = MVT::getVectorVT(MVT::i32, NumElems);
17790 assert((NewVT.is256BitVector() || NewVT.is512BitVector()) &&
17791 "Unsupported value type for operation");
17793 // Use native supported vector instruction vplzcntd.
17794 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, NewVT, Op.getOperand(0));
17795 SDValue CtlzNode = DAG.getNode(ISD::CTLZ, dl, NewVT, Op);
17796 SDValue TruncNode = DAG.getNode(ISD::TRUNCATE, dl, VT, CtlzNode);
17797 SDValue Delta = DAG.getConstant(32 - EltVT.getSizeInBits(), dl, VT);
17799 return DAG.getNode(ISD::SUB, dl, VT, TruncNode, Delta);
17802 static SDValue LowerCTLZ(SDValue Op, const X86Subtarget *Subtarget,
17803 SelectionDAG &DAG) {
17804 MVT VT = Op.getSimpleValueType();
17806 unsigned NumBits = VT.getSizeInBits();
17809 if (VT.isVector() && Subtarget->hasAVX512())
17810 return LowerVectorCTLZ_AVX512(Op, DAG);
17812 Op = Op.getOperand(0);
17813 if (VT == MVT::i8) {
17814 // Zero extend to i32 since there is not an i8 bsr.
17816 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17819 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
17820 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17821 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17823 // If src is zero (i.e. bsr sets ZF), returns NumBits.
17826 DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
17827 DAG.getConstant(X86::COND_E, dl, MVT::i8),
17830 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
17832 // Finally xor with NumBits-1.
17833 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
17834 DAG.getConstant(NumBits - 1, dl, OpVT));
17837 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17841 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, const X86Subtarget *Subtarget,
17842 SelectionDAG &DAG) {
17843 MVT VT = Op.getSimpleValueType();
17845 unsigned NumBits = VT.getSizeInBits();
17848 if (VT.isVector() && Subtarget->hasAVX512())
17849 return LowerVectorCTLZ_AVX512(Op, DAG);
17851 Op = Op.getOperand(0);
17852 if (VT == MVT::i8) {
17853 // Zero extend to i32 since there is not an i8 bsr.
17855 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
17858 // Issue a bsr (scan bits in reverse).
17859 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
17860 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
17862 // And xor with NumBits-1.
17863 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
17864 DAG.getConstant(NumBits - 1, dl, OpVT));
17867 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
17871 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
17872 MVT VT = Op.getSimpleValueType();
17873 unsigned NumBits = VT.getScalarSizeInBits();
17876 if (VT.isVector()) {
17877 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17879 SDValue N0 = Op.getOperand(0);
17880 SDValue Zero = DAG.getConstant(0, dl, VT);
17882 // lsb(x) = (x & -x)
17883 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, N0,
17884 DAG.getNode(ISD::SUB, dl, VT, Zero, N0));
17886 // cttz_undef(x) = (width - 1) - ctlz(lsb)
17887 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF &&
17888 TLI.isOperationLegal(ISD::CTLZ, VT)) {
17889 SDValue WidthMinusOne = DAG.getConstant(NumBits - 1, dl, VT);
17890 return DAG.getNode(ISD::SUB, dl, VT, WidthMinusOne,
17891 DAG.getNode(ISD::CTLZ, dl, VT, LSB));
17894 // cttz(x) = ctpop(lsb - 1)
17895 SDValue One = DAG.getConstant(1, dl, VT);
17896 return DAG.getNode(ISD::CTPOP, dl, VT,
17897 DAG.getNode(ISD::SUB, dl, VT, LSB, One));
17900 assert(Op.getOpcode() == ISD::CTTZ &&
17901 "Only scalar CTTZ requires custom lowering");
17903 // Issue a bsf (scan bits forward) which also sets EFLAGS.
17904 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17905 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op.getOperand(0));
17907 // If src is zero (i.e. bsf sets ZF), returns NumBits.
17910 DAG.getConstant(NumBits, dl, VT),
17911 DAG.getConstant(X86::COND_E, dl, MVT::i8),
17914 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
17917 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
17918 // ones, and then concatenate the result back.
17919 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
17920 MVT VT = Op.getSimpleValueType();
17922 assert(VT.is256BitVector() && VT.isInteger() &&
17923 "Unsupported value type for operation");
17925 unsigned NumElems = VT.getVectorNumElements();
17928 // Extract the LHS vectors
17929 SDValue LHS = Op.getOperand(0);
17930 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
17931 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
17933 // Extract the RHS vectors
17934 SDValue RHS = Op.getOperand(1);
17935 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
17936 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
17938 MVT EltVT = VT.getVectorElementType();
17939 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17941 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
17942 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
17943 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
17946 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
17947 if (Op.getValueType() == MVT::i1)
17948 return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17949 Op.getOperand(0), Op.getOperand(1));
17950 assert(Op.getSimpleValueType().is256BitVector() &&
17951 Op.getSimpleValueType().isInteger() &&
17952 "Only handle AVX 256-bit vector integer operation");
17953 return Lower256IntArith(Op, DAG);
17956 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
17957 if (Op.getValueType() == MVT::i1)
17958 return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
17959 Op.getOperand(0), Op.getOperand(1));
17960 assert(Op.getSimpleValueType().is256BitVector() &&
17961 Op.getSimpleValueType().isInteger() &&
17962 "Only handle AVX 256-bit vector integer operation");
17963 return Lower256IntArith(Op, DAG);
17966 static SDValue LowerMINMAX(SDValue Op, SelectionDAG &DAG) {
17967 assert(Op.getSimpleValueType().is256BitVector() &&
17968 Op.getSimpleValueType().isInteger() &&
17969 "Only handle AVX 256-bit vector integer operation");
17970 return Lower256IntArith(Op, DAG);
17973 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
17974 SelectionDAG &DAG) {
17976 MVT VT = Op.getSimpleValueType();
17979 return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
17981 // Decompose 256-bit ops into smaller 128-bit ops.
17982 if (VT.is256BitVector() && !Subtarget->hasInt256())
17983 return Lower256IntArith(Op, DAG);
17985 SDValue A = Op.getOperand(0);
17986 SDValue B = Op.getOperand(1);
17988 // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
17989 // pairs, multiply and truncate.
17990 if (VT == MVT::v16i8 || VT == MVT::v32i8) {
17991 if (Subtarget->hasInt256()) {
17992 if (VT == MVT::v32i8) {
17993 MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
17994 SDValue Lo = DAG.getIntPtrConstant(0, dl);
17995 SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
17996 SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
17997 SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
17998 SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
17999 SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
18000 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
18001 DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
18002 DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
18005 MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
18006 return DAG.getNode(
18007 ISD::TRUNCATE, dl, VT,
18008 DAG.getNode(ISD::MUL, dl, ExVT,
18009 DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
18010 DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
18013 assert(VT == MVT::v16i8 &&
18014 "Pre-AVX2 support only supports v16i8 multiplication");
18015 MVT ExVT = MVT::v8i16;
18017 // Extract the lo parts and sign extend to i16
18019 if (Subtarget->hasSSE41()) {
18020 ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
18021 BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
18023 const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
18024 -1, 4, -1, 5, -1, 6, -1, 7};
18025 ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
18026 BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
18027 ALo = DAG.getBitcast(ExVT, ALo);
18028 BLo = DAG.getBitcast(ExVT, BLo);
18029 ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
18030 BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
18033 // Extract the hi parts and sign extend to i16
18035 if (Subtarget->hasSSE41()) {
18036 const int ShufMask[] = {8, 9, 10, 11, 12, 13, 14, 15,
18037 -1, -1, -1, -1, -1, -1, -1, -1};
18038 AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
18039 BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
18040 AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
18041 BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
18043 const int ShufMask[] = {-1, 8, -1, 9, -1, 10, -1, 11,
18044 -1, 12, -1, 13, -1, 14, -1, 15};
18045 AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
18046 BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
18047 AHi = DAG.getBitcast(ExVT, AHi);
18048 BHi = DAG.getBitcast(ExVT, BHi);
18049 AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
18050 BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
18053 // Multiply, mask the lower 8bits of the lo/hi results and pack
18054 SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
18055 SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
18056 RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
18057 RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
18058 return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
18061 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
18062 if (VT == MVT::v4i32) {
18063 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
18064 "Should not custom lower when pmuldq is available!");
18066 // Extract the odd parts.
18067 static const int UnpackMask[] = { 1, -1, 3, -1 };
18068 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
18069 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
18071 // Multiply the even parts.
18072 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
18073 // Now multiply odd parts.
18074 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
18076 Evens = DAG.getBitcast(VT, Evens);
18077 Odds = DAG.getBitcast(VT, Odds);
18079 // Merge the two vectors back together with a shuffle. This expands into 2
18081 static const int ShufMask[] = { 0, 4, 2, 6 };
18082 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
18085 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
18086 "Only know how to lower V2I64/V4I64/V8I64 multiply");
18088 // Ahi = psrlqi(a, 32);
18089 // Bhi = psrlqi(b, 32);
18091 // AloBlo = pmuludq(a, b);
18092 // AloBhi = pmuludq(a, Bhi);
18093 // AhiBlo = pmuludq(Ahi, b);
18095 // AloBhi = psllqi(AloBhi, 32);
18096 // AhiBlo = psllqi(AhiBlo, 32);
18097 // return AloBlo + AloBhi + AhiBlo;
18099 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
18100 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
18102 SDValue AhiBlo = Ahi;
18103 SDValue AloBhi = Bhi;
18104 // Bit cast to 32-bit vectors for MULUDQ
18105 MVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
18106 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
18107 A = DAG.getBitcast(MulVT, A);
18108 B = DAG.getBitcast(MulVT, B);
18109 Ahi = DAG.getBitcast(MulVT, Ahi);
18110 Bhi = DAG.getBitcast(MulVT, Bhi);
18112 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
18113 // After shifting right const values the result may be all-zero.
18114 if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
18115 AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
18116 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
18118 if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
18119 AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
18120 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
18123 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
18124 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
18127 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
18128 assert(Subtarget->isTargetWin64() && "Unexpected target");
18129 EVT VT = Op.getValueType();
18130 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
18131 "Unexpected return type for lowering");
18135 switch (Op->getOpcode()) {
18136 default: llvm_unreachable("Unexpected request for libcall!");
18137 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
18138 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
18139 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
18140 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
18141 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
18142 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
18146 SDValue InChain = DAG.getEntryNode();
18148 TargetLowering::ArgListTy Args;
18149 TargetLowering::ArgListEntry Entry;
18150 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
18151 EVT ArgVT = Op->getOperand(i).getValueType();
18152 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
18153 "Unexpected argument type for lowering");
18154 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
18155 Entry.Node = StackPtr;
18156 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
18158 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18159 Entry.Ty = PointerType::get(ArgTy,0);
18160 Entry.isSExt = false;
18161 Entry.isZExt = false;
18162 Args.push_back(Entry);
18165 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
18166 getPointerTy(DAG.getDataLayout()));
18168 TargetLowering::CallLoweringInfo CLI(DAG);
18169 CLI.setDebugLoc(dl).setChain(InChain)
18170 .setCallee(getLibcallCallingConv(LC),
18171 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
18172 Callee, std::move(Args), 0)
18173 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
18175 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
18176 return DAG.getBitcast(VT, CallInfo.first);
18179 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
18180 SelectionDAG &DAG) {
18181 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
18182 MVT VT = Op0.getSimpleValueType();
18185 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
18186 (VT == MVT::v8i32 && Subtarget->hasInt256()));
18188 // PMULxD operations multiply each even value (starting at 0) of LHS with
18189 // the related value of RHS and produce a widen result.
18190 // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
18191 // => <2 x i64> <ae|cg>
18193 // In other word, to have all the results, we need to perform two PMULxD:
18194 // 1. one with the even values.
18195 // 2. one with the odd values.
18196 // To achieve #2, with need to place the odd values at an even position.
18198 // Place the odd value at an even position (basically, shift all values 1
18199 // step to the left):
18200 const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
18201 // <a|b|c|d> => <b|undef|d|undef>
18202 SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
18203 // <e|f|g|h> => <f|undef|h|undef>
18204 SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
18206 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
18208 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
18209 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
18211 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
18212 // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
18213 // => <2 x i64> <ae|cg>
18214 SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
18215 // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
18216 // => <2 x i64> <bf|dh>
18217 SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
18219 // Shuffle it back into the right order.
18220 SDValue Highs, Lows;
18221 if (VT == MVT::v8i32) {
18222 const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
18223 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
18224 const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
18225 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
18227 const int HighMask[] = {1, 5, 3, 7};
18228 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
18229 const int LowMask[] = {0, 4, 2, 6};
18230 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
18233 // If we have a signed multiply but no PMULDQ fix up the high parts of a
18234 // unsigned multiply.
18235 if (IsSigned && !Subtarget->hasSSE41()) {
18236 SDValue ShAmt = DAG.getConstant(
18238 DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
18239 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
18240 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
18241 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
18242 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
18244 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
18245 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
18248 // The first result of MUL_LOHI is actually the low value, followed by the
18250 SDValue Ops[] = {Lows, Highs};
18251 return DAG.getMergeValues(Ops, dl);
18254 // Return true if the required (according to Opcode) shift-imm form is natively
18255 // supported by the Subtarget
18256 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
18258 if (VT.getScalarSizeInBits() < 16)
18261 if (VT.is512BitVector() &&
18262 (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
18265 bool LShift = VT.is128BitVector() ||
18266 (VT.is256BitVector() && Subtarget->hasInt256());
18268 bool AShift = LShift && (Subtarget->hasVLX() ||
18269 (VT != MVT::v2i64 && VT != MVT::v4i64));
18270 return (Opcode == ISD::SRA) ? AShift : LShift;
18273 // The shift amount is a variable, but it is the same for all vector lanes.
18274 // These instructions are defined together with shift-immediate.
18276 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
18278 return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
18281 // Return true if the required (according to Opcode) variable-shift form is
18282 // natively supported by the Subtarget
18283 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
18286 if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
18289 // vXi16 supported only on AVX-512, BWI
18290 if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
18293 if (VT.is512BitVector() || Subtarget->hasVLX())
18296 bool LShift = VT.is128BitVector() || VT.is256BitVector();
18297 bool AShift = LShift && VT != MVT::v2i64 && VT != MVT::v4i64;
18298 return (Opcode == ISD::SRA) ? AShift : LShift;
18301 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
18302 const X86Subtarget *Subtarget) {
18303 MVT VT = Op.getSimpleValueType();
18305 SDValue R = Op.getOperand(0);
18306 SDValue Amt = Op.getOperand(1);
18308 unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
18309 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
18311 auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
18312 assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
18313 MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
18314 SDValue Ex = DAG.getBitcast(ExVT, R);
18316 if (ShiftAmt >= 32) {
18317 // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
18319 getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
18320 SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
18321 ShiftAmt - 32, DAG);
18322 if (VT == MVT::v2i64)
18323 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
18324 if (VT == MVT::v4i64)
18325 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
18326 {9, 1, 11, 3, 13, 5, 15, 7});
18328 // SRA upper i32, SHL whole i64 and select lower i32.
18329 SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
18332 getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
18333 Lower = DAG.getBitcast(ExVT, Lower);
18334 if (VT == MVT::v2i64)
18335 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
18336 if (VT == MVT::v4i64)
18337 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
18338 {8, 1, 10, 3, 12, 5, 14, 7});
18340 return DAG.getBitcast(VT, Ex);
18343 // Optimize shl/srl/sra with constant shift amount.
18344 if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
18345 if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
18346 uint64_t ShiftAmt = ShiftConst->getZExtValue();
18348 if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
18349 return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
18351 // i64 SRA needs to be performed as partial shifts.
18352 if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
18353 Op.getOpcode() == ISD::SRA && !Subtarget->hasXOP())
18354 return ArithmeticShiftRight64(ShiftAmt);
18356 if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
18357 unsigned NumElts = VT.getVectorNumElements();
18358 MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
18360 // Simple i8 add case
18361 if (Op.getOpcode() == ISD::SHL && ShiftAmt == 1)
18362 return DAG.getNode(ISD::ADD, dl, VT, R, R);
18364 // ashr(R, 7) === cmp_slt(R, 0)
18365 if (Op.getOpcode() == ISD::SRA && ShiftAmt == 7) {
18366 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18367 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
18370 // XOP can shift v16i8 directly instead of as shift v8i16 + mask.
18371 if (VT == MVT::v16i8 && Subtarget->hasXOP())
18374 if (Op.getOpcode() == ISD::SHL) {
18375 // Make a large shift.
18376 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
18378 SHL = DAG.getBitcast(VT, SHL);
18379 // Zero out the rightmost bits.
18380 SmallVector<SDValue, 32> V(
18381 NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
18382 return DAG.getNode(ISD::AND, dl, VT, SHL,
18383 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
18385 if (Op.getOpcode() == ISD::SRL) {
18386 // Make a large shift.
18387 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
18389 SRL = DAG.getBitcast(VT, SRL);
18390 // Zero out the leftmost bits.
18391 SmallVector<SDValue, 32> V(
18392 NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
18393 return DAG.getNode(ISD::AND, dl, VT, SRL,
18394 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
18396 if (Op.getOpcode() == ISD::SRA) {
18397 // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
18398 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18399 SmallVector<SDValue, 32> V(NumElts,
18400 DAG.getConstant(128 >> ShiftAmt, dl,
18402 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
18403 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
18404 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
18407 llvm_unreachable("Unknown shift opcode.");
18412 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18413 if (!Subtarget->is64Bit() && !Subtarget->hasXOP() &&
18414 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64))) {
18416 // Peek through any splat that was introduced for i64 shift vectorization.
18417 int SplatIndex = -1;
18418 if (ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt.getNode()))
18419 if (SVN->isSplat()) {
18420 SplatIndex = SVN->getSplatIndex();
18421 Amt = Amt.getOperand(0);
18422 assert(SplatIndex < (int)VT.getVectorNumElements() &&
18423 "Splat shuffle referencing second operand");
18426 if (Amt.getOpcode() != ISD::BITCAST ||
18427 Amt.getOperand(0).getOpcode() != ISD::BUILD_VECTOR)
18430 Amt = Amt.getOperand(0);
18431 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18432 VT.getVectorNumElements();
18433 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
18434 uint64_t ShiftAmt = 0;
18435 unsigned BaseOp = (SplatIndex < 0 ? 0 : SplatIndex * Ratio);
18436 for (unsigned i = 0; i != Ratio; ++i) {
18437 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + BaseOp));
18441 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
18444 // Check remaining shift amounts (if not a splat).
18445 if (SplatIndex < 0) {
18446 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18447 uint64_t ShAmt = 0;
18448 for (unsigned j = 0; j != Ratio; ++j) {
18449 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
18453 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
18455 if (ShAmt != ShiftAmt)
18460 if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
18461 return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
18463 if (Op.getOpcode() == ISD::SRA)
18464 return ArithmeticShiftRight64(ShiftAmt);
18470 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
18471 const X86Subtarget* Subtarget) {
18472 MVT VT = Op.getSimpleValueType();
18474 SDValue R = Op.getOperand(0);
18475 SDValue Amt = Op.getOperand(1);
18477 unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
18478 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
18480 unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
18481 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
18483 if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
18485 MVT EltVT = VT.getVectorElementType();
18487 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
18488 // Check if this build_vector node is doing a splat.
18489 // If so, then set BaseShAmt equal to the splat value.
18490 BaseShAmt = BV->getSplatValue();
18491 if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
18492 BaseShAmt = SDValue();
18494 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
18495 Amt = Amt.getOperand(0);
18497 ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
18498 if (SVN && SVN->isSplat()) {
18499 unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
18500 SDValue InVec = Amt.getOperand(0);
18501 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
18502 assert((SplatIdx < InVec.getSimpleValueType().getVectorNumElements()) &&
18503 "Unexpected shuffle index found!");
18504 BaseShAmt = InVec.getOperand(SplatIdx);
18505 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
18506 if (ConstantSDNode *C =
18507 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
18508 if (C->getZExtValue() == SplatIdx)
18509 BaseShAmt = InVec.getOperand(1);
18514 // Avoid introducing an extract element from a shuffle.
18515 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
18516 DAG.getIntPtrConstant(SplatIdx, dl));
18520 if (BaseShAmt.getNode()) {
18521 assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
18522 if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
18523 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
18524 else if (EltVT.bitsLT(MVT::i32))
18525 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
18527 return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
18531 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
18532 if (!Subtarget->is64Bit() && VT == MVT::v2i64 &&
18533 Amt.getOpcode() == ISD::BITCAST &&
18534 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
18535 Amt = Amt.getOperand(0);
18536 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
18537 VT.getVectorNumElements();
18538 std::vector<SDValue> Vals(Ratio);
18539 for (unsigned i = 0; i != Ratio; ++i)
18540 Vals[i] = Amt.getOperand(i);
18541 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
18542 for (unsigned j = 0; j != Ratio; ++j)
18543 if (Vals[j] != Amt.getOperand(i + j))
18547 if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
18548 return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
18553 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
18554 SelectionDAG &DAG) {
18555 MVT VT = Op.getSimpleValueType();
18557 SDValue R = Op.getOperand(0);
18558 SDValue Amt = Op.getOperand(1);
18560 assert(VT.isVector() && "Custom lowering only for vector shifts!");
18561 assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
18563 if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
18566 if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
18569 if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
18572 // XOP has 128-bit variable logical/arithmetic shifts.
18573 // +ve/-ve Amt = shift left/right.
18574 if (Subtarget->hasXOP() &&
18575 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
18576 VT == MVT::v8i16 || VT == MVT::v16i8)) {
18577 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SRA) {
18578 SDValue Zero = getZeroVector(VT, Subtarget, DAG, dl);
18579 Amt = DAG.getNode(ISD::SUB, dl, VT, Zero, Amt);
18581 if (Op.getOpcode() == ISD::SHL || Op.getOpcode() == ISD::SRL)
18582 return DAG.getNode(X86ISD::VPSHL, dl, VT, R, Amt);
18583 if (Op.getOpcode() == ISD::SRA)
18584 return DAG.getNode(X86ISD::VPSHA, dl, VT, R, Amt);
18587 // 2i64 vector logical shifts can efficiently avoid scalarization - do the
18588 // shifts per-lane and then shuffle the partial results back together.
18589 if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
18590 // Splat the shift amounts so the scalar shifts above will catch it.
18591 SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
18592 SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
18593 SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
18594 SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
18595 return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
18598 // i64 vector arithmetic shift can be emulated with the transform:
18599 // M = lshr(SIGN_BIT, Amt)
18600 // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
18601 if ((VT == MVT::v2i64 || (VT == MVT::v4i64 && Subtarget->hasInt256())) &&
18602 Op.getOpcode() == ISD::SRA) {
18603 SDValue S = DAG.getConstant(APInt::getSignBit(64), dl, VT);
18604 SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
18605 R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
18606 R = DAG.getNode(ISD::XOR, dl, VT, R, M);
18607 R = DAG.getNode(ISD::SUB, dl, VT, R, M);
18611 // If possible, lower this packed shift into a vector multiply instead of
18612 // expanding it into a sequence of scalar shifts.
18613 // Do this only if the vector shift count is a constant build_vector.
18614 if (Op.getOpcode() == ISD::SHL &&
18615 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
18616 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
18617 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18618 SmallVector<SDValue, 8> Elts;
18619 MVT SVT = VT.getVectorElementType();
18620 unsigned SVTBits = SVT.getSizeInBits();
18621 APInt One(SVTBits, 1);
18622 unsigned NumElems = VT.getVectorNumElements();
18624 for (unsigned i=0; i !=NumElems; ++i) {
18625 SDValue Op = Amt->getOperand(i);
18626 if (Op->getOpcode() == ISD::UNDEF) {
18627 Elts.push_back(Op);
18631 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
18632 APInt C(SVTBits, ND->getAPIntValue().getZExtValue());
18633 uint64_t ShAmt = C.getZExtValue();
18634 if (ShAmt >= SVTBits) {
18635 Elts.push_back(DAG.getUNDEF(SVT));
18638 Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
18640 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
18641 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
18644 // Lower SHL with variable shift amount.
18645 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
18646 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
18648 Op = DAG.getNode(ISD::ADD, dl, VT, Op,
18649 DAG.getConstant(0x3f800000U, dl, VT));
18650 Op = DAG.getBitcast(MVT::v4f32, Op);
18651 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
18652 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
18655 // If possible, lower this shift as a sequence of two shifts by
18656 // constant plus a MOVSS/MOVSD instead of scalarizing it.
18658 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
18660 // Could be rewritten as:
18661 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
18663 // The advantage is that the two shifts from the example would be
18664 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
18665 // the vector shift into four scalar shifts plus four pairs of vector
18667 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
18668 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18669 unsigned TargetOpcode = X86ISD::MOVSS;
18670 bool CanBeSimplified;
18671 // The splat value for the first packed shift (the 'X' from the example).
18672 SDValue Amt1 = Amt->getOperand(0);
18673 // The splat value for the second packed shift (the 'Y' from the example).
18674 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
18675 Amt->getOperand(2);
18677 // See if it is possible to replace this node with a sequence of
18678 // two shifts followed by a MOVSS/MOVSD
18679 if (VT == MVT::v4i32) {
18680 // Check if it is legal to use a MOVSS.
18681 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
18682 Amt2 == Amt->getOperand(3);
18683 if (!CanBeSimplified) {
18684 // Otherwise, check if we can still simplify this node using a MOVSD.
18685 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
18686 Amt->getOperand(2) == Amt->getOperand(3);
18687 TargetOpcode = X86ISD::MOVSD;
18688 Amt2 = Amt->getOperand(2);
18691 // Do similar checks for the case where the machine value type
18693 CanBeSimplified = Amt1 == Amt->getOperand(1);
18694 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
18695 CanBeSimplified = Amt2 == Amt->getOperand(i);
18697 if (!CanBeSimplified) {
18698 TargetOpcode = X86ISD::MOVSD;
18699 CanBeSimplified = true;
18700 Amt2 = Amt->getOperand(4);
18701 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
18702 CanBeSimplified = Amt1 == Amt->getOperand(i);
18703 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
18704 CanBeSimplified = Amt2 == Amt->getOperand(j);
18708 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
18709 isa<ConstantSDNode>(Amt2)) {
18710 // Replace this node with two shifts followed by a MOVSS/MOVSD.
18711 MVT CastVT = MVT::v4i32;
18713 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
18714 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
18716 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
18717 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
18718 if (TargetOpcode == X86ISD::MOVSD)
18719 CastVT = MVT::v2i64;
18720 SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
18721 SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
18722 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
18724 return DAG.getBitcast(VT, Result);
18728 // v4i32 Non Uniform Shifts.
18729 // If the shift amount is constant we can shift each lane using the SSE2
18730 // immediate shifts, else we need to zero-extend each lane to the lower i64
18731 // and shift using the SSE2 variable shifts.
18732 // The separate results can then be blended together.
18733 if (VT == MVT::v4i32) {
18734 unsigned Opc = Op.getOpcode();
18735 SDValue Amt0, Amt1, Amt2, Amt3;
18736 if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
18737 Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
18738 Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
18739 Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
18740 Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
18742 // ISD::SHL is handled above but we include it here for completeness.
18745 llvm_unreachable("Unknown target vector shift node");
18747 Opc = X86ISD::VSHL;
18750 Opc = X86ISD::VSRL;
18753 Opc = X86ISD::VSRA;
18756 // The SSE2 shifts use the lower i64 as the same shift amount for
18757 // all lanes and the upper i64 is ignored. These shuffle masks
18758 // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
18759 SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
18760 Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
18761 Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
18762 Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
18763 Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
18766 SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
18767 SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
18768 SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
18769 SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
18770 SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
18771 SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
18772 return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
18775 if (VT == MVT::v16i8 ||
18776 (VT == MVT::v32i8 && Subtarget->hasInt256() && !Subtarget->hasXOP())) {
18777 MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
18778 unsigned ShiftOpcode = Op->getOpcode();
18780 auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
18781 // On SSE41 targets we make use of the fact that VSELECT lowers
18782 // to PBLENDVB which selects bytes based just on the sign bit.
18783 if (Subtarget->hasSSE41()) {
18784 V0 = DAG.getBitcast(VT, V0);
18785 V1 = DAG.getBitcast(VT, V1);
18786 Sel = DAG.getBitcast(VT, Sel);
18787 return DAG.getBitcast(SelVT,
18788 DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
18790 // On pre-SSE41 targets we test for the sign bit by comparing to
18791 // zero - a negative value will set all bits of the lanes to true
18792 // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
18793 SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
18794 SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
18795 return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
18798 // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
18799 // We can safely do this using i16 shifts as we're only interested in
18800 // the 3 lower bits of each byte.
18801 Amt = DAG.getBitcast(ExtVT, Amt);
18802 Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
18803 Amt = DAG.getBitcast(VT, Amt);
18805 if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
18806 // r = VSELECT(r, shift(r, 4), a);
18808 DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18809 R = SignBitSelect(VT, Amt, M, R);
18812 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18814 // r = VSELECT(r, shift(r, 2), a);
18815 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
18816 R = SignBitSelect(VT, Amt, M, R);
18819 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18821 // return VSELECT(r, shift(r, 1), a);
18822 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
18823 R = SignBitSelect(VT, Amt, M, R);
18827 if (Op->getOpcode() == ISD::SRA) {
18828 // For SRA we need to unpack each byte to the higher byte of a i16 vector
18829 // so we can correctly sign extend. We don't care what happens to the
18831 SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
18832 SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
18833 SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
18834 SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
18835 ALo = DAG.getBitcast(ExtVT, ALo);
18836 AHi = DAG.getBitcast(ExtVT, AHi);
18837 RLo = DAG.getBitcast(ExtVT, RLo);
18838 RHi = DAG.getBitcast(ExtVT, RHi);
18840 // r = VSELECT(r, shift(r, 4), a);
18841 SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18842 DAG.getConstant(4, dl, ExtVT));
18843 SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18844 DAG.getConstant(4, dl, ExtVT));
18845 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18846 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18849 ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
18850 AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
18852 // r = VSELECT(r, shift(r, 2), a);
18853 MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18854 DAG.getConstant(2, dl, ExtVT));
18855 MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18856 DAG.getConstant(2, dl, ExtVT));
18857 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18858 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18861 ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
18862 AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
18864 // r = VSELECT(r, shift(r, 1), a);
18865 MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
18866 DAG.getConstant(1, dl, ExtVT));
18867 MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
18868 DAG.getConstant(1, dl, ExtVT));
18869 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
18870 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
18872 // Logical shift the result back to the lower byte, leaving a zero upper
18874 // meaning that we can safely pack with PACKUSWB.
18876 DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
18878 DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
18879 return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
18883 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
18884 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
18885 // solution better.
18886 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
18887 MVT ExtVT = MVT::v8i32;
18889 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
18890 R = DAG.getNode(ExtOpc, dl, ExtVT, R);
18891 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
18892 return DAG.getNode(ISD::TRUNCATE, dl, VT,
18893 DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
18896 if (Subtarget->hasInt256() && !Subtarget->hasXOP() && VT == MVT::v16i16) {
18897 MVT ExtVT = MVT::v8i32;
18898 SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
18899 SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
18900 SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
18901 SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
18902 SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
18903 ALo = DAG.getBitcast(ExtVT, ALo);
18904 AHi = DAG.getBitcast(ExtVT, AHi);
18905 RLo = DAG.getBitcast(ExtVT, RLo);
18906 RHi = DAG.getBitcast(ExtVT, RHi);
18907 SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
18908 SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
18909 Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
18910 Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
18911 return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
18914 if (VT == MVT::v8i16) {
18915 unsigned ShiftOpcode = Op->getOpcode();
18917 auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
18918 // On SSE41 targets we make use of the fact that VSELECT lowers
18919 // to PBLENDVB which selects bytes based just on the sign bit.
18920 if (Subtarget->hasSSE41()) {
18921 MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
18922 V0 = DAG.getBitcast(ExtVT, V0);
18923 V1 = DAG.getBitcast(ExtVT, V1);
18924 Sel = DAG.getBitcast(ExtVT, Sel);
18925 return DAG.getBitcast(
18926 VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
18928 // On pre-SSE41 targets we splat the sign bit - a negative value will
18929 // set all bits of the lanes to true and VSELECT uses that in
18930 // its OR(AND(V0,C),AND(V1,~C)) lowering.
18932 DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
18933 return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
18936 // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
18937 if (Subtarget->hasSSE41()) {
18938 // On SSE41 targets we need to replicate the shift mask in both
18939 // bytes for PBLENDVB.
18942 DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
18943 DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
18945 Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
18948 // r = VSELECT(r, shift(r, 8), a);
18949 SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
18950 R = SignBitSelect(Amt, M, R);
18953 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18955 // r = VSELECT(r, shift(r, 4), a);
18956 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
18957 R = SignBitSelect(Amt, M, R);
18960 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18962 // r = VSELECT(r, shift(r, 2), a);
18963 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
18964 R = SignBitSelect(Amt, M, R);
18967 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
18969 // return VSELECT(r, shift(r, 1), a);
18970 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
18971 R = SignBitSelect(Amt, M, R);
18975 // Decompose 256-bit shifts into smaller 128-bit shifts.
18976 if (VT.is256BitVector()) {
18977 unsigned NumElems = VT.getVectorNumElements();
18978 MVT EltVT = VT.getVectorElementType();
18979 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
18981 // Extract the two vectors
18982 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
18983 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
18985 // Recreate the shift amount vectors
18986 SDValue Amt1, Amt2;
18987 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
18988 // Constant shift amount
18989 SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
18990 ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
18991 ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
18993 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
18994 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
18996 // Variable shift amount
18997 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
18998 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
19001 // Issue new vector shifts for the smaller types
19002 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
19003 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
19005 // Concatenate the result back
19006 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
19012 static SDValue LowerRotate(SDValue Op, const X86Subtarget *Subtarget,
19013 SelectionDAG &DAG) {
19014 MVT VT = Op.getSimpleValueType();
19016 SDValue R = Op.getOperand(0);
19017 SDValue Amt = Op.getOperand(1);
19019 assert(VT.isVector() && "Custom lowering only for vector rotates!");
19020 assert(Subtarget->hasXOP() && "XOP support required for vector rotates!");
19021 assert((Op.getOpcode() == ISD::ROTL) && "Only ROTL supported");
19023 // XOP has 128-bit vector variable + immediate rotates.
19024 // +ve/-ve Amt = rotate left/right.
19026 // Split 256-bit integers.
19027 if (VT.is256BitVector())
19028 return Lower256IntArith(Op, DAG);
19030 assert(VT.is128BitVector() && "Only rotate 128-bit vectors!");
19032 // Attempt to rotate by immediate.
19033 if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
19034 if (auto *RotateConst = BVAmt->getConstantSplatNode()) {
19035 uint64_t RotateAmt = RotateConst->getAPIntValue().getZExtValue();
19036 assert(RotateAmt < VT.getScalarSizeInBits() && "Rotation out of range");
19037 return DAG.getNode(X86ISD::VPROTI, DL, VT, R,
19038 DAG.getConstant(RotateAmt, DL, MVT::i8));
19042 // Use general rotate by variable (per-element).
19043 return DAG.getNode(X86ISD::VPROT, DL, VT, R, Amt);
19046 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
19047 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
19048 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
19049 // looks for this combo and may remove the "setcc" instruction if the "setcc"
19050 // has only one use.
19051 SDNode *N = Op.getNode();
19052 SDValue LHS = N->getOperand(0);
19053 SDValue RHS = N->getOperand(1);
19054 unsigned BaseOp = 0;
19057 switch (Op.getOpcode()) {
19058 default: llvm_unreachable("Unknown ovf instruction!");
19060 // A subtract of one will be selected as a INC. Note that INC doesn't
19061 // set CF, so we can't do this for UADDO.
19062 if (isOneConstant(RHS)) {
19063 BaseOp = X86ISD::INC;
19064 Cond = X86::COND_O;
19067 BaseOp = X86ISD::ADD;
19068 Cond = X86::COND_O;
19071 BaseOp = X86ISD::ADD;
19072 Cond = X86::COND_B;
19075 // A subtract of one will be selected as a DEC. Note that DEC doesn't
19076 // set CF, so we can't do this for USUBO.
19077 if (isOneConstant(RHS)) {
19078 BaseOp = X86ISD::DEC;
19079 Cond = X86::COND_O;
19082 BaseOp = X86ISD::SUB;
19083 Cond = X86::COND_O;
19086 BaseOp = X86ISD::SUB;
19087 Cond = X86::COND_B;
19090 BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
19091 Cond = X86::COND_O;
19093 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
19094 if (N->getValueType(0) == MVT::i8) {
19095 BaseOp = X86ISD::UMUL8;
19096 Cond = X86::COND_O;
19099 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
19101 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
19104 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
19105 DAG.getConstant(X86::COND_O, DL, MVT::i32),
19106 SDValue(Sum.getNode(), 2));
19108 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
19112 // Also sets EFLAGS.
19113 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
19114 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
19117 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
19118 DAG.getConstant(Cond, DL, MVT::i32),
19119 SDValue(Sum.getNode(), 1));
19121 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
19124 /// Returns true if the operand type is exactly twice the native width, and
19125 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
19126 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
19127 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
19128 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
19129 unsigned OpWidth = MemType->getPrimitiveSizeInBits();
19132 return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
19133 else if (OpWidth == 128)
19134 return Subtarget->hasCmpxchg16b();
19139 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
19140 return needsCmpXchgNb(SI->getValueOperand()->getType());
19143 // Note: this turns large loads into lock cmpxchg8b/16b.
19144 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
19145 TargetLowering::AtomicExpansionKind
19146 X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
19147 auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
19148 return needsCmpXchgNb(PTy->getElementType()) ? AtomicExpansionKind::CmpXChg
19149 : AtomicExpansionKind::None;
19152 TargetLowering::AtomicExpansionKind
19153 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
19154 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
19155 Type *MemType = AI->getType();
19157 // If the operand is too big, we must see if cmpxchg8/16b is available
19158 // and default to library calls otherwise.
19159 if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
19160 return needsCmpXchgNb(MemType) ? AtomicExpansionKind::CmpXChg
19161 : AtomicExpansionKind::None;
19164 AtomicRMWInst::BinOp Op = AI->getOperation();
19167 llvm_unreachable("Unknown atomic operation");
19168 case AtomicRMWInst::Xchg:
19169 case AtomicRMWInst::Add:
19170 case AtomicRMWInst::Sub:
19171 // It's better to use xadd, xsub or xchg for these in all cases.
19172 return AtomicExpansionKind::None;
19173 case AtomicRMWInst::Or:
19174 case AtomicRMWInst::And:
19175 case AtomicRMWInst::Xor:
19176 // If the atomicrmw's result isn't actually used, we can just add a "lock"
19177 // prefix to a normal instruction for these operations.
19178 return !AI->use_empty() ? AtomicExpansionKind::CmpXChg
19179 : AtomicExpansionKind::None;
19180 case AtomicRMWInst::Nand:
19181 case AtomicRMWInst::Max:
19182 case AtomicRMWInst::Min:
19183 case AtomicRMWInst::UMax:
19184 case AtomicRMWInst::UMin:
19185 // These always require a non-trivial set of data operations on x86. We must
19186 // use a cmpxchg loop.
19187 return AtomicExpansionKind::CmpXChg;
19191 static bool hasMFENCE(const X86Subtarget& Subtarget) {
19192 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
19193 // no-sse2). There isn't any reason to disable it if the target processor
19195 return Subtarget.hasSSE2() || Subtarget.is64Bit();
19199 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
19200 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
19201 Type *MemType = AI->getType();
19202 // Accesses larger than the native width are turned into cmpxchg/libcalls, so
19203 // there is no benefit in turning such RMWs into loads, and it is actually
19204 // harmful as it introduces a mfence.
19205 if (MemType->getPrimitiveSizeInBits() > NativeWidth)
19208 auto Builder = IRBuilder<>(AI);
19209 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
19210 auto SynchScope = AI->getSynchScope();
19211 // We must restrict the ordering to avoid generating loads with Release or
19212 // ReleaseAcquire orderings.
19213 auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
19214 auto Ptr = AI->getPointerOperand();
19216 // Before the load we need a fence. Here is an example lifted from
19217 // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
19220 // x.store(1, relaxed);
19221 // r1 = y.fetch_add(0, release);
19223 // y.fetch_add(42, acquire);
19224 // r2 = x.load(relaxed);
19225 // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
19226 // lowered to just a load without a fence. A mfence flushes the store buffer,
19227 // making the optimization clearly correct.
19228 // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
19229 // otherwise, we might be able to be more aggressive on relaxed idempotent
19230 // rmw. In practice, they do not look useful, so we don't try to be
19231 // especially clever.
19232 if (SynchScope == SingleThread)
19233 // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
19234 // the IR level, so we must wrap it in an intrinsic.
19237 if (!hasMFENCE(*Subtarget))
19238 // FIXME: it might make sense to use a locked operation here but on a
19239 // different cache-line to prevent cache-line bouncing. In practice it
19240 // is probably a small win, and x86 processors without mfence are rare
19241 // enough that we do not bother.
19245 llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
19246 Builder.CreateCall(MFence, {});
19248 // Finally we can emit the atomic load.
19249 LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
19250 AI->getType()->getPrimitiveSizeInBits());
19251 Loaded->setAtomic(Order, SynchScope);
19252 AI->replaceAllUsesWith(Loaded);
19253 AI->eraseFromParent();
19257 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
19258 SelectionDAG &DAG) {
19260 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
19261 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
19262 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
19263 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
19265 // The only fence that needs an instruction is a sequentially-consistent
19266 // cross-thread fence.
19267 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
19268 if (hasMFENCE(*Subtarget))
19269 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
19271 SDValue Chain = Op.getOperand(0);
19272 SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
19274 DAG.getRegister(X86::ESP, MVT::i32), // Base
19275 DAG.getTargetConstant(1, dl, MVT::i8), // Scale
19276 DAG.getRegister(0, MVT::i32), // Index
19277 DAG.getTargetConstant(0, dl, MVT::i32), // Disp
19278 DAG.getRegister(0, MVT::i32), // Segment.
19282 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
19283 return SDValue(Res, 0);
19286 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
19287 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
19290 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
19291 SelectionDAG &DAG) {
19292 MVT T = Op.getSimpleValueType();
19296 switch(T.SimpleTy) {
19297 default: llvm_unreachable("Invalid value type!");
19298 case MVT::i8: Reg = X86::AL; size = 1; break;
19299 case MVT::i16: Reg = X86::AX; size = 2; break;
19300 case MVT::i32: Reg = X86::EAX; size = 4; break;
19302 assert(Subtarget->is64Bit() && "Node not type legal!");
19303 Reg = X86::RAX; size = 8;
19306 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
19307 Op.getOperand(2), SDValue());
19308 SDValue Ops[] = { cpIn.getValue(0),
19311 DAG.getTargetConstant(size, DL, MVT::i8),
19312 cpIn.getValue(1) };
19313 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
19314 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
19315 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
19319 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
19320 SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
19321 MVT::i32, cpOut.getValue(2));
19322 SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
19323 DAG.getConstant(X86::COND_E, DL, MVT::i8),
19326 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
19327 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
19328 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
19332 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
19333 SelectionDAG &DAG) {
19334 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
19335 MVT DstVT = Op.getSimpleValueType();
19337 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
19338 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
19339 if (DstVT != MVT::f64)
19340 // This conversion needs to be expanded.
19343 SDValue InVec = Op->getOperand(0);
19345 unsigned NumElts = SrcVT.getVectorNumElements();
19346 MVT SVT = SrcVT.getVectorElementType();
19348 // Widen the vector in input in the case of MVT::v2i32.
19349 // Example: from MVT::v2i32 to MVT::v4i32.
19350 SmallVector<SDValue, 16> Elts;
19351 for (unsigned i = 0, e = NumElts; i != e; ++i)
19352 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
19353 DAG.getIntPtrConstant(i, dl)));
19355 // Explicitly mark the extra elements as Undef.
19356 Elts.append(NumElts, DAG.getUNDEF(SVT));
19358 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
19359 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
19360 SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
19361 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
19362 DAG.getIntPtrConstant(0, dl));
19365 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
19366 Subtarget->hasMMX() && "Unexpected custom BITCAST");
19367 assert((DstVT == MVT::i64 ||
19368 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
19369 "Unexpected custom BITCAST");
19370 // i64 <=> MMX conversions are Legal.
19371 if (SrcVT==MVT::i64 && DstVT.isVector())
19373 if (DstVT==MVT::i64 && SrcVT.isVector())
19375 // MMX <=> MMX conversions are Legal.
19376 if (SrcVT.isVector() && DstVT.isVector())
19378 // All other conversions need to be expanded.
19382 /// Compute the horizontal sum of bytes in V for the elements of VT.
19384 /// Requires V to be a byte vector and VT to be an integer vector type with
19385 /// wider elements than V's type. The width of the elements of VT determines
19386 /// how many bytes of V are summed horizontally to produce each element of the
19388 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
19389 const X86Subtarget *Subtarget,
19390 SelectionDAG &DAG) {
19392 MVT ByteVecVT = V.getSimpleValueType();
19393 MVT EltVT = VT.getVectorElementType();
19394 int NumElts = VT.getVectorNumElements();
19395 assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
19396 "Expected value to have byte element type.");
19397 assert(EltVT != MVT::i8 &&
19398 "Horizontal byte sum only makes sense for wider elements!");
19399 unsigned VecSize = VT.getSizeInBits();
19400 assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
19402 // PSADBW instruction horizontally add all bytes and leave the result in i64
19403 // chunks, thus directly computes the pop count for v2i64 and v4i64.
19404 if (EltVT == MVT::i64) {
19405 SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
19406 MVT SadVecVT = MVT::getVectorVT(MVT::i64, VecSize / 64);
19407 V = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT, V, Zeros);
19408 return DAG.getBitcast(VT, V);
19411 if (EltVT == MVT::i32) {
19412 // We unpack the low half and high half into i32s interleaved with zeros so
19413 // that we can use PSADBW to horizontally sum them. The most useful part of
19414 // this is that it lines up the results of two PSADBW instructions to be
19415 // two v2i64 vectors which concatenated are the 4 population counts. We can
19416 // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
19417 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
19418 SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
19419 SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
19421 // Do the horizontal sums into two v2i64s.
19422 Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
19423 MVT SadVecVT = MVT::getVectorVT(MVT::i64, VecSize / 64);
19424 Low = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT,
19425 DAG.getBitcast(ByteVecVT, Low), Zeros);
19426 High = DAG.getNode(X86ISD::PSADBW, DL, SadVecVT,
19427 DAG.getBitcast(ByteVecVT, High), Zeros);
19429 // Merge them together.
19430 MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
19431 V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
19432 DAG.getBitcast(ShortVecVT, Low),
19433 DAG.getBitcast(ShortVecVT, High));
19435 return DAG.getBitcast(VT, V);
19438 // The only element type left is i16.
19439 assert(EltVT == MVT::i16 && "Unknown how to handle type");
19441 // To obtain pop count for each i16 element starting from the pop count for
19442 // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
19443 // right by 8. It is important to shift as i16s as i8 vector shift isn't
19444 // directly supported.
19445 SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
19446 SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
19447 SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
19448 V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
19449 DAG.getBitcast(ByteVecVT, V));
19450 return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
19453 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
19454 const X86Subtarget *Subtarget,
19455 SelectionDAG &DAG) {
19456 MVT VT = Op.getSimpleValueType();
19457 MVT EltVT = VT.getVectorElementType();
19458 unsigned VecSize = VT.getSizeInBits();
19460 // Implement a lookup table in register by using an algorithm based on:
19461 // http://wm.ite.pl/articles/sse-popcount.html
19463 // The general idea is that every lower byte nibble in the input vector is an
19464 // index into a in-register pre-computed pop count table. We then split up the
19465 // input vector in two new ones: (1) a vector with only the shifted-right
19466 // higher nibbles for each byte and (2) a vector with the lower nibbles (and
19467 // masked out higher ones) for each byte. PSHUB is used separately with both
19468 // to index the in-register table. Next, both are added and the result is a
19469 // i8 vector where each element contains the pop count for input byte.
19471 // To obtain the pop count for elements != i8, we follow up with the same
19472 // approach and use additional tricks as described below.
19474 const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
19475 /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
19476 /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
19477 /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
19479 int NumByteElts = VecSize / 8;
19480 MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
19481 SDValue In = DAG.getBitcast(ByteVecVT, Op);
19482 SmallVector<SDValue, 16> LUTVec;
19483 for (int i = 0; i < NumByteElts; ++i)
19484 LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
19485 SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
19486 SmallVector<SDValue, 16> Mask0F(NumByteElts,
19487 DAG.getConstant(0x0F, DL, MVT::i8));
19488 SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
19491 SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
19492 SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
19493 SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
19496 SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
19498 // The input vector is used as the shuffle mask that index elements into the
19499 // LUT. After counting low and high nibbles, add the vector to obtain the
19500 // final pop count per i8 element.
19501 SDValue HighPopCnt =
19502 DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
19503 SDValue LowPopCnt =
19504 DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
19505 SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
19507 if (EltVT == MVT::i8)
19510 return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
19513 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
19514 const X86Subtarget *Subtarget,
19515 SelectionDAG &DAG) {
19516 MVT VT = Op.getSimpleValueType();
19517 assert(VT.is128BitVector() &&
19518 "Only 128-bit vector bitmath lowering supported.");
19520 int VecSize = VT.getSizeInBits();
19521 MVT EltVT = VT.getVectorElementType();
19522 int Len = EltVT.getSizeInBits();
19524 // This is the vectorized version of the "best" algorithm from
19525 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
19526 // with a minor tweak to use a series of adds + shifts instead of vector
19527 // multiplications. Implemented for all integer vector types. We only use
19528 // this when we don't have SSSE3 which allows a LUT-based lowering that is
19529 // much faster, even faster than using native popcnt instructions.
19531 auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
19532 MVT VT = V.getSimpleValueType();
19533 SmallVector<SDValue, 32> Shifters(
19534 VT.getVectorNumElements(),
19535 DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
19536 return DAG.getNode(OpCode, DL, VT, V,
19537 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
19539 auto GetMask = [&](SDValue V, APInt Mask) {
19540 MVT VT = V.getSimpleValueType();
19541 SmallVector<SDValue, 32> Masks(
19542 VT.getVectorNumElements(),
19543 DAG.getConstant(Mask, DL, VT.getVectorElementType()));
19544 return DAG.getNode(ISD::AND, DL, VT, V,
19545 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
19548 // We don't want to incur the implicit masks required to SRL vNi8 vectors on
19549 // x86, so set the SRL type to have elements at least i16 wide. This is
19550 // correct because all of our SRLs are followed immediately by a mask anyways
19551 // that handles any bits that sneak into the high bits of the byte elements.
19552 MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
19556 // v = v - ((v >> 1) & 0x55555555...)
19558 DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
19559 SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
19560 V = DAG.getNode(ISD::SUB, DL, VT, V, And);
19562 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
19563 SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
19564 Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
19565 SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
19566 V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
19568 // v = (v + (v >> 4)) & 0x0F0F0F0F...
19569 Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
19570 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
19571 V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
19573 // At this point, V contains the byte-wise population count, and we are
19574 // merely doing a horizontal sum if necessary to get the wider element
19576 if (EltVT == MVT::i8)
19579 return LowerHorizontalByteSum(
19580 DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
19584 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19585 SelectionDAG &DAG) {
19586 MVT VT = Op.getSimpleValueType();
19587 // FIXME: Need to add AVX-512 support here!
19588 assert((VT.is256BitVector() || VT.is128BitVector()) &&
19589 "Unknown CTPOP type to handle");
19590 SDLoc DL(Op.getNode());
19591 SDValue Op0 = Op.getOperand(0);
19593 if (!Subtarget->hasSSSE3()) {
19594 // We can't use the fast LUT approach, so fall back on vectorized bitmath.
19595 assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
19596 return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
19599 if (VT.is256BitVector() && !Subtarget->hasInt256()) {
19600 unsigned NumElems = VT.getVectorNumElements();
19602 // Extract each 128-bit vector, compute pop count and concat the result.
19603 SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
19604 SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
19606 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
19607 LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
19608 LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
19611 return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
19614 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
19615 SelectionDAG &DAG) {
19616 assert(Op.getSimpleValueType().isVector() &&
19617 "We only do custom lowering for vector population count.");
19618 return LowerVectorCTPOP(Op, Subtarget, DAG);
19621 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
19622 SDNode *Node = Op.getNode();
19624 EVT T = Node->getValueType(0);
19625 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
19626 DAG.getConstant(0, dl, T), Node->getOperand(2));
19627 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
19628 cast<AtomicSDNode>(Node)->getMemoryVT(),
19629 Node->getOperand(0),
19630 Node->getOperand(1), negOp,
19631 cast<AtomicSDNode>(Node)->getMemOperand(),
19632 cast<AtomicSDNode>(Node)->getOrdering(),
19633 cast<AtomicSDNode>(Node)->getSynchScope());
19636 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
19637 SDNode *Node = Op.getNode();
19639 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
19641 // Convert seq_cst store -> xchg
19642 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
19643 // FIXME: On 32-bit, store -> fist or movq would be more efficient
19644 // (The only way to get a 16-byte store is cmpxchg16b)
19645 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
19646 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
19647 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
19648 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
19649 cast<AtomicSDNode>(Node)->getMemoryVT(),
19650 Node->getOperand(0),
19651 Node->getOperand(1), Node->getOperand(2),
19652 cast<AtomicSDNode>(Node)->getMemOperand(),
19653 cast<AtomicSDNode>(Node)->getOrdering(),
19654 cast<AtomicSDNode>(Node)->getSynchScope());
19655 return Swap.getValue(1);
19657 // Other atomic stores have a simple pattern.
19661 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
19662 MVT VT = Op.getNode()->getSimpleValueType(0);
19664 // Let legalize expand this if it isn't a legal type yet.
19665 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
19668 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
19671 bool ExtraOp = false;
19672 switch (Op.getOpcode()) {
19673 default: llvm_unreachable("Invalid code");
19674 case ISD::ADDC: Opc = X86ISD::ADD; break;
19675 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
19676 case ISD::SUBC: Opc = X86ISD::SUB; break;
19677 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
19681 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19683 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
19684 Op.getOperand(1), Op.getOperand(2));
19687 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
19688 SelectionDAG &DAG) {
19689 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
19691 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
19692 // which returns the values as { float, float } (in XMM0) or
19693 // { double, double } (which is returned in XMM0, XMM1).
19695 SDValue Arg = Op.getOperand(0);
19696 EVT ArgVT = Arg.getValueType();
19697 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
19699 TargetLowering::ArgListTy Args;
19700 TargetLowering::ArgListEntry Entry;
19704 Entry.isSExt = false;
19705 Entry.isZExt = false;
19706 Args.push_back(Entry);
19708 bool isF64 = ArgVT == MVT::f64;
19709 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
19710 // the small struct {f32, f32} is returned in (eax, edx). For f64,
19711 // the results are returned via SRet in memory.
19712 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
19713 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19715 DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
19717 Type *RetTy = isF64
19718 ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
19719 : (Type*)VectorType::get(ArgTy, 4);
19721 TargetLowering::CallLoweringInfo CLI(DAG);
19722 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
19723 .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
19725 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
19728 // Returned in xmm0 and xmm1.
19729 return CallResult.first;
19731 // Returned in bits 0:31 and 32:64 xmm0.
19732 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19733 CallResult.first, DAG.getIntPtrConstant(0, dl));
19734 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
19735 CallResult.first, DAG.getIntPtrConstant(1, dl));
19736 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
19737 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
19740 /// Widen a vector input to a vector of NVT. The
19741 /// input vector must have the same element type as NVT.
19742 static SDValue ExtendToType(SDValue InOp, MVT NVT, SelectionDAG &DAG,
19743 bool FillWithZeroes = false) {
19744 // Check if InOp already has the right width.
19745 MVT InVT = InOp.getSimpleValueType();
19749 if (InOp.isUndef())
19750 return DAG.getUNDEF(NVT);
19752 assert(InVT.getVectorElementType() == NVT.getVectorElementType() &&
19753 "input and widen element type must match");
19755 unsigned InNumElts = InVT.getVectorNumElements();
19756 unsigned WidenNumElts = NVT.getVectorNumElements();
19757 assert(WidenNumElts > InNumElts && WidenNumElts % InNumElts == 0 &&
19758 "Unexpected request for vector widening");
19760 EVT EltVT = NVT.getVectorElementType();
19763 if (ISD::isBuildVectorOfConstantSDNodes(InOp.getNode()) ||
19764 ISD::isBuildVectorOfConstantFPSDNodes(InOp.getNode())) {
19765 SmallVector<SDValue, 16> Ops;
19766 for (unsigned i = 0; i < InNumElts; ++i)
19767 Ops.push_back(InOp.getOperand(i));
19769 SDValue FillVal = FillWithZeroes ? DAG.getConstant(0, dl, EltVT) :
19770 DAG.getUNDEF(EltVT);
19771 for (unsigned i = 0; i < WidenNumElts - InNumElts; ++i)
19772 Ops.push_back(FillVal);
19773 return DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Ops);
19775 SDValue FillVal = FillWithZeroes ? DAG.getConstant(0, dl, NVT) :
19777 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, NVT, FillVal,
19778 InOp, DAG.getIntPtrConstant(0, dl));
19781 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
19782 SelectionDAG &DAG) {
19783 assert(Subtarget->hasAVX512() &&
19784 "MGATHER/MSCATTER are supported on AVX-512 arch only");
19786 MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
19787 MVT VT = N->getValue().getSimpleValueType();
19788 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
19791 // X86 scatter kills mask register, so its type should be added to
19792 // the list of return values
19793 if (N->getNumValues() == 1) {
19794 SDValue Index = N->getIndex();
19795 if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
19796 !Index.getSimpleValueType().is512BitVector())
19797 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
19799 SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
19800 SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
19801 N->getOperand(3), Index };
19803 SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
19804 DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
19805 return SDValue(NewScatter.getNode(), 0);
19810 static SDValue LowerMLOAD(SDValue Op, const X86Subtarget *Subtarget,
19811 SelectionDAG &DAG) {
19813 MaskedLoadSDNode *N = cast<MaskedLoadSDNode>(Op.getNode());
19814 MVT VT = Op.getSimpleValueType();
19815 SDValue Mask = N->getMask();
19818 if (Subtarget->hasAVX512() && !Subtarget->hasVLX() &&
19819 !VT.is512BitVector() && Mask.getValueType() == MVT::v8i1) {
19820 // This operation is legal for targets with VLX, but without
19821 // VLX the vector should be widened to 512 bit
19822 unsigned NumEltsInWideVec = 512/VT.getScalarSizeInBits();
19823 MVT WideDataVT = MVT::getVectorVT(VT.getScalarType(), NumEltsInWideVec);
19824 MVT WideMaskVT = MVT::getVectorVT(MVT::i1, NumEltsInWideVec);
19825 SDValue Src0 = N->getSrc0();
19826 Src0 = ExtendToType(Src0, WideDataVT, DAG);
19827 Mask = ExtendToType(Mask, WideMaskVT, DAG, true);
19828 SDValue NewLoad = DAG.getMaskedLoad(WideDataVT, dl, N->getChain(),
19829 N->getBasePtr(), Mask, Src0,
19830 N->getMemoryVT(), N->getMemOperand(),
19831 N->getExtensionType());
19833 SDValue Exract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
19834 NewLoad.getValue(0),
19835 DAG.getIntPtrConstant(0, dl));
19836 SDValue RetOps[] = {Exract, NewLoad.getValue(1)};
19837 return DAG.getMergeValues(RetOps, dl);
19842 static SDValue LowerMSTORE(SDValue Op, const X86Subtarget *Subtarget,
19843 SelectionDAG &DAG) {
19844 MaskedStoreSDNode *N = cast<MaskedStoreSDNode>(Op.getNode());
19845 SDValue DataToStore = N->getValue();
19846 MVT VT = DataToStore.getSimpleValueType();
19847 SDValue Mask = N->getMask();
19850 if (Subtarget->hasAVX512() && !Subtarget->hasVLX() &&
19851 !VT.is512BitVector() && Mask.getValueType() == MVT::v8i1) {
19852 // This operation is legal for targets with VLX, but without
19853 // VLX the vector should be widened to 512 bit
19854 unsigned NumEltsInWideVec = 512/VT.getScalarSizeInBits();
19855 MVT WideDataVT = MVT::getVectorVT(VT.getScalarType(), NumEltsInWideVec);
19856 MVT WideMaskVT = MVT::getVectorVT(MVT::i1, NumEltsInWideVec);
19857 DataToStore = ExtendToType(DataToStore, WideDataVT, DAG);
19858 Mask = ExtendToType(Mask, WideMaskVT, DAG, true);
19859 return DAG.getMaskedStore(N->getChain(), dl, DataToStore, N->getBasePtr(),
19860 Mask, N->getMemoryVT(), N->getMemOperand(),
19861 N->isTruncatingStore());
19866 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
19867 SelectionDAG &DAG) {
19868 assert(Subtarget->hasAVX512() &&
19869 "MGATHER/MSCATTER are supported on AVX-512 arch only");
19871 MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
19872 MVT VT = Op.getSimpleValueType();
19873 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
19876 SDValue Index = N->getIndex();
19877 if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
19878 !Index.getSimpleValueType().is512BitVector()) {
19879 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
19880 SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
19881 N->getOperand(3), Index };
19882 DAG.UpdateNodeOperands(N, Ops);
19887 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
19888 SelectionDAG &DAG) const {
19889 // TODO: Eventually, the lowering of these nodes should be informed by or
19890 // deferred to the GC strategy for the function in which they appear. For
19891 // now, however, they must be lowered to something. Since they are logically
19892 // no-ops in the case of a null GC strategy (or a GC strategy which does not
19893 // require special handling for these nodes), lower them as literal NOOPs for
19895 SmallVector<SDValue, 2> Ops;
19897 Ops.push_back(Op.getOperand(0));
19898 if (Op->getGluedNode())
19899 Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
19902 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
19903 SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
19908 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
19909 SelectionDAG &DAG) const {
19910 // TODO: Eventually, the lowering of these nodes should be informed by or
19911 // deferred to the GC strategy for the function in which they appear. For
19912 // now, however, they must be lowered to something. Since they are logically
19913 // no-ops in the case of a null GC strategy (or a GC strategy which does not
19914 // require special handling for these nodes), lower them as literal NOOPs for
19916 SmallVector<SDValue, 2> Ops;
19918 Ops.push_back(Op.getOperand(0));
19919 if (Op->getGluedNode())
19920 Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
19923 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
19924 SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
19929 /// LowerOperation - Provide custom lowering hooks for some operations.
19931 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
19932 switch (Op.getOpcode()) {
19933 default: llvm_unreachable("Should not custom lower this!");
19934 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
19935 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
19936 return LowerCMP_SWAP(Op, Subtarget, DAG);
19937 case ISD::CTPOP: return LowerCTPOP(Op, Subtarget, DAG);
19938 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
19939 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
19940 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
19941 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
19942 case ISD::VECTOR_SHUFFLE: return lowerVectorShuffle(Op, Subtarget, DAG);
19943 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
19944 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
19945 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
19946 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
19947 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
19948 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
19949 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
19950 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
19951 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
19952 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
19953 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
19954 case ISD::SHL_PARTS:
19955 case ISD::SRA_PARTS:
19956 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
19957 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
19958 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
19959 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
19960 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
19961 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
19962 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
19963 case ISD::SIGN_EXTEND_VECTOR_INREG:
19964 return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
19965 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
19966 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
19967 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
19968 case ISD::LOAD: return LowerExtendedLoad(Op, Subtarget, DAG);
19970 case ISD::FNEG: return LowerFABSorFNEG(Op, DAG);
19971 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
19972 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
19973 case ISD::SETCC: return LowerSETCC(Op, DAG);
19974 case ISD::SETCCE: return LowerSETCCE(Op, DAG);
19975 case ISD::SELECT: return LowerSELECT(Op, DAG);
19976 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
19977 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
19978 case ISD::VASTART: return LowerVASTART(Op, DAG);
19979 case ISD::VAARG: return LowerVAARG(Op, DAG);
19980 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
19981 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
19982 case ISD::INTRINSIC_VOID:
19983 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
19984 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
19985 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
19986 case ISD::FRAME_TO_ARGS_OFFSET:
19987 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
19988 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
19989 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
19990 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
19991 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
19992 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
19993 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
19994 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
19995 case ISD::CTLZ: return LowerCTLZ(Op, Subtarget, DAG);
19996 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, Subtarget, DAG);
19998 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op, DAG);
19999 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
20000 case ISD::UMUL_LOHI:
20001 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
20002 case ISD::ROTL: return LowerRotate(Op, Subtarget, DAG);
20005 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
20011 case ISD::UMULO: return LowerXALUO(Op, DAG);
20012 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
20013 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
20017 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
20018 case ISD::ADD: return LowerADD(Op, DAG);
20019 case ISD::SUB: return LowerSUB(Op, DAG);
20023 case ISD::UMIN: return LowerMINMAX(Op, DAG);
20024 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
20025 case ISD::MLOAD: return LowerMLOAD(Op, Subtarget, DAG);
20026 case ISD::MSTORE: return LowerMSTORE(Op, Subtarget, DAG);
20027 case ISD::MGATHER: return LowerMGATHER(Op, Subtarget, DAG);
20028 case ISD::MSCATTER: return LowerMSCATTER(Op, Subtarget, DAG);
20029 case ISD::GC_TRANSITION_START:
20030 return LowerGC_TRANSITION_START(Op, DAG);
20031 case ISD::GC_TRANSITION_END: return LowerGC_TRANSITION_END(Op, DAG);
20035 /// ReplaceNodeResults - Replace a node with an illegal result type
20036 /// with a new node built out of custom code.
20037 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
20038 SmallVectorImpl<SDValue>&Results,
20039 SelectionDAG &DAG) const {
20041 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20042 switch (N->getOpcode()) {
20044 llvm_unreachable("Do not know how to custom type legalize this operation!");
20045 case X86ISD::AVG: {
20046 // Legalize types for X86ISD::AVG by expanding vectors.
20047 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
20049 auto InVT = N->getValueType(0);
20050 auto InVTSize = InVT.getSizeInBits();
20051 const unsigned RegSize =
20052 (InVTSize > 128) ? ((InVTSize > 256) ? 512 : 256) : 128;
20053 assert((!Subtarget->hasAVX512() || RegSize < 512) &&
20054 "512-bit vector requires AVX512");
20055 assert((!Subtarget->hasAVX2() || RegSize < 256) &&
20056 "256-bit vector requires AVX2");
20058 auto ElemVT = InVT.getVectorElementType();
20059 auto RegVT = EVT::getVectorVT(*DAG.getContext(), ElemVT,
20060 RegSize / ElemVT.getSizeInBits());
20061 assert(RegSize % InVT.getSizeInBits() == 0);
20062 unsigned NumConcat = RegSize / InVT.getSizeInBits();
20064 SmallVector<SDValue, 16> Ops(NumConcat, DAG.getUNDEF(InVT));
20065 Ops[0] = N->getOperand(0);
20066 SDValue InVec0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, RegVT, Ops);
20067 Ops[0] = N->getOperand(1);
20068 SDValue InVec1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, RegVT, Ops);
20070 SDValue Res = DAG.getNode(X86ISD::AVG, dl, RegVT, InVec0, InVec1);
20071 Results.push_back(DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, InVT, Res,
20072 DAG.getIntPtrConstant(0, dl)));
20075 // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
20076 case X86ISD::FMINC:
20078 case X86ISD::FMAXC:
20079 case X86ISD::FMAX: {
20080 EVT VT = N->getValueType(0);
20081 assert(VT == MVT::v2f32 && "Unexpected type (!= v2f32) on FMIN/FMAX.");
20082 SDValue UNDEF = DAG.getUNDEF(VT);
20083 SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
20084 N->getOperand(0), UNDEF);
20085 SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
20086 N->getOperand(1), UNDEF);
20087 Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
20090 case ISD::SIGN_EXTEND_INREG:
20095 // We don't want to expand or promote these.
20102 case ISD::UDIVREM: {
20103 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
20104 Results.push_back(V);
20107 case ISD::FP_TO_SINT:
20108 case ISD::FP_TO_UINT: {
20109 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
20111 std::pair<SDValue,SDValue> Vals =
20112 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
20113 SDValue FIST = Vals.first, StackSlot = Vals.second;
20114 if (FIST.getNode()) {
20115 EVT VT = N->getValueType(0);
20116 // Return a load from the stack slot.
20117 if (StackSlot.getNode())
20118 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
20119 MachinePointerInfo(),
20120 false, false, false, 0));
20122 Results.push_back(FIST);
20126 case ISD::UINT_TO_FP: {
20127 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
20128 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
20129 N->getValueType(0) != MVT::v2f32)
20131 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
20133 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
20135 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
20136 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
20137 DAG.getBitcast(MVT::v2i64, VBias));
20138 Or = DAG.getBitcast(MVT::v2f64, Or);
20139 // TODO: Are there any fast-math-flags to propagate here?
20140 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
20141 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
20144 case ISD::FP_ROUND: {
20145 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
20147 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
20148 Results.push_back(V);
20151 case ISD::FP_EXTEND: {
20152 // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
20153 // No other ValueType for FP_EXTEND should reach this point.
20154 assert(N->getValueType(0) == MVT::v2f32 &&
20155 "Do not know how to legalize this Node");
20158 case ISD::INTRINSIC_W_CHAIN: {
20159 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
20161 default : llvm_unreachable("Do not know how to custom type "
20162 "legalize this intrinsic operation!");
20163 case Intrinsic::x86_rdtsc:
20164 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
20166 case Intrinsic::x86_rdtscp:
20167 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
20169 case Intrinsic::x86_rdpmc:
20170 return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
20173 case ISD::INTRINSIC_WO_CHAIN: {
20174 if (SDValue V = LowerINTRINSIC_WO_CHAIN(SDValue(N, 0), Subtarget, DAG))
20175 Results.push_back(V);
20178 case ISD::READCYCLECOUNTER: {
20179 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
20182 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
20183 EVT T = N->getValueType(0);
20184 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
20185 bool Regs64bit = T == MVT::i128;
20186 MVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
20187 SDValue cpInL, cpInH;
20188 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
20189 DAG.getConstant(0, dl, HalfT));
20190 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
20191 DAG.getConstant(1, dl, HalfT));
20192 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
20193 Regs64bit ? X86::RAX : X86::EAX,
20195 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
20196 Regs64bit ? X86::RDX : X86::EDX,
20197 cpInH, cpInL.getValue(1));
20198 SDValue swapInL, swapInH;
20199 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
20200 DAG.getConstant(0, dl, HalfT));
20201 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
20202 DAG.getConstant(1, dl, HalfT));
20203 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
20204 Regs64bit ? X86::RBX : X86::EBX,
20205 swapInL, cpInH.getValue(1));
20206 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
20207 Regs64bit ? X86::RCX : X86::ECX,
20208 swapInH, swapInL.getValue(1));
20209 SDValue Ops[] = { swapInH.getValue(0),
20211 swapInH.getValue(1) };
20212 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
20213 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
20214 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
20215 X86ISD::LCMPXCHG8_DAG;
20216 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
20217 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
20218 Regs64bit ? X86::RAX : X86::EAX,
20219 HalfT, Result.getValue(1));
20220 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
20221 Regs64bit ? X86::RDX : X86::EDX,
20222 HalfT, cpOutL.getValue(2));
20223 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
20225 SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
20226 MVT::i32, cpOutH.getValue(2));
20228 DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
20229 DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
20230 Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
20232 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
20233 Results.push_back(Success);
20234 Results.push_back(EFLAGS.getValue(1));
20237 case ISD::ATOMIC_SWAP:
20238 case ISD::ATOMIC_LOAD_ADD:
20239 case ISD::ATOMIC_LOAD_SUB:
20240 case ISD::ATOMIC_LOAD_AND:
20241 case ISD::ATOMIC_LOAD_OR:
20242 case ISD::ATOMIC_LOAD_XOR:
20243 case ISD::ATOMIC_LOAD_NAND:
20244 case ISD::ATOMIC_LOAD_MIN:
20245 case ISD::ATOMIC_LOAD_MAX:
20246 case ISD::ATOMIC_LOAD_UMIN:
20247 case ISD::ATOMIC_LOAD_UMAX:
20248 case ISD::ATOMIC_LOAD: {
20249 // Delegate to generic TypeLegalization. Situations we can really handle
20250 // should have already been dealt with by AtomicExpandPass.cpp.
20253 case ISD::BITCAST: {
20254 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
20255 EVT DstVT = N->getValueType(0);
20256 EVT SrcVT = N->getOperand(0)->getValueType(0);
20258 if (SrcVT != MVT::f64 ||
20259 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
20262 unsigned NumElts = DstVT.getVectorNumElements();
20263 EVT SVT = DstVT.getVectorElementType();
20264 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
20265 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
20266 MVT::v2f64, N->getOperand(0));
20267 SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
20269 if (ExperimentalVectorWideningLegalization) {
20270 // If we are legalizing vectors by widening, we already have the desired
20271 // legal vector type, just return it.
20272 Results.push_back(ToVecInt);
20276 SmallVector<SDValue, 8> Elts;
20277 for (unsigned i = 0, e = NumElts; i != e; ++i)
20278 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
20279 ToVecInt, DAG.getIntPtrConstant(i, dl)));
20281 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
20286 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
20287 switch ((X86ISD::NodeType)Opcode) {
20288 case X86ISD::FIRST_NUMBER: break;
20289 case X86ISD::BSF: return "X86ISD::BSF";
20290 case X86ISD::BSR: return "X86ISD::BSR";
20291 case X86ISD::SHLD: return "X86ISD::SHLD";
20292 case X86ISD::SHRD: return "X86ISD::SHRD";
20293 case X86ISD::FAND: return "X86ISD::FAND";
20294 case X86ISD::FANDN: return "X86ISD::FANDN";
20295 case X86ISD::FOR: return "X86ISD::FOR";
20296 case X86ISD::FXOR: return "X86ISD::FXOR";
20297 case X86ISD::FILD: return "X86ISD::FILD";
20298 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
20299 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
20300 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
20301 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
20302 case X86ISD::FLD: return "X86ISD::FLD";
20303 case X86ISD::FST: return "X86ISD::FST";
20304 case X86ISD::CALL: return "X86ISD::CALL";
20305 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
20306 case X86ISD::RDTSCP_DAG: return "X86ISD::RDTSCP_DAG";
20307 case X86ISD::RDPMC_DAG: return "X86ISD::RDPMC_DAG";
20308 case X86ISD::BT: return "X86ISD::BT";
20309 case X86ISD::CMP: return "X86ISD::CMP";
20310 case X86ISD::COMI: return "X86ISD::COMI";
20311 case X86ISD::UCOMI: return "X86ISD::UCOMI";
20312 case X86ISD::CMPM: return "X86ISD::CMPM";
20313 case X86ISD::CMPMU: return "X86ISD::CMPMU";
20314 case X86ISD::CMPM_RND: return "X86ISD::CMPM_RND";
20315 case X86ISD::SETCC: return "X86ISD::SETCC";
20316 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
20317 case X86ISD::FSETCC: return "X86ISD::FSETCC";
20318 case X86ISD::FGETSIGNx86: return "X86ISD::FGETSIGNx86";
20319 case X86ISD::CMOV: return "X86ISD::CMOV";
20320 case X86ISD::BRCOND: return "X86ISD::BRCOND";
20321 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
20322 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
20323 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
20324 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
20325 case X86ISD::Wrapper: return "X86ISD::Wrapper";
20326 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
20327 case X86ISD::MOVDQ2Q: return "X86ISD::MOVDQ2Q";
20328 case X86ISD::MMX_MOVD2W: return "X86ISD::MMX_MOVD2W";
20329 case X86ISD::MMX_MOVW2D: return "X86ISD::MMX_MOVW2D";
20330 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
20331 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
20332 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
20333 case X86ISD::PINSRB: return "X86ISD::PINSRB";
20334 case X86ISD::PINSRW: return "X86ISD::PINSRW";
20335 case X86ISD::MMX_PINSRW: return "X86ISD::MMX_PINSRW";
20336 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
20337 case X86ISD::ANDNP: return "X86ISD::ANDNP";
20338 case X86ISD::PSIGN: return "X86ISD::PSIGN";
20339 case X86ISD::BLENDI: return "X86ISD::BLENDI";
20340 case X86ISD::SHRUNKBLEND: return "X86ISD::SHRUNKBLEND";
20341 case X86ISD::ADDUS: return "X86ISD::ADDUS";
20342 case X86ISD::SUBUS: return "X86ISD::SUBUS";
20343 case X86ISD::HADD: return "X86ISD::HADD";
20344 case X86ISD::HSUB: return "X86ISD::HSUB";
20345 case X86ISD::FHADD: return "X86ISD::FHADD";
20346 case X86ISD::FHSUB: return "X86ISD::FHSUB";
20347 case X86ISD::ABS: return "X86ISD::ABS";
20348 case X86ISD::CONFLICT: return "X86ISD::CONFLICT";
20349 case X86ISD::FMAX: return "X86ISD::FMAX";
20350 case X86ISD::FMAX_RND: return "X86ISD::FMAX_RND";
20351 case X86ISD::FMIN: return "X86ISD::FMIN";
20352 case X86ISD::FMIN_RND: return "X86ISD::FMIN_RND";
20353 case X86ISD::FMAXC: return "X86ISD::FMAXC";
20354 case X86ISD::FMINC: return "X86ISD::FMINC";
20355 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
20356 case X86ISD::FRCP: return "X86ISD::FRCP";
20357 case X86ISD::EXTRQI: return "X86ISD::EXTRQI";
20358 case X86ISD::INSERTQI: return "X86ISD::INSERTQI";
20359 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
20360 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
20361 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
20362 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
20363 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
20364 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
20365 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
20366 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
20367 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
20368 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
20369 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
20370 case X86ISD::LCMPXCHG16_DAG: return "X86ISD::LCMPXCHG16_DAG";
20371 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
20372 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
20373 case X86ISD::VZEXT: return "X86ISD::VZEXT";
20374 case X86ISD::VSEXT: return "X86ISD::VSEXT";
20375 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
20376 case X86ISD::VTRUNCS: return "X86ISD::VTRUNCS";
20377 case X86ISD::VTRUNCUS: return "X86ISD::VTRUNCUS";
20378 case X86ISD::VINSERT: return "X86ISD::VINSERT";
20379 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
20380 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
20381 case X86ISD::CVTDQ2PD: return "X86ISD::CVTDQ2PD";
20382 case X86ISD::CVTUDQ2PD: return "X86ISD::CVTUDQ2PD";
20383 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
20384 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
20385 case X86ISD::VSHL: return "X86ISD::VSHL";
20386 case X86ISD::VSRL: return "X86ISD::VSRL";
20387 case X86ISD::VSRA: return "X86ISD::VSRA";
20388 case X86ISD::VSHLI: return "X86ISD::VSHLI";
20389 case X86ISD::VSRLI: return "X86ISD::VSRLI";
20390 case X86ISD::VSRAI: return "X86ISD::VSRAI";
20391 case X86ISD::CMPP: return "X86ISD::CMPP";
20392 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
20393 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
20394 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
20395 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
20396 case X86ISD::ADD: return "X86ISD::ADD";
20397 case X86ISD::SUB: return "X86ISD::SUB";
20398 case X86ISD::ADC: return "X86ISD::ADC";
20399 case X86ISD::SBB: return "X86ISD::SBB";
20400 case X86ISD::SMUL: return "X86ISD::SMUL";
20401 case X86ISD::UMUL: return "X86ISD::UMUL";
20402 case X86ISD::SMUL8: return "X86ISD::SMUL8";
20403 case X86ISD::UMUL8: return "X86ISD::UMUL8";
20404 case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
20405 case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
20406 case X86ISD::INC: return "X86ISD::INC";
20407 case X86ISD::DEC: return "X86ISD::DEC";
20408 case X86ISD::OR: return "X86ISD::OR";
20409 case X86ISD::XOR: return "X86ISD::XOR";
20410 case X86ISD::AND: return "X86ISD::AND";
20411 case X86ISD::BEXTR: return "X86ISD::BEXTR";
20412 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
20413 case X86ISD::PTEST: return "X86ISD::PTEST";
20414 case X86ISD::TESTP: return "X86ISD::TESTP";
20415 case X86ISD::TESTM: return "X86ISD::TESTM";
20416 case X86ISD::TESTNM: return "X86ISD::TESTNM";
20417 case X86ISD::KORTEST: return "X86ISD::KORTEST";
20418 case X86ISD::KTEST: return "X86ISD::KTEST";
20419 case X86ISD::PACKSS: return "X86ISD::PACKSS";
20420 case X86ISD::PACKUS: return "X86ISD::PACKUS";
20421 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
20422 case X86ISD::VALIGN: return "X86ISD::VALIGN";
20423 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
20424 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
20425 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
20426 case X86ISD::SHUFP: return "X86ISD::SHUFP";
20427 case X86ISD::SHUF128: return "X86ISD::SHUF128";
20428 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
20429 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
20430 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
20431 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
20432 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
20433 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
20434 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
20435 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
20436 case X86ISD::MOVSD: return "X86ISD::MOVSD";
20437 case X86ISD::MOVSS: return "X86ISD::MOVSS";
20438 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
20439 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
20440 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
20441 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
20442 case X86ISD::SUBV_BROADCAST: return "X86ISD::SUBV_BROADCAST";
20443 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
20444 case X86ISD::VPERMILPV: return "X86ISD::VPERMILPV";
20445 case X86ISD::VPERMILPI: return "X86ISD::VPERMILPI";
20446 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
20447 case X86ISD::VPERMV: return "X86ISD::VPERMV";
20448 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
20449 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
20450 case X86ISD::VPERMI: return "X86ISD::VPERMI";
20451 case X86ISD::VPTERNLOG: return "X86ISD::VPTERNLOG";
20452 case X86ISD::VFIXUPIMM: return "X86ISD::VFIXUPIMM";
20453 case X86ISD::VRANGE: return "X86ISD::VRANGE";
20454 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
20455 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
20456 case X86ISD::PSADBW: return "X86ISD::PSADBW";
20457 case X86ISD::DBPSADBW: return "X86ISD::DBPSADBW";
20458 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
20459 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
20460 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
20461 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
20462 case X86ISD::MFENCE: return "X86ISD::MFENCE";
20463 case X86ISD::SFENCE: return "X86ISD::SFENCE";
20464 case X86ISD::LFENCE: return "X86ISD::LFENCE";
20465 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
20466 case X86ISD::SAHF: return "X86ISD::SAHF";
20467 case X86ISD::RDRAND: return "X86ISD::RDRAND";
20468 case X86ISD::RDSEED: return "X86ISD::RDSEED";
20469 case X86ISD::VPMADDUBSW: return "X86ISD::VPMADDUBSW";
20470 case X86ISD::VPMADDWD: return "X86ISD::VPMADDWD";
20471 case X86ISD::VPROT: return "X86ISD::VPROT";
20472 case X86ISD::VPROTI: return "X86ISD::VPROTI";
20473 case X86ISD::VPSHA: return "X86ISD::VPSHA";
20474 case X86ISD::VPSHL: return "X86ISD::VPSHL";
20475 case X86ISD::VPCOM: return "X86ISD::VPCOM";
20476 case X86ISD::VPCOMU: return "X86ISD::VPCOMU";
20477 case X86ISD::FMADD: return "X86ISD::FMADD";
20478 case X86ISD::FMSUB: return "X86ISD::FMSUB";
20479 case X86ISD::FNMADD: return "X86ISD::FNMADD";
20480 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
20481 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
20482 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
20483 case X86ISD::FMADD_RND: return "X86ISD::FMADD_RND";
20484 case X86ISD::FNMADD_RND: return "X86ISD::FNMADD_RND";
20485 case X86ISD::FMSUB_RND: return "X86ISD::FMSUB_RND";
20486 case X86ISD::FNMSUB_RND: return "X86ISD::FNMSUB_RND";
20487 case X86ISD::FMADDSUB_RND: return "X86ISD::FMADDSUB_RND";
20488 case X86ISD::FMSUBADD_RND: return "X86ISD::FMSUBADD_RND";
20489 case X86ISD::VRNDSCALE: return "X86ISD::VRNDSCALE";
20490 case X86ISD::VREDUCE: return "X86ISD::VREDUCE";
20491 case X86ISD::VGETMANT: return "X86ISD::VGETMANT";
20492 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
20493 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
20494 case X86ISD::XTEST: return "X86ISD::XTEST";
20495 case X86ISD::COMPRESS: return "X86ISD::COMPRESS";
20496 case X86ISD::EXPAND: return "X86ISD::EXPAND";
20497 case X86ISD::SELECT: return "X86ISD::SELECT";
20498 case X86ISD::ADDSUB: return "X86ISD::ADDSUB";
20499 case X86ISD::RCP28: return "X86ISD::RCP28";
20500 case X86ISD::EXP2: return "X86ISD::EXP2";
20501 case X86ISD::RSQRT28: return "X86ISD::RSQRT28";
20502 case X86ISD::FADD_RND: return "X86ISD::FADD_RND";
20503 case X86ISD::FSUB_RND: return "X86ISD::FSUB_RND";
20504 case X86ISD::FMUL_RND: return "X86ISD::FMUL_RND";
20505 case X86ISD::FDIV_RND: return "X86ISD::FDIV_RND";
20506 case X86ISD::FSQRT_RND: return "X86ISD::FSQRT_RND";
20507 case X86ISD::FGETEXP_RND: return "X86ISD::FGETEXP_RND";
20508 case X86ISD::SCALEF: return "X86ISD::SCALEF";
20509 case X86ISD::ADDS: return "X86ISD::ADDS";
20510 case X86ISD::SUBS: return "X86ISD::SUBS";
20511 case X86ISD::AVG: return "X86ISD::AVG";
20512 case X86ISD::MULHRS: return "X86ISD::MULHRS";
20513 case X86ISD::SINT_TO_FP_RND: return "X86ISD::SINT_TO_FP_RND";
20514 case X86ISD::UINT_TO_FP_RND: return "X86ISD::UINT_TO_FP_RND";
20515 case X86ISD::FP_TO_SINT_RND: return "X86ISD::FP_TO_SINT_RND";
20516 case X86ISD::FP_TO_UINT_RND: return "X86ISD::FP_TO_UINT_RND";
20517 case X86ISD::VFPCLASS: return "X86ISD::VFPCLASS";
20518 case X86ISD::VFPCLASSS: return "X86ISD::VFPCLASSS";
20523 // isLegalAddressingMode - Return true if the addressing mode represented
20524 // by AM is legal for this target, for a load/store of the specified type.
20525 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
20526 const AddrMode &AM, Type *Ty,
20527 unsigned AS) const {
20528 // X86 supports extremely general addressing modes.
20529 CodeModel::Model M = getTargetMachine().getCodeModel();
20530 Reloc::Model R = getTargetMachine().getRelocationModel();
20532 // X86 allows a sign-extended 32-bit immediate field as a displacement.
20533 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
20538 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
20540 // If a reference to this global requires an extra load, we can't fold it.
20541 if (isGlobalStubReference(GVFlags))
20544 // If BaseGV requires a register for the PIC base, we cannot also have a
20545 // BaseReg specified.
20546 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
20549 // If lower 4G is not available, then we must use rip-relative addressing.
20550 if ((M != CodeModel::Small || R != Reloc::Static) &&
20551 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
20555 switch (AM.Scale) {
20561 // These scales always work.
20566 // These scales are formed with basereg+scalereg. Only accept if there is
20571 default: // Other stuff never works.
20578 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
20579 unsigned Bits = Ty->getScalarSizeInBits();
20581 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
20582 // particularly cheaper than those without.
20586 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
20587 // variable shifts just as cheap as scalar ones.
20588 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
20591 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
20592 // fully general vector.
20596 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
20597 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
20599 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
20600 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
20601 return NumBits1 > NumBits2;
20604 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
20605 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
20608 if (!isTypeLegal(EVT::getEVT(Ty1)))
20611 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
20613 // Assuming the caller doesn't have a zeroext or signext return parameter,
20614 // truncation all the way down to i1 is valid.
20618 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
20619 return isInt<32>(Imm);
20622 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
20623 // Can also use sub to handle negated immediates.
20624 return isInt<32>(Imm);
20627 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
20628 if (!VT1.isInteger() || !VT2.isInteger())
20630 unsigned NumBits1 = VT1.getSizeInBits();
20631 unsigned NumBits2 = VT2.getSizeInBits();
20632 return NumBits1 > NumBits2;
20635 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
20636 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
20637 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
20640 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
20641 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
20642 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
20645 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
20646 EVT VT1 = Val.getValueType();
20647 if (isZExtFree(VT1, VT2))
20650 if (Val.getOpcode() != ISD::LOAD)
20653 if (!VT1.isSimple() || !VT1.isInteger() ||
20654 !VT2.isSimple() || !VT2.isInteger())
20657 switch (VT1.getSimpleVT().SimpleTy) {
20662 // X86 has 8, 16, and 32-bit zero-extending loads.
20669 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
20672 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
20673 if (!Subtarget->hasAnyFMA())
20676 VT = VT.getScalarType();
20678 if (!VT.isSimple())
20681 switch (VT.getSimpleVT().SimpleTy) {
20692 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
20693 // i16 instructions are longer (0x66 prefix) and potentially slower.
20694 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
20697 /// isShuffleMaskLegal - Targets can use this to indicate that they only
20698 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
20699 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
20700 /// are assumed to be legal.
20702 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
20704 if (!VT.isSimple())
20707 // Not for i1 vectors
20708 if (VT.getSimpleVT().getScalarType() == MVT::i1)
20711 // Very little shuffling can be done for 64-bit vectors right now.
20712 if (VT.getSimpleVT().getSizeInBits() == 64)
20715 // We only care that the types being shuffled are legal. The lowering can
20716 // handle any possible shuffle mask that results.
20717 return isTypeLegal(VT.getSimpleVT());
20721 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
20723 // Just delegate to the generic legality, clear masks aren't special.
20724 return isShuffleMaskLegal(Mask, VT);
20727 //===----------------------------------------------------------------------===//
20728 // X86 Scheduler Hooks
20729 //===----------------------------------------------------------------------===//
20731 /// Utility function to emit xbegin specifying the start of an RTM region.
20732 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
20733 const TargetInstrInfo *TII) {
20734 DebugLoc DL = MI->getDebugLoc();
20736 const BasicBlock *BB = MBB->getBasicBlock();
20737 MachineFunction::iterator I = ++MBB->getIterator();
20739 // For the v = xbegin(), we generate
20750 MachineBasicBlock *thisMBB = MBB;
20751 MachineFunction *MF = MBB->getParent();
20752 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20753 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20754 MF->insert(I, mainMBB);
20755 MF->insert(I, sinkMBB);
20757 // Transfer the remainder of BB and its successor edges to sinkMBB.
20758 sinkMBB->splice(sinkMBB->begin(), MBB,
20759 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20760 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20764 // # fallthrough to mainMBB
20765 // # abortion to sinkMBB
20766 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
20767 thisMBB->addSuccessor(mainMBB);
20768 thisMBB->addSuccessor(sinkMBB);
20772 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
20773 mainMBB->addSuccessor(sinkMBB);
20776 // EAX is live into the sinkMBB
20777 sinkMBB->addLiveIn(X86::EAX);
20778 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20779 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20782 MI->eraseFromParent();
20786 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
20787 // or XMM0_V32I8 in AVX all of this code can be replaced with that
20788 // in the .td file.
20789 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
20790 const TargetInstrInfo *TII) {
20792 switch (MI->getOpcode()) {
20793 default: llvm_unreachable("illegal opcode!");
20794 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
20795 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
20796 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
20797 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
20798 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
20799 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
20800 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
20801 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
20804 DebugLoc dl = MI->getDebugLoc();
20805 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
20807 unsigned NumArgs = MI->getNumOperands();
20808 for (unsigned i = 1; i < NumArgs; ++i) {
20809 MachineOperand &Op = MI->getOperand(i);
20810 if (!(Op.isReg() && Op.isImplicit()))
20811 MIB.addOperand(Op);
20813 if (MI->hasOneMemOperand())
20814 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
20816 BuildMI(*BB, MI, dl,
20817 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20818 .addReg(X86::XMM0);
20820 MI->eraseFromParent();
20824 // FIXME: Custom handling because TableGen doesn't support multiple implicit
20825 // defs in an instruction pattern
20826 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
20827 const TargetInstrInfo *TII) {
20829 switch (MI->getOpcode()) {
20830 default: llvm_unreachable("illegal opcode!");
20831 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
20832 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
20833 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
20834 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
20835 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
20836 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
20837 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
20838 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
20841 DebugLoc dl = MI->getDebugLoc();
20842 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
20844 unsigned NumArgs = MI->getNumOperands(); // remove the results
20845 for (unsigned i = 1; i < NumArgs; ++i) {
20846 MachineOperand &Op = MI->getOperand(i);
20847 if (!(Op.isReg() && Op.isImplicit()))
20848 MIB.addOperand(Op);
20850 if (MI->hasOneMemOperand())
20851 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
20853 BuildMI(*BB, MI, dl,
20854 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
20857 MI->eraseFromParent();
20861 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
20862 const X86Subtarget *Subtarget) {
20863 DebugLoc dl = MI->getDebugLoc();
20864 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20865 // Address into RAX/EAX, other two args into ECX, EDX.
20866 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
20867 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
20868 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
20869 for (int i = 0; i < X86::AddrNumOperands; ++i)
20870 MIB.addOperand(MI->getOperand(i));
20872 unsigned ValOps = X86::AddrNumOperands;
20873 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
20874 .addReg(MI->getOperand(ValOps).getReg());
20875 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
20876 .addReg(MI->getOperand(ValOps+1).getReg());
20878 // The instruction doesn't actually take any operands though.
20879 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
20881 MI->eraseFromParent(); // The pseudo is gone now.
20885 MachineBasicBlock *
20886 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
20887 MachineBasicBlock *MBB) const {
20888 // Emit va_arg instruction on X86-64.
20890 // Operands to this pseudo-instruction:
20891 // 0 ) Output : destination address (reg)
20892 // 1-5) Input : va_list address (addr, i64mem)
20893 // 6 ) ArgSize : Size (in bytes) of vararg type
20894 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
20895 // 8 ) Align : Alignment of type
20896 // 9 ) EFLAGS (implicit-def)
20898 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
20899 static_assert(X86::AddrNumOperands == 5,
20900 "VAARG_64 assumes 5 address operands");
20902 unsigned DestReg = MI->getOperand(0).getReg();
20903 MachineOperand &Base = MI->getOperand(1);
20904 MachineOperand &Scale = MI->getOperand(2);
20905 MachineOperand &Index = MI->getOperand(3);
20906 MachineOperand &Disp = MI->getOperand(4);
20907 MachineOperand &Segment = MI->getOperand(5);
20908 unsigned ArgSize = MI->getOperand(6).getImm();
20909 unsigned ArgMode = MI->getOperand(7).getImm();
20910 unsigned Align = MI->getOperand(8).getImm();
20912 // Memory Reference
20913 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
20914 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20915 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20917 // Machine Information
20918 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20919 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
20920 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
20921 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
20922 DebugLoc DL = MI->getDebugLoc();
20924 // struct va_list {
20927 // i64 overflow_area (address)
20928 // i64 reg_save_area (address)
20930 // sizeof(va_list) = 24
20931 // alignment(va_list) = 8
20933 unsigned TotalNumIntRegs = 6;
20934 unsigned TotalNumXMMRegs = 8;
20935 bool UseGPOffset = (ArgMode == 1);
20936 bool UseFPOffset = (ArgMode == 2);
20937 unsigned MaxOffset = TotalNumIntRegs * 8 +
20938 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
20940 /* Align ArgSize to a multiple of 8 */
20941 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
20942 bool NeedsAlign = (Align > 8);
20944 MachineBasicBlock *thisMBB = MBB;
20945 MachineBasicBlock *overflowMBB;
20946 MachineBasicBlock *offsetMBB;
20947 MachineBasicBlock *endMBB;
20949 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
20950 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
20951 unsigned OffsetReg = 0;
20953 if (!UseGPOffset && !UseFPOffset) {
20954 // If we only pull from the overflow region, we don't create a branch.
20955 // We don't need to alter control flow.
20956 OffsetDestReg = 0; // unused
20957 OverflowDestReg = DestReg;
20959 offsetMBB = nullptr;
20960 overflowMBB = thisMBB;
20963 // First emit code to check if gp_offset (or fp_offset) is below the bound.
20964 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
20965 // If not, pull from overflow_area. (branch to overflowMBB)
20970 // offsetMBB overflowMBB
20975 // Registers for the PHI in endMBB
20976 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
20977 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
20979 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
20980 MachineFunction *MF = MBB->getParent();
20981 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20982 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20983 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20985 MachineFunction::iterator MBBIter = ++MBB->getIterator();
20987 // Insert the new basic blocks
20988 MF->insert(MBBIter, offsetMBB);
20989 MF->insert(MBBIter, overflowMBB);
20990 MF->insert(MBBIter, endMBB);
20992 // Transfer the remainder of MBB and its successor edges to endMBB.
20993 endMBB->splice(endMBB->begin(), thisMBB,
20994 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
20995 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
20997 // Make offsetMBB and overflowMBB successors of thisMBB
20998 thisMBB->addSuccessor(offsetMBB);
20999 thisMBB->addSuccessor(overflowMBB);
21001 // endMBB is a successor of both offsetMBB and overflowMBB
21002 offsetMBB->addSuccessor(endMBB);
21003 overflowMBB->addSuccessor(endMBB);
21005 // Load the offset value into a register
21006 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
21007 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
21011 .addDisp(Disp, UseFPOffset ? 4 : 0)
21012 .addOperand(Segment)
21013 .setMemRefs(MMOBegin, MMOEnd);
21015 // Check if there is enough room left to pull this argument.
21016 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
21018 .addImm(MaxOffset + 8 - ArgSizeA8);
21020 // Branch to "overflowMBB" if offset >= max
21021 // Fall through to "offsetMBB" otherwise
21022 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
21023 .addMBB(overflowMBB);
21026 // In offsetMBB, emit code to use the reg_save_area.
21028 assert(OffsetReg != 0);
21030 // Read the reg_save_area address.
21031 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
21032 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
21037 .addOperand(Segment)
21038 .setMemRefs(MMOBegin, MMOEnd);
21040 // Zero-extend the offset
21041 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
21042 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
21045 .addImm(X86::sub_32bit);
21047 // Add the offset to the reg_save_area to get the final address.
21048 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
21049 .addReg(OffsetReg64)
21050 .addReg(RegSaveReg);
21052 // Compute the offset for the next argument
21053 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
21054 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
21056 .addImm(UseFPOffset ? 16 : 8);
21058 // Store it back into the va_list.
21059 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
21063 .addDisp(Disp, UseFPOffset ? 4 : 0)
21064 .addOperand(Segment)
21065 .addReg(NextOffsetReg)
21066 .setMemRefs(MMOBegin, MMOEnd);
21069 BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
21074 // Emit code to use overflow area
21077 // Load the overflow_area address into a register.
21078 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
21079 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
21084 .addOperand(Segment)
21085 .setMemRefs(MMOBegin, MMOEnd);
21087 // If we need to align it, do so. Otherwise, just copy the address
21088 // to OverflowDestReg.
21090 // Align the overflow address
21091 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
21092 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
21094 // aligned_addr = (addr + (align-1)) & ~(align-1)
21095 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
21096 .addReg(OverflowAddrReg)
21099 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
21101 .addImm(~(uint64_t)(Align-1));
21103 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
21104 .addReg(OverflowAddrReg);
21107 // Compute the next overflow address after this argument.
21108 // (the overflow address should be kept 8-byte aligned)
21109 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
21110 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
21111 .addReg(OverflowDestReg)
21112 .addImm(ArgSizeA8);
21114 // Store the new overflow address.
21115 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
21120 .addOperand(Segment)
21121 .addReg(NextAddrReg)
21122 .setMemRefs(MMOBegin, MMOEnd);
21124 // If we branched, emit the PHI to the front of endMBB.
21126 BuildMI(*endMBB, endMBB->begin(), DL,
21127 TII->get(X86::PHI), DestReg)
21128 .addReg(OffsetDestReg).addMBB(offsetMBB)
21129 .addReg(OverflowDestReg).addMBB(overflowMBB);
21132 // Erase the pseudo instruction
21133 MI->eraseFromParent();
21138 MachineBasicBlock *
21139 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
21141 MachineBasicBlock *MBB) const {
21142 // Emit code to save XMM registers to the stack. The ABI says that the
21143 // number of registers to save is given in %al, so it's theoretically
21144 // possible to do an indirect jump trick to avoid saving all of them,
21145 // however this code takes a simpler approach and just executes all
21146 // of the stores if %al is non-zero. It's less code, and it's probably
21147 // easier on the hardware branch predictor, and stores aren't all that
21148 // expensive anyway.
21150 // Create the new basic blocks. One block contains all the XMM stores,
21151 // and one block is the final destination regardless of whether any
21152 // stores were performed.
21153 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
21154 MachineFunction *F = MBB->getParent();
21155 MachineFunction::iterator MBBIter = ++MBB->getIterator();
21156 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
21157 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
21158 F->insert(MBBIter, XMMSaveMBB);
21159 F->insert(MBBIter, EndMBB);
21161 // Transfer the remainder of MBB and its successor edges to EndMBB.
21162 EndMBB->splice(EndMBB->begin(), MBB,
21163 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
21164 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
21166 // The original block will now fall through to the XMM save block.
21167 MBB->addSuccessor(XMMSaveMBB);
21168 // The XMMSaveMBB will fall through to the end block.
21169 XMMSaveMBB->addSuccessor(EndMBB);
21171 // Now add the instructions.
21172 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21173 DebugLoc DL = MI->getDebugLoc();
21175 unsigned CountReg = MI->getOperand(0).getReg();
21176 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
21177 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
21179 if (!Subtarget->isCallingConvWin64(F->getFunction()->getCallingConv())) {
21180 // If %al is 0, branch around the XMM save block.
21181 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
21182 BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
21183 MBB->addSuccessor(EndMBB);
21186 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
21187 // that was just emitted, but clearly shouldn't be "saved".
21188 assert((MI->getNumOperands() <= 3 ||
21189 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
21190 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
21191 && "Expected last argument to be EFLAGS");
21192 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
21193 // In the XMM save block, save all the XMM argument registers.
21194 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
21195 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
21196 MachineMemOperand *MMO = F->getMachineMemOperand(
21197 MachinePointerInfo::getFixedStack(*F, RegSaveFrameIndex, Offset),
21198 MachineMemOperand::MOStore,
21199 /*Size=*/16, /*Align=*/16);
21200 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
21201 .addFrameIndex(RegSaveFrameIndex)
21202 .addImm(/*Scale=*/1)
21203 .addReg(/*IndexReg=*/0)
21204 .addImm(/*Disp=*/Offset)
21205 .addReg(/*Segment=*/0)
21206 .addReg(MI->getOperand(i).getReg())
21207 .addMemOperand(MMO);
21210 MI->eraseFromParent(); // The pseudo instruction is gone now.
21215 // The EFLAGS operand of SelectItr might be missing a kill marker
21216 // because there were multiple uses of EFLAGS, and ISel didn't know
21217 // which to mark. Figure out whether SelectItr should have had a
21218 // kill marker, and set it if it should. Returns the correct kill
21220 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
21221 MachineBasicBlock* BB,
21222 const TargetRegisterInfo* TRI) {
21223 // Scan forward through BB for a use/def of EFLAGS.
21224 MachineBasicBlock::iterator miI(std::next(SelectItr));
21225 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
21226 const MachineInstr& mi = *miI;
21227 if (mi.readsRegister(X86::EFLAGS))
21229 if (mi.definesRegister(X86::EFLAGS))
21230 break; // Should have kill-flag - update below.
21233 // If we hit the end of the block, check whether EFLAGS is live into a
21235 if (miI == BB->end()) {
21236 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
21237 sEnd = BB->succ_end();
21238 sItr != sEnd; ++sItr) {
21239 MachineBasicBlock* succ = *sItr;
21240 if (succ->isLiveIn(X86::EFLAGS))
21245 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
21246 // out. SelectMI should have a kill flag on EFLAGS.
21247 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
21251 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
21252 // together with other CMOV pseudo-opcodes into a single basic-block with
21253 // conditional jump around it.
21254 static bool isCMOVPseudo(MachineInstr *MI) {
21255 switch (MI->getOpcode()) {
21256 case X86::CMOV_FR32:
21257 case X86::CMOV_FR64:
21258 case X86::CMOV_GR8:
21259 case X86::CMOV_GR16:
21260 case X86::CMOV_GR32:
21261 case X86::CMOV_RFP32:
21262 case X86::CMOV_RFP64:
21263 case X86::CMOV_RFP80:
21264 case X86::CMOV_V2F64:
21265 case X86::CMOV_V2I64:
21266 case X86::CMOV_V4F32:
21267 case X86::CMOV_V4F64:
21268 case X86::CMOV_V4I64:
21269 case X86::CMOV_V16F32:
21270 case X86::CMOV_V8F32:
21271 case X86::CMOV_V8F64:
21272 case X86::CMOV_V8I64:
21273 case X86::CMOV_V8I1:
21274 case X86::CMOV_V16I1:
21275 case X86::CMOV_V32I1:
21276 case X86::CMOV_V64I1:
21284 MachineBasicBlock *
21285 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
21286 MachineBasicBlock *BB) const {
21287 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21288 DebugLoc DL = MI->getDebugLoc();
21290 // To "insert" a SELECT_CC instruction, we actually have to insert the
21291 // diamond control-flow pattern. The incoming instruction knows the
21292 // destination vreg to set, the condition code register to branch on, the
21293 // true/false values to select between, and a branch opcode to use.
21294 const BasicBlock *LLVM_BB = BB->getBasicBlock();
21295 MachineFunction::iterator It = ++BB->getIterator();
21300 // cmpTY ccX, r1, r2
21302 // fallthrough --> copy0MBB
21303 MachineBasicBlock *thisMBB = BB;
21304 MachineFunction *F = BB->getParent();
21306 // This code lowers all pseudo-CMOV instructions. Generally it lowers these
21307 // as described above, by inserting a BB, and then making a PHI at the join
21308 // point to select the true and false operands of the CMOV in the PHI.
21310 // The code also handles two different cases of multiple CMOV opcodes
21314 // In this case, there are multiple CMOVs in a row, all which are based on
21315 // the same condition setting (or the exact opposite condition setting).
21316 // In this case we can lower all the CMOVs using a single inserted BB, and
21317 // then make a number of PHIs at the join point to model the CMOVs. The only
21318 // trickiness here, is that in a case like:
21320 // t2 = CMOV cond1 t1, f1
21321 // t3 = CMOV cond1 t2, f2
21323 // when rewriting this into PHIs, we have to perform some renaming on the
21324 // temps since you cannot have a PHI operand refer to a PHI result earlier
21325 // in the same block. The "simple" but wrong lowering would be:
21327 // t2 = PHI t1(BB1), f1(BB2)
21328 // t3 = PHI t2(BB1), f2(BB2)
21330 // but clearly t2 is not defined in BB1, so that is incorrect. The proper
21331 // renaming is to note that on the path through BB1, t2 is really just a
21332 // copy of t1, and do that renaming, properly generating:
21334 // t2 = PHI t1(BB1), f1(BB2)
21335 // t3 = PHI t1(BB1), f2(BB2)
21337 // Case 2, we lower cascaded CMOVs such as
21339 // (CMOV (CMOV F, T, cc1), T, cc2)
21341 // to two successives branches. For that, we look for another CMOV as the
21342 // following instruction.
21344 // Without this, we would add a PHI between the two jumps, which ends up
21345 // creating a few copies all around. For instance, for
21347 // (sitofp (zext (fcmp une)))
21349 // we would generate:
21351 // ucomiss %xmm1, %xmm0
21352 // movss <1.0f>, %xmm0
21353 // movaps %xmm0, %xmm1
21355 // xorps %xmm1, %xmm1
21358 // movaps %xmm1, %xmm0
21362 // because this custom-inserter would have generated:
21374 // A: X = ...; Y = ...
21376 // C: Z = PHI [X, A], [Y, B]
21378 // E: PHI [X, C], [Z, D]
21380 // If we lower both CMOVs in a single step, we can instead generate:
21392 // A: X = ...; Y = ...
21394 // E: PHI [X, A], [X, C], [Y, D]
21396 // Which, in our sitofp/fcmp example, gives us something like:
21398 // ucomiss %xmm1, %xmm0
21399 // movss <1.0f>, %xmm0
21402 // xorps %xmm0, %xmm0
21406 MachineInstr *CascadedCMOV = nullptr;
21407 MachineInstr *LastCMOV = MI;
21408 X86::CondCode CC = X86::CondCode(MI->getOperand(3).getImm());
21409 X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
21410 MachineBasicBlock::iterator NextMIIt =
21411 std::next(MachineBasicBlock::iterator(MI));
21413 // Check for case 1, where there are multiple CMOVs with the same condition
21414 // first. Of the two cases of multiple CMOV lowerings, case 1 reduces the
21415 // number of jumps the most.
21417 if (isCMOVPseudo(MI)) {
21418 // See if we have a string of CMOVS with the same condition.
21419 while (NextMIIt != BB->end() &&
21420 isCMOVPseudo(NextMIIt) &&
21421 (NextMIIt->getOperand(3).getImm() == CC ||
21422 NextMIIt->getOperand(3).getImm() == OppCC)) {
21423 LastCMOV = &*NextMIIt;
21428 // This checks for case 2, but only do this if we didn't already find
21429 // case 1, as indicated by LastCMOV == MI.
21430 if (LastCMOV == MI &&
21431 NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
21432 NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
21433 NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg()) {
21434 CascadedCMOV = &*NextMIIt;
21437 MachineBasicBlock *jcc1MBB = nullptr;
21439 // If we have a cascaded CMOV, we lower it to two successive branches to
21440 // the same block. EFLAGS is used by both, so mark it as live in the second.
21441 if (CascadedCMOV) {
21442 jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
21443 F->insert(It, jcc1MBB);
21444 jcc1MBB->addLiveIn(X86::EFLAGS);
21447 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
21448 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
21449 F->insert(It, copy0MBB);
21450 F->insert(It, sinkMBB);
21452 // If the EFLAGS register isn't dead in the terminator, then claim that it's
21453 // live into the sink and copy blocks.
21454 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
21456 MachineInstr *LastEFLAGSUser = CascadedCMOV ? CascadedCMOV : LastCMOV;
21457 if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
21458 !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
21459 copy0MBB->addLiveIn(X86::EFLAGS);
21460 sinkMBB->addLiveIn(X86::EFLAGS);
21463 // Transfer the remainder of BB and its successor edges to sinkMBB.
21464 sinkMBB->splice(sinkMBB->begin(), BB,
21465 std::next(MachineBasicBlock::iterator(LastCMOV)), BB->end());
21466 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
21468 // Add the true and fallthrough blocks as its successors.
21469 if (CascadedCMOV) {
21470 // The fallthrough block may be jcc1MBB, if we have a cascaded CMOV.
21471 BB->addSuccessor(jcc1MBB);
21473 // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
21474 // jump to the sinkMBB.
21475 jcc1MBB->addSuccessor(copy0MBB);
21476 jcc1MBB->addSuccessor(sinkMBB);
21478 BB->addSuccessor(copy0MBB);
21481 // The true block target of the first (or only) branch is always sinkMBB.
21482 BB->addSuccessor(sinkMBB);
21484 // Create the conditional branch instruction.
21485 unsigned Opc = X86::GetCondBranchFromCond(CC);
21486 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
21488 if (CascadedCMOV) {
21489 unsigned Opc2 = X86::GetCondBranchFromCond(
21490 (X86::CondCode)CascadedCMOV->getOperand(3).getImm());
21491 BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
21495 // %FalseValue = ...
21496 // # fallthrough to sinkMBB
21497 copy0MBB->addSuccessor(sinkMBB);
21500 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
21502 MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
21503 MachineBasicBlock::iterator MIItEnd =
21504 std::next(MachineBasicBlock::iterator(LastCMOV));
21505 MachineBasicBlock::iterator SinkInsertionPoint = sinkMBB->begin();
21506 DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
21507 MachineInstrBuilder MIB;
21509 // As we are creating the PHIs, we have to be careful if there is more than
21510 // one. Later CMOVs may reference the results of earlier CMOVs, but later
21511 // PHIs have to reference the individual true/false inputs from earlier PHIs.
21512 // That also means that PHI construction must work forward from earlier to
21513 // later, and that the code must maintain a mapping from earlier PHI's
21514 // destination registers, and the registers that went into the PHI.
21516 for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
21517 unsigned DestReg = MIIt->getOperand(0).getReg();
21518 unsigned Op1Reg = MIIt->getOperand(1).getReg();
21519 unsigned Op2Reg = MIIt->getOperand(2).getReg();
21521 // If this CMOV we are generating is the opposite condition from
21522 // the jump we generated, then we have to swap the operands for the
21523 // PHI that is going to be generated.
21524 if (MIIt->getOperand(3).getImm() == OppCC)
21525 std::swap(Op1Reg, Op2Reg);
21527 if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
21528 Op1Reg = RegRewriteTable[Op1Reg].first;
21530 if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
21531 Op2Reg = RegRewriteTable[Op2Reg].second;
21533 MIB = BuildMI(*sinkMBB, SinkInsertionPoint, DL,
21534 TII->get(X86::PHI), DestReg)
21535 .addReg(Op1Reg).addMBB(copy0MBB)
21536 .addReg(Op2Reg).addMBB(thisMBB);
21538 // Add this PHI to the rewrite table.
21539 RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
21542 // If we have a cascaded CMOV, the second Jcc provides the same incoming
21543 // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
21544 if (CascadedCMOV) {
21545 MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
21546 // Copy the PHI result to the register defined by the second CMOV.
21547 BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
21548 DL, TII->get(TargetOpcode::COPY),
21549 CascadedCMOV->getOperand(0).getReg())
21550 .addReg(MI->getOperand(0).getReg());
21551 CascadedCMOV->eraseFromParent();
21554 // Now remove the CMOV(s).
21555 for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; )
21556 (MIIt++)->eraseFromParent();
21561 MachineBasicBlock *
21562 X86TargetLowering::EmitLoweredAtomicFP(MachineInstr *MI,
21563 MachineBasicBlock *BB) const {
21564 // Combine the following atomic floating-point modification pattern:
21565 // a.store(reg OP a.load(acquire), release)
21566 // Transform them into:
21567 // OPss (%gpr), %xmm
21568 // movss %xmm, (%gpr)
21569 // Or sd equivalent for 64-bit operations.
21571 switch (MI->getOpcode()) {
21572 default: llvm_unreachable("unexpected instr type for EmitLoweredAtomicFP");
21573 case X86::RELEASE_FADD32mr: MOp = X86::MOVSSmr; FOp = X86::ADDSSrm; break;
21574 case X86::RELEASE_FADD64mr: MOp = X86::MOVSDmr; FOp = X86::ADDSDrm; break;
21576 const X86InstrInfo *TII = Subtarget->getInstrInfo();
21577 DebugLoc DL = MI->getDebugLoc();
21578 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
21579 MachineOperand MSrc = MI->getOperand(0);
21580 unsigned VSrc = MI->getOperand(5).getReg();
21581 const MachineOperand &Disp = MI->getOperand(3);
21582 MachineOperand ZeroDisp = MachineOperand::CreateImm(0);
21583 bool hasDisp = Disp.isGlobal() || Disp.isImm();
21584 if (hasDisp && MSrc.isReg())
21585 MSrc.setIsKill(false);
21586 MachineInstrBuilder MIM = BuildMI(*BB, MI, DL, TII->get(MOp))
21587 .addOperand(/*Base=*/MSrc)
21588 .addImm(/*Scale=*/1)
21589 .addReg(/*Index=*/0)
21590 .addDisp(hasDisp ? Disp : ZeroDisp, /*off=*/0)
21592 MachineInstr *MIO = BuildMI(*BB, (MachineInstr *)MIM, DL, TII->get(FOp),
21593 MRI.createVirtualRegister(MRI.getRegClass(VSrc)))
21595 .addOperand(/*Base=*/MSrc)
21596 .addImm(/*Scale=*/1)
21597 .addReg(/*Index=*/0)
21598 .addDisp(hasDisp ? Disp : ZeroDisp, /*off=*/0)
21599 .addReg(/*Segment=*/0);
21600 MIM.addReg(MIO->getOperand(0).getReg(), RegState::Kill);
21601 MI->eraseFromParent(); // The pseudo instruction is gone now.
21605 MachineBasicBlock *
21606 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
21607 MachineBasicBlock *BB) const {
21608 MachineFunction *MF = BB->getParent();
21609 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21610 DebugLoc DL = MI->getDebugLoc();
21611 const BasicBlock *LLVM_BB = BB->getBasicBlock();
21613 assert(MF->shouldSplitStack());
21615 const bool Is64Bit = Subtarget->is64Bit();
21616 const bool IsLP64 = Subtarget->isTarget64BitLP64();
21618 const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
21619 const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
21622 // ... [Till the alloca]
21623 // If stacklet is not large enough, jump to mallocMBB
21626 // Allocate by subtracting from RSP
21627 // Jump to continueMBB
21630 // Allocate by call to runtime
21634 // [rest of original BB]
21637 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21638 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21639 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
21641 MachineRegisterInfo &MRI = MF->getRegInfo();
21642 const TargetRegisterClass *AddrRegClass =
21643 getRegClassFor(getPointerTy(MF->getDataLayout()));
21645 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
21646 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
21647 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
21648 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
21649 sizeVReg = MI->getOperand(1).getReg(),
21650 physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
21652 MachineFunction::iterator MBBIter = ++BB->getIterator();
21654 MF->insert(MBBIter, bumpMBB);
21655 MF->insert(MBBIter, mallocMBB);
21656 MF->insert(MBBIter, continueMBB);
21658 continueMBB->splice(continueMBB->begin(), BB,
21659 std::next(MachineBasicBlock::iterator(MI)), BB->end());
21660 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
21662 // Add code to the main basic block to check if the stack limit has been hit,
21663 // and if so, jump to mallocMBB otherwise to bumpMBB.
21664 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
21665 BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
21666 .addReg(tmpSPVReg).addReg(sizeVReg);
21667 BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
21668 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
21669 .addReg(SPLimitVReg);
21670 BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
21672 // bumpMBB simply decreases the stack pointer, since we know the current
21673 // stacklet has enough space.
21674 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
21675 .addReg(SPLimitVReg);
21676 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
21677 .addReg(SPLimitVReg);
21678 BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
21680 // Calls into a routine in libgcc to allocate more space from the heap.
21681 const uint32_t *RegMask =
21682 Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
21684 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
21686 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
21687 .addExternalSymbol("__morestack_allocate_stack_space")
21688 .addRegMask(RegMask)
21689 .addReg(X86::RDI, RegState::Implicit)
21690 .addReg(X86::RAX, RegState::ImplicitDefine);
21691 } else if (Is64Bit) {
21692 BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
21694 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
21695 .addExternalSymbol("__morestack_allocate_stack_space")
21696 .addRegMask(RegMask)
21697 .addReg(X86::EDI, RegState::Implicit)
21698 .addReg(X86::EAX, RegState::ImplicitDefine);
21700 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
21702 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
21703 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
21704 .addExternalSymbol("__morestack_allocate_stack_space")
21705 .addRegMask(RegMask)
21706 .addReg(X86::EAX, RegState::ImplicitDefine);
21710 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
21713 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
21714 .addReg(IsLP64 ? X86::RAX : X86::EAX);
21715 BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
21717 // Set up the CFG correctly.
21718 BB->addSuccessor(bumpMBB);
21719 BB->addSuccessor(mallocMBB);
21720 mallocMBB->addSuccessor(continueMBB);
21721 bumpMBB->addSuccessor(continueMBB);
21723 // Take care of the PHI nodes.
21724 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
21725 MI->getOperand(0).getReg())
21726 .addReg(mallocPtrVReg).addMBB(mallocMBB)
21727 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
21729 // Delete the original pseudo instruction.
21730 MI->eraseFromParent();
21733 return continueMBB;
21736 MachineBasicBlock *
21737 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
21738 MachineBasicBlock *BB) const {
21739 assert(!Subtarget->isTargetMachO());
21740 DebugLoc DL = MI->getDebugLoc();
21741 MachineInstr *ResumeMI = Subtarget->getFrameLowering()->emitStackProbe(
21742 *BB->getParent(), *BB, MI, DL, false);
21743 MachineBasicBlock *ResumeBB = ResumeMI->getParent();
21744 MI->eraseFromParent(); // The pseudo instruction is gone now.
21748 MachineBasicBlock *
21749 X86TargetLowering::EmitLoweredCatchRet(MachineInstr *MI,
21750 MachineBasicBlock *BB) const {
21751 MachineFunction *MF = BB->getParent();
21752 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
21753 MachineBasicBlock *TargetMBB = MI->getOperand(0).getMBB();
21754 DebugLoc DL = MI->getDebugLoc();
21756 assert(!isAsynchronousEHPersonality(
21757 classifyEHPersonality(MF->getFunction()->getPersonalityFn())) &&
21758 "SEH does not use catchret!");
21760 // Only 32-bit EH needs to worry about manually restoring stack pointers.
21761 if (!Subtarget->is32Bit())
21764 // C++ EH creates a new target block to hold the restore code, and wires up
21765 // the new block to the return destination with a normal JMP_4.
21766 MachineBasicBlock *RestoreMBB =
21767 MF->CreateMachineBasicBlock(BB->getBasicBlock());
21768 assert(BB->succ_size() == 1);
21769 MF->insert(std::next(BB->getIterator()), RestoreMBB);
21770 RestoreMBB->transferSuccessorsAndUpdatePHIs(BB);
21771 BB->addSuccessor(RestoreMBB);
21772 MI->getOperand(0).setMBB(RestoreMBB);
21774 auto RestoreMBBI = RestoreMBB->begin();
21775 BuildMI(*RestoreMBB, RestoreMBBI, DL, TII.get(X86::EH_RESTORE));
21776 BuildMI(*RestoreMBB, RestoreMBBI, DL, TII.get(X86::JMP_4)).addMBB(TargetMBB);
21780 MachineBasicBlock *
21781 X86TargetLowering::EmitLoweredCatchPad(MachineInstr *MI,
21782 MachineBasicBlock *BB) const {
21783 MachineFunction *MF = BB->getParent();
21784 const Constant *PerFn = MF->getFunction()->getPersonalityFn();
21785 bool IsSEH = isAsynchronousEHPersonality(classifyEHPersonality(PerFn));
21786 // Only 32-bit SEH requires special handling for catchpad.
21787 if (IsSEH && Subtarget->is32Bit()) {
21788 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
21789 DebugLoc DL = MI->getDebugLoc();
21790 BuildMI(*BB, MI, DL, TII.get(X86::EH_RESTORE));
21792 MI->eraseFromParent();
21796 MachineBasicBlock *
21797 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
21798 MachineBasicBlock *BB) const {
21799 // This is pretty easy. We're taking the value that we received from
21800 // our load from the relocation, sticking it in either RDI (x86-64)
21801 // or EAX and doing an indirect call. The return value will then
21802 // be in the normal return register.
21803 MachineFunction *F = BB->getParent();
21804 const X86InstrInfo *TII = Subtarget->getInstrInfo();
21805 DebugLoc DL = MI->getDebugLoc();
21807 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
21808 assert(MI->getOperand(3).isGlobal() && "This should be a global");
21810 // Get a register mask for the lowered call.
21811 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
21812 // proper register mask.
21813 const uint32_t *RegMask =
21814 Subtarget->is64Bit() ?
21815 Subtarget->getRegisterInfo()->getDarwinTLSCallPreservedMask() :
21816 Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
21817 if (Subtarget->is64Bit()) {
21818 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21819 TII->get(X86::MOV64rm), X86::RDI)
21821 .addImm(0).addReg(0)
21822 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21823 MI->getOperand(3).getTargetFlags())
21825 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
21826 addDirectMem(MIB, X86::RDI);
21827 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
21828 } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
21829 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21830 TII->get(X86::MOV32rm), X86::EAX)
21832 .addImm(0).addReg(0)
21833 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21834 MI->getOperand(3).getTargetFlags())
21836 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
21837 addDirectMem(MIB, X86::EAX);
21838 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
21840 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
21841 TII->get(X86::MOV32rm), X86::EAX)
21842 .addReg(TII->getGlobalBaseReg(F))
21843 .addImm(0).addReg(0)
21844 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
21845 MI->getOperand(3).getTargetFlags())
21847 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
21848 addDirectMem(MIB, X86::EAX);
21849 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
21852 MI->eraseFromParent(); // The pseudo instruction is gone now.
21856 MachineBasicBlock *
21857 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
21858 MachineBasicBlock *MBB) const {
21859 DebugLoc DL = MI->getDebugLoc();
21860 MachineFunction *MF = MBB->getParent();
21861 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
21862 MachineRegisterInfo &MRI = MF->getRegInfo();
21864 const BasicBlock *BB = MBB->getBasicBlock();
21865 MachineFunction::iterator I = ++MBB->getIterator();
21867 // Memory Reference
21868 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
21869 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
21872 unsigned MemOpndSlot = 0;
21874 unsigned CurOp = 0;
21876 DstReg = MI->getOperand(CurOp++).getReg();
21877 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
21878 assert(RC->hasType(MVT::i32) && "Invalid destination!");
21879 unsigned mainDstReg = MRI.createVirtualRegister(RC);
21880 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
21882 MemOpndSlot = CurOp;
21884 MVT PVT = getPointerTy(MF->getDataLayout());
21885 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
21886 "Invalid Pointer Size!");
21888 // For v = setjmp(buf), we generate
21891 // buf[LabelOffset] = restoreMBB <-- takes address of restoreMBB
21892 // SjLjSetup restoreMBB
21898 // v = phi(main, restore)
21901 // if base pointer being used, load it from frame
21904 MachineBasicBlock *thisMBB = MBB;
21905 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
21906 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
21907 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
21908 MF->insert(I, mainMBB);
21909 MF->insert(I, sinkMBB);
21910 MF->push_back(restoreMBB);
21911 restoreMBB->setHasAddressTaken();
21913 MachineInstrBuilder MIB;
21915 // Transfer the remainder of BB and its successor edges to sinkMBB.
21916 sinkMBB->splice(sinkMBB->begin(), MBB,
21917 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
21918 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
21921 unsigned PtrStoreOpc = 0;
21922 unsigned LabelReg = 0;
21923 const int64_t LabelOffset = 1 * PVT.getStoreSize();
21924 Reloc::Model RM = MF->getTarget().getRelocationModel();
21925 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
21926 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
21928 // Prepare IP either in reg or imm.
21929 if (!UseImmLabel) {
21930 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
21931 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
21932 LabelReg = MRI.createVirtualRegister(PtrRC);
21933 if (Subtarget->is64Bit()) {
21934 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
21938 .addMBB(restoreMBB)
21941 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
21942 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
21943 .addReg(XII->getGlobalBaseReg(MF))
21946 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
21950 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
21952 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
21953 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
21954 if (i == X86::AddrDisp)
21955 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
21957 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
21960 MIB.addReg(LabelReg);
21962 MIB.addMBB(restoreMBB);
21963 MIB.setMemRefs(MMOBegin, MMOEnd);
21965 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
21966 .addMBB(restoreMBB);
21968 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
21969 MIB.addRegMask(RegInfo->getNoPreservedMask());
21970 thisMBB->addSuccessor(mainMBB);
21971 thisMBB->addSuccessor(restoreMBB);
21975 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
21976 mainMBB->addSuccessor(sinkMBB);
21979 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
21980 TII->get(X86::PHI), DstReg)
21981 .addReg(mainDstReg).addMBB(mainMBB)
21982 .addReg(restoreDstReg).addMBB(restoreMBB);
21985 if (RegInfo->hasBasePointer(*MF)) {
21986 const bool Uses64BitFramePtr =
21987 Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
21988 X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
21989 X86FI->setRestoreBasePointer(MF);
21990 unsigned FramePtr = RegInfo->getFrameRegister(*MF);
21991 unsigned BasePtr = RegInfo->getBaseRegister();
21992 unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
21993 addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
21994 FramePtr, true, X86FI->getRestoreBasePointerOffset())
21995 .setMIFlag(MachineInstr::FrameSetup);
21997 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
21998 BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
21999 restoreMBB->addSuccessor(sinkMBB);
22001 MI->eraseFromParent();
22005 MachineBasicBlock *
22006 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
22007 MachineBasicBlock *MBB) const {
22008 DebugLoc DL = MI->getDebugLoc();
22009 MachineFunction *MF = MBB->getParent();
22010 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22011 MachineRegisterInfo &MRI = MF->getRegInfo();
22013 // Memory Reference
22014 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
22015 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
22017 MVT PVT = getPointerTy(MF->getDataLayout());
22018 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
22019 "Invalid Pointer Size!");
22021 const TargetRegisterClass *RC =
22022 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
22023 unsigned Tmp = MRI.createVirtualRegister(RC);
22024 // Since FP is only updated here but NOT referenced, it's treated as GPR.
22025 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
22026 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
22027 unsigned SP = RegInfo->getStackRegister();
22029 MachineInstrBuilder MIB;
22031 const int64_t LabelOffset = 1 * PVT.getStoreSize();
22032 const int64_t SPOffset = 2 * PVT.getStoreSize();
22034 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
22035 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
22038 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
22039 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
22040 MIB.addOperand(MI->getOperand(i));
22041 MIB.setMemRefs(MMOBegin, MMOEnd);
22043 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
22044 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
22045 if (i == X86::AddrDisp)
22046 MIB.addDisp(MI->getOperand(i), LabelOffset);
22048 MIB.addOperand(MI->getOperand(i));
22050 MIB.setMemRefs(MMOBegin, MMOEnd);
22052 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
22053 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
22054 if (i == X86::AddrDisp)
22055 MIB.addDisp(MI->getOperand(i), SPOffset);
22057 MIB.addOperand(MI->getOperand(i));
22059 MIB.setMemRefs(MMOBegin, MMOEnd);
22061 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
22063 MI->eraseFromParent();
22067 // Replace 213-type (isel default) FMA3 instructions with 231-type for
22068 // accumulator loops. Writing back to the accumulator allows the coalescer
22069 // to remove extra copies in the loop.
22070 // FIXME: Do this on AVX512. We don't support 231 variants yet (PR23937).
22071 MachineBasicBlock *
22072 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
22073 MachineBasicBlock *MBB) const {
22074 MachineOperand &AddendOp = MI->getOperand(3);
22076 // Bail out early if the addend isn't a register - we can't switch these.
22077 if (!AddendOp.isReg())
22080 MachineFunction &MF = *MBB->getParent();
22081 MachineRegisterInfo &MRI = MF.getRegInfo();
22083 // Check whether the addend is defined by a PHI:
22084 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
22085 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
22086 if (!AddendDef.isPHI())
22089 // Look for the following pattern:
22091 // %addend = phi [%entry, 0], [%loop, %result]
22093 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
22097 // %addend = phi [%entry, 0], [%loop, %result]
22099 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
22101 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
22102 assert(AddendDef.getOperand(i).isReg());
22103 MachineOperand PHISrcOp = AddendDef.getOperand(i);
22104 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
22105 if (&PHISrcInst == MI) {
22106 // Found a matching instruction.
22107 unsigned NewFMAOpc = 0;
22108 switch (MI->getOpcode()) {
22109 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
22110 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
22111 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
22112 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
22113 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
22114 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
22115 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
22116 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
22117 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
22118 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
22119 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
22120 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
22121 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
22122 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
22123 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
22124 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
22125 case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
22126 case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
22127 case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
22128 case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
22130 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
22131 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
22132 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
22133 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
22134 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
22135 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
22136 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
22137 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
22138 case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
22139 case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
22140 case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
22141 case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
22142 default: llvm_unreachable("Unrecognized FMA variant.");
22145 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
22146 MachineInstrBuilder MIB =
22147 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
22148 .addOperand(MI->getOperand(0))
22149 .addOperand(MI->getOperand(3))
22150 .addOperand(MI->getOperand(2))
22151 .addOperand(MI->getOperand(1));
22152 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
22153 MI->eraseFromParent();
22160 MachineBasicBlock *
22161 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
22162 MachineBasicBlock *BB) const {
22163 switch (MI->getOpcode()) {
22164 default: llvm_unreachable("Unexpected instr type to insert");
22165 case X86::TAILJMPd64:
22166 case X86::TAILJMPr64:
22167 case X86::TAILJMPm64:
22168 case X86::TAILJMPd64_REX:
22169 case X86::TAILJMPr64_REX:
22170 case X86::TAILJMPm64_REX:
22171 llvm_unreachable("TAILJMP64 would not be touched here.");
22172 case X86::TCRETURNdi64:
22173 case X86::TCRETURNri64:
22174 case X86::TCRETURNmi64:
22176 case X86::WIN_ALLOCA:
22177 return EmitLoweredWinAlloca(MI, BB);
22178 case X86::CATCHRET:
22179 return EmitLoweredCatchRet(MI, BB);
22180 case X86::CATCHPAD:
22181 return EmitLoweredCatchPad(MI, BB);
22182 case X86::SEG_ALLOCA_32:
22183 case X86::SEG_ALLOCA_64:
22184 return EmitLoweredSegAlloca(MI, BB);
22185 case X86::TLSCall_32:
22186 case X86::TLSCall_64:
22187 return EmitLoweredTLSCall(MI, BB);
22188 case X86::CMOV_FR32:
22189 case X86::CMOV_FR64:
22190 case X86::CMOV_FR128:
22191 case X86::CMOV_GR8:
22192 case X86::CMOV_GR16:
22193 case X86::CMOV_GR32:
22194 case X86::CMOV_RFP32:
22195 case X86::CMOV_RFP64:
22196 case X86::CMOV_RFP80:
22197 case X86::CMOV_V2F64:
22198 case X86::CMOV_V2I64:
22199 case X86::CMOV_V4F32:
22200 case X86::CMOV_V4F64:
22201 case X86::CMOV_V4I64:
22202 case X86::CMOV_V16F32:
22203 case X86::CMOV_V8F32:
22204 case X86::CMOV_V8F64:
22205 case X86::CMOV_V8I64:
22206 case X86::CMOV_V8I1:
22207 case X86::CMOV_V16I1:
22208 case X86::CMOV_V32I1:
22209 case X86::CMOV_V64I1:
22210 return EmitLoweredSelect(MI, BB);
22212 case X86::RELEASE_FADD32mr:
22213 case X86::RELEASE_FADD64mr:
22214 return EmitLoweredAtomicFP(MI, BB);
22216 case X86::FP32_TO_INT16_IN_MEM:
22217 case X86::FP32_TO_INT32_IN_MEM:
22218 case X86::FP32_TO_INT64_IN_MEM:
22219 case X86::FP64_TO_INT16_IN_MEM:
22220 case X86::FP64_TO_INT32_IN_MEM:
22221 case X86::FP64_TO_INT64_IN_MEM:
22222 case X86::FP80_TO_INT16_IN_MEM:
22223 case X86::FP80_TO_INT32_IN_MEM:
22224 case X86::FP80_TO_INT64_IN_MEM: {
22225 MachineFunction *F = BB->getParent();
22226 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
22227 DebugLoc DL = MI->getDebugLoc();
22229 // Change the floating point control register to use "round towards zero"
22230 // mode when truncating to an integer value.
22231 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
22232 addFrameReference(BuildMI(*BB, MI, DL,
22233 TII->get(X86::FNSTCW16m)), CWFrameIdx);
22235 // Load the old value of the high byte of the control word...
22237 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
22238 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
22241 // Set the high part to be round to zero...
22242 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
22245 // Reload the modified control word now...
22246 addFrameReference(BuildMI(*BB, MI, DL,
22247 TII->get(X86::FLDCW16m)), CWFrameIdx);
22249 // Restore the memory image of control word to original value
22250 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
22253 // Get the X86 opcode to use.
22255 switch (MI->getOpcode()) {
22256 default: llvm_unreachable("illegal opcode!");
22257 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
22258 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
22259 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
22260 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
22261 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
22262 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
22263 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
22264 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
22265 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
22269 MachineOperand &Op = MI->getOperand(0);
22271 AM.BaseType = X86AddressMode::RegBase;
22272 AM.Base.Reg = Op.getReg();
22274 AM.BaseType = X86AddressMode::FrameIndexBase;
22275 AM.Base.FrameIndex = Op.getIndex();
22277 Op = MI->getOperand(1);
22279 AM.Scale = Op.getImm();
22280 Op = MI->getOperand(2);
22282 AM.IndexReg = Op.getImm();
22283 Op = MI->getOperand(3);
22284 if (Op.isGlobal()) {
22285 AM.GV = Op.getGlobal();
22287 AM.Disp = Op.getImm();
22289 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
22290 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
22292 // Reload the original control word now.
22293 addFrameReference(BuildMI(*BB, MI, DL,
22294 TII->get(X86::FLDCW16m)), CWFrameIdx);
22296 MI->eraseFromParent(); // The pseudo instruction is gone now.
22299 // String/text processing lowering.
22300 case X86::PCMPISTRM128REG:
22301 case X86::VPCMPISTRM128REG:
22302 case X86::PCMPISTRM128MEM:
22303 case X86::VPCMPISTRM128MEM:
22304 case X86::PCMPESTRM128REG:
22305 case X86::VPCMPESTRM128REG:
22306 case X86::PCMPESTRM128MEM:
22307 case X86::VPCMPESTRM128MEM:
22308 assert(Subtarget->hasSSE42() &&
22309 "Target must have SSE4.2 or AVX features enabled");
22310 return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
22312 // String/text processing lowering.
22313 case X86::PCMPISTRIREG:
22314 case X86::VPCMPISTRIREG:
22315 case X86::PCMPISTRIMEM:
22316 case X86::VPCMPISTRIMEM:
22317 case X86::PCMPESTRIREG:
22318 case X86::VPCMPESTRIREG:
22319 case X86::PCMPESTRIMEM:
22320 case X86::VPCMPESTRIMEM:
22321 assert(Subtarget->hasSSE42() &&
22322 "Target must have SSE4.2 or AVX features enabled");
22323 return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
22325 // Thread synchronization.
22327 return EmitMonitor(MI, BB, Subtarget);
22331 return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
22333 case X86::VASTART_SAVE_XMM_REGS:
22334 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
22336 case X86::VAARG_64:
22337 return EmitVAARG64WithCustomInserter(MI, BB);
22339 case X86::EH_SjLj_SetJmp32:
22340 case X86::EH_SjLj_SetJmp64:
22341 return emitEHSjLjSetJmp(MI, BB);
22343 case X86::EH_SjLj_LongJmp32:
22344 case X86::EH_SjLj_LongJmp64:
22345 return emitEHSjLjLongJmp(MI, BB);
22347 case TargetOpcode::STATEPOINT:
22348 // As an implementation detail, STATEPOINT shares the STACKMAP format at
22349 // this point in the process. We diverge later.
22350 return emitPatchPoint(MI, BB);
22352 case TargetOpcode::STACKMAP:
22353 case TargetOpcode::PATCHPOINT:
22354 return emitPatchPoint(MI, BB);
22356 case X86::VFMADDPDr213r:
22357 case X86::VFMADDPSr213r:
22358 case X86::VFMADDSDr213r:
22359 case X86::VFMADDSSr213r:
22360 case X86::VFMSUBPDr213r:
22361 case X86::VFMSUBPSr213r:
22362 case X86::VFMSUBSDr213r:
22363 case X86::VFMSUBSSr213r:
22364 case X86::VFNMADDPDr213r:
22365 case X86::VFNMADDPSr213r:
22366 case X86::VFNMADDSDr213r:
22367 case X86::VFNMADDSSr213r:
22368 case X86::VFNMSUBPDr213r:
22369 case X86::VFNMSUBPSr213r:
22370 case X86::VFNMSUBSDr213r:
22371 case X86::VFNMSUBSSr213r:
22372 case X86::VFMADDSUBPDr213r:
22373 case X86::VFMADDSUBPSr213r:
22374 case X86::VFMSUBADDPDr213r:
22375 case X86::VFMSUBADDPSr213r:
22376 case X86::VFMADDPDr213rY:
22377 case X86::VFMADDPSr213rY:
22378 case X86::VFMSUBPDr213rY:
22379 case X86::VFMSUBPSr213rY:
22380 case X86::VFNMADDPDr213rY:
22381 case X86::VFNMADDPSr213rY:
22382 case X86::VFNMSUBPDr213rY:
22383 case X86::VFNMSUBPSr213rY:
22384 case X86::VFMADDSUBPDr213rY:
22385 case X86::VFMADDSUBPSr213rY:
22386 case X86::VFMSUBADDPDr213rY:
22387 case X86::VFMSUBADDPSr213rY:
22388 return emitFMA3Instr(MI, BB);
22392 //===----------------------------------------------------------------------===//
22393 // X86 Optimization Hooks
22394 //===----------------------------------------------------------------------===//
22396 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
22399 const SelectionDAG &DAG,
22400 unsigned Depth) const {
22401 unsigned BitWidth = KnownZero.getBitWidth();
22402 unsigned Opc = Op.getOpcode();
22403 assert((Opc >= ISD::BUILTIN_OP_END ||
22404 Opc == ISD::INTRINSIC_WO_CHAIN ||
22405 Opc == ISD::INTRINSIC_W_CHAIN ||
22406 Opc == ISD::INTRINSIC_VOID) &&
22407 "Should use MaskedValueIsZero if you don't know whether Op"
22408 " is a target node!");
22410 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
22424 // These nodes' second result is a boolean.
22425 if (Op.getResNo() == 0)
22428 case X86ISD::SETCC:
22429 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
22431 case ISD::INTRINSIC_WO_CHAIN: {
22432 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
22433 unsigned NumLoBits = 0;
22436 case Intrinsic::x86_sse_movmsk_ps:
22437 case Intrinsic::x86_avx_movmsk_ps_256:
22438 case Intrinsic::x86_sse2_movmsk_pd:
22439 case Intrinsic::x86_avx_movmsk_pd_256:
22440 case Intrinsic::x86_mmx_pmovmskb:
22441 case Intrinsic::x86_sse2_pmovmskb_128:
22442 case Intrinsic::x86_avx2_pmovmskb: {
22443 // High bits of movmskp{s|d}, pmovmskb are known zero.
22445 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
22446 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
22447 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
22448 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
22449 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
22450 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
22451 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
22452 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
22454 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
22463 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
22465 const SelectionDAG &,
22466 unsigned Depth) const {
22467 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
22468 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
22469 return Op.getValueType().getScalarSizeInBits();
22475 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
22476 /// node is a GlobalAddress + offset.
22477 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
22478 const GlobalValue* &GA,
22479 int64_t &Offset) const {
22480 if (N->getOpcode() == X86ISD::Wrapper) {
22481 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
22482 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
22483 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
22487 return TargetLowering::isGAPlusOffset(N, GA, Offset);
22490 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
22491 /// same as extracting the high 128-bit part of 256-bit vector and then
22492 /// inserting the result into the low part of a new 256-bit vector
22493 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
22494 EVT VT = SVOp->getValueType(0);
22495 unsigned NumElems = VT.getVectorNumElements();
22497 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
22498 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
22499 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
22500 SVOp->getMaskElt(j) >= 0)
22506 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
22507 /// same as extracting the low 128-bit part of 256-bit vector and then
22508 /// inserting the result into the high part of a new 256-bit vector
22509 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
22510 EVT VT = SVOp->getValueType(0);
22511 unsigned NumElems = VT.getVectorNumElements();
22513 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
22514 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
22515 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
22516 SVOp->getMaskElt(j) >= 0)
22522 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
22523 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
22524 TargetLowering::DAGCombinerInfo &DCI,
22525 const X86Subtarget* Subtarget) {
22527 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22528 SDValue V1 = SVOp->getOperand(0);
22529 SDValue V2 = SVOp->getOperand(1);
22530 MVT VT = SVOp->getSimpleValueType(0);
22531 unsigned NumElems = VT.getVectorNumElements();
22533 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
22534 V2.getOpcode() == ISD::CONCAT_VECTORS) {
22538 // V UNDEF BUILD_VECTOR UNDEF
22540 // CONCAT_VECTOR CONCAT_VECTOR
22543 // RESULT: V + zero extended
22545 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
22546 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
22547 V1.getOperand(1).getOpcode() != ISD::UNDEF)
22550 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
22553 // To match the shuffle mask, the first half of the mask should
22554 // be exactly the first vector, and all the rest a splat with the
22555 // first element of the second one.
22556 for (unsigned i = 0; i != NumElems/2; ++i)
22557 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
22558 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
22561 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
22562 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
22563 if (Ld->hasNUsesOfValue(1, 0)) {
22564 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
22565 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
22567 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
22569 Ld->getPointerInfo(),
22570 Ld->getAlignment(),
22571 false/*isVolatile*/, true/*ReadMem*/,
22572 false/*WriteMem*/);
22574 // Make sure the newly-created LOAD is in the same position as Ld in
22575 // terms of dependency. We create a TokenFactor for Ld and ResNode,
22576 // and update uses of Ld's output chain to use the TokenFactor.
22577 if (Ld->hasAnyUseOfValue(1)) {
22578 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
22579 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
22580 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
22581 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
22582 SDValue(ResNode.getNode(), 1));
22585 return DAG.getBitcast(VT, ResNode);
22589 // Emit a zeroed vector and insert the desired subvector on its
22591 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
22592 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
22593 return DCI.CombineTo(N, InsV);
22596 //===--------------------------------------------------------------------===//
22597 // Combine some shuffles into subvector extracts and inserts:
22600 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
22601 if (isShuffleHigh128VectorInsertLow(SVOp)) {
22602 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
22603 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
22604 return DCI.CombineTo(N, InsV);
22607 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
22608 if (isShuffleLow128VectorInsertHigh(SVOp)) {
22609 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
22610 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
22611 return DCI.CombineTo(N, InsV);
22617 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
22620 /// This is the leaf of the recursive combinine below. When we have found some
22621 /// chain of single-use x86 shuffle instructions and accumulated the combined
22622 /// shuffle mask represented by them, this will try to pattern match that mask
22623 /// into either a single instruction if there is a special purpose instruction
22624 /// for this operation, or into a PSHUFB instruction which is a fully general
22625 /// instruction but should only be used to replace chains over a certain depth.
22626 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
22627 int Depth, bool HasPSHUFB, SelectionDAG &DAG,
22628 TargetLowering::DAGCombinerInfo &DCI,
22629 const X86Subtarget *Subtarget) {
22630 assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
22632 // Find the operand that enters the chain. Note that multiple uses are OK
22633 // here, we're not going to remove the operand we find.
22634 SDValue Input = Op.getOperand(0);
22635 while (Input.getOpcode() == ISD::BITCAST)
22636 Input = Input.getOperand(0);
22638 MVT VT = Input.getSimpleValueType();
22639 MVT RootVT = Root.getSimpleValueType();
22642 if (Mask.size() == 1) {
22643 int Index = Mask[0];
22644 assert((Index >= 0 || Index == SM_SentinelUndef ||
22645 Index == SM_SentinelZero) &&
22646 "Invalid shuffle index found!");
22648 // We may end up with an accumulated mask of size 1 as a result of
22649 // widening of shuffle operands (see function canWidenShuffleElements).
22650 // If the only shuffle index is equal to SM_SentinelZero then propagate
22651 // a zero vector. Otherwise, the combine shuffle mask is a no-op shuffle
22652 // mask, and therefore the entire chain of shuffles can be folded away.
22653 if (Index == SM_SentinelZero)
22654 DCI.CombineTo(Root.getNode(), getZeroVector(RootVT, Subtarget, DAG, DL));
22656 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
22661 // Use the float domain if the operand type is a floating point type.
22662 bool FloatDomain = VT.isFloatingPoint();
22664 // For floating point shuffles, we don't have free copies in the shuffle
22665 // instructions or the ability to load as part of the instruction, so
22666 // canonicalize their shuffles to UNPCK or MOV variants.
22668 // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
22669 // vectors because it can have a load folded into it that UNPCK cannot. This
22670 // doesn't preclude something switching to the shorter encoding post-RA.
22672 // FIXME: Should teach these routines about AVX vector widths.
22673 if (FloatDomain && VT.is128BitVector()) {
22674 if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
22675 bool Lo = Mask.equals({0, 0});
22678 // Check if we have SSE3 which will let us use MOVDDUP. That instruction
22679 // is no slower than UNPCKLPD but has the option to fold the input operand
22680 // into even an unaligned memory load.
22681 if (Lo && Subtarget->hasSSE3()) {
22682 Shuffle = X86ISD::MOVDDUP;
22683 ShuffleVT = MVT::v2f64;
22685 // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
22686 // than the UNPCK variants.
22687 Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
22688 ShuffleVT = MVT::v4f32;
22690 if (Depth == 1 && Root->getOpcode() == Shuffle)
22691 return false; // Nothing to do!
22692 Op = DAG.getBitcast(ShuffleVT, Input);
22693 DCI.AddToWorklist(Op.getNode());
22694 if (Shuffle == X86ISD::MOVDDUP)
22695 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
22697 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
22698 DCI.AddToWorklist(Op.getNode());
22699 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22703 if (Subtarget->hasSSE3() &&
22704 (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
22705 bool Lo = Mask.equals({0, 0, 2, 2});
22706 unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
22707 MVT ShuffleVT = MVT::v4f32;
22708 if (Depth == 1 && Root->getOpcode() == Shuffle)
22709 return false; // Nothing to do!
22710 Op = DAG.getBitcast(ShuffleVT, Input);
22711 DCI.AddToWorklist(Op.getNode());
22712 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
22713 DCI.AddToWorklist(Op.getNode());
22714 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22718 if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
22719 bool Lo = Mask.equals({0, 0, 1, 1});
22720 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
22721 MVT ShuffleVT = MVT::v4f32;
22722 if (Depth == 1 && Root->getOpcode() == Shuffle)
22723 return false; // Nothing to do!
22724 Op = DAG.getBitcast(ShuffleVT, Input);
22725 DCI.AddToWorklist(Op.getNode());
22726 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
22727 DCI.AddToWorklist(Op.getNode());
22728 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22734 // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
22735 // variants as none of these have single-instruction variants that are
22736 // superior to the UNPCK formulation.
22737 if (!FloatDomain && VT.is128BitVector() &&
22738 (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
22739 Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
22740 Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
22742 {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
22743 bool Lo = Mask[0] == 0;
22744 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
22745 if (Depth == 1 && Root->getOpcode() == Shuffle)
22746 return false; // Nothing to do!
22748 switch (Mask.size()) {
22750 ShuffleVT = MVT::v8i16;
22753 ShuffleVT = MVT::v16i8;
22756 llvm_unreachable("Impossible mask size!");
22758 Op = DAG.getBitcast(ShuffleVT, Input);
22759 DCI.AddToWorklist(Op.getNode());
22760 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
22761 DCI.AddToWorklist(Op.getNode());
22762 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22767 // Don't try to re-form single instruction chains under any circumstances now
22768 // that we've done encoding canonicalization for them.
22772 // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
22773 // can replace them with a single PSHUFB instruction profitably. Intel's
22774 // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
22775 // in practice PSHUFB tends to be *very* fast so we're more aggressive.
22776 if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
22777 SmallVector<SDValue, 16> PSHUFBMask;
22778 int NumBytes = VT.getSizeInBits() / 8;
22779 int Ratio = NumBytes / Mask.size();
22780 for (int i = 0; i < NumBytes; ++i) {
22781 if (Mask[i / Ratio] == SM_SentinelUndef) {
22782 PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
22785 int M = Mask[i / Ratio] != SM_SentinelZero
22786 ? Ratio * Mask[i / Ratio] + i % Ratio
22788 PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
22790 MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
22791 Op = DAG.getBitcast(ByteVT, Input);
22792 DCI.AddToWorklist(Op.getNode());
22793 SDValue PSHUFBMaskOp =
22794 DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
22795 DCI.AddToWorklist(PSHUFBMaskOp.getNode());
22796 Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
22797 DCI.AddToWorklist(Op.getNode());
22798 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
22803 // Failed to find any combines.
22807 /// \brief Fully generic combining of x86 shuffle instructions.
22809 /// This should be the last combine run over the x86 shuffle instructions. Once
22810 /// they have been fully optimized, this will recursively consider all chains
22811 /// of single-use shuffle instructions, build a generic model of the cumulative
22812 /// shuffle operation, and check for simpler instructions which implement this
22813 /// operation. We use this primarily for two purposes:
22815 /// 1) Collapse generic shuffles to specialized single instructions when
22816 /// equivalent. In most cases, this is just an encoding size win, but
22817 /// sometimes we will collapse multiple generic shuffles into a single
22818 /// special-purpose shuffle.
22819 /// 2) Look for sequences of shuffle instructions with 3 or more total
22820 /// instructions, and replace them with the slightly more expensive SSSE3
22821 /// PSHUFB instruction if available. We do this as the last combining step
22822 /// to ensure we avoid using PSHUFB if we can implement the shuffle with
22823 /// a suitable short sequence of other instructions. The PHUFB will either
22824 /// use a register or have to read from memory and so is slightly (but only
22825 /// slightly) more expensive than the other shuffle instructions.
22827 /// Because this is inherently a quadratic operation (for each shuffle in
22828 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
22829 /// This should never be an issue in practice as the shuffle lowering doesn't
22830 /// produce sequences of more than 8 instructions.
22832 /// FIXME: We will currently miss some cases where the redundant shuffling
22833 /// would simplify under the threshold for PSHUFB formation because of
22834 /// combine-ordering. To fix this, we should do the redundant instruction
22835 /// combining in this recursive walk.
22836 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
22837 ArrayRef<int> RootMask,
22838 int Depth, bool HasPSHUFB,
22840 TargetLowering::DAGCombinerInfo &DCI,
22841 const X86Subtarget *Subtarget) {
22842 // Bound the depth of our recursive combine because this is ultimately
22843 // quadratic in nature.
22847 // Directly rip through bitcasts to find the underlying operand.
22848 while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
22849 Op = Op.getOperand(0);
22851 MVT VT = Op.getSimpleValueType();
22852 if (!VT.isVector())
22853 return false; // Bail if we hit a non-vector.
22855 assert(Root.getSimpleValueType().isVector() &&
22856 "Shuffles operate on vector types!");
22857 assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
22858 "Can only combine shuffles of the same vector register size.");
22860 if (!isTargetShuffle(Op.getOpcode()))
22862 SmallVector<int, 16> OpMask;
22864 bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
22865 // We only can combine unary shuffles which we can decode the mask for.
22866 if (!HaveMask || !IsUnary)
22869 assert(VT.getVectorNumElements() == OpMask.size() &&
22870 "Different mask size from vector size!");
22871 assert(((RootMask.size() > OpMask.size() &&
22872 RootMask.size() % OpMask.size() == 0) ||
22873 (OpMask.size() > RootMask.size() &&
22874 OpMask.size() % RootMask.size() == 0) ||
22875 OpMask.size() == RootMask.size()) &&
22876 "The smaller number of elements must divide the larger.");
22877 int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
22878 int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
22879 assert(((RootRatio == 1 && OpRatio == 1) ||
22880 (RootRatio == 1) != (OpRatio == 1)) &&
22881 "Must not have a ratio for both incoming and op masks!");
22883 SmallVector<int, 16> Mask;
22884 Mask.reserve(std::max(OpMask.size(), RootMask.size()));
22886 // Merge this shuffle operation's mask into our accumulated mask. Note that
22887 // this shuffle's mask will be the first applied to the input, followed by the
22888 // root mask to get us all the way to the root value arrangement. The reason
22889 // for this order is that we are recursing up the operation chain.
22890 for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
22891 int RootIdx = i / RootRatio;
22892 if (RootMask[RootIdx] < 0) {
22893 // This is a zero or undef lane, we're done.
22894 Mask.push_back(RootMask[RootIdx]);
22898 int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
22899 int OpIdx = RootMaskedIdx / OpRatio;
22900 if (OpMask[OpIdx] < 0) {
22901 // The incoming lanes are zero or undef, it doesn't matter which ones we
22903 Mask.push_back(OpMask[OpIdx]);
22907 // Ok, we have non-zero lanes, map them through.
22908 Mask.push_back(OpMask[OpIdx] * OpRatio +
22909 RootMaskedIdx % OpRatio);
22912 // See if we can recurse into the operand to combine more things.
22913 switch (Op.getOpcode()) {
22914 case X86ISD::PSHUFB:
22916 case X86ISD::PSHUFD:
22917 case X86ISD::PSHUFHW:
22918 case X86ISD::PSHUFLW:
22919 if (Op.getOperand(0).hasOneUse() &&
22920 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
22921 HasPSHUFB, DAG, DCI, Subtarget))
22925 case X86ISD::UNPCKL:
22926 case X86ISD::UNPCKH:
22927 assert(Op.getOperand(0) == Op.getOperand(1) &&
22928 "We only combine unary shuffles!");
22929 // We can't check for single use, we have to check that this shuffle is the
22931 if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
22932 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
22933 HasPSHUFB, DAG, DCI, Subtarget))
22938 // Minor canonicalization of the accumulated shuffle mask to make it easier
22939 // to match below. All this does is detect masks with squential pairs of
22940 // elements, and shrink them to the half-width mask. It does this in a loop
22941 // so it will reduce the size of the mask to the minimal width mask which
22942 // performs an equivalent shuffle.
22943 SmallVector<int, 16> WidenedMask;
22944 while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
22945 Mask = std::move(WidenedMask);
22946 WidenedMask.clear();
22949 return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
22953 /// \brief Get the PSHUF-style mask from PSHUF node.
22955 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
22956 /// PSHUF-style masks that can be reused with such instructions.
22957 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
22958 MVT VT = N.getSimpleValueType();
22959 SmallVector<int, 4> Mask;
22961 bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
22965 // If we have more than 128-bits, only the low 128-bits of shuffle mask
22966 // matter. Check that the upper masks are repeats and remove them.
22967 if (VT.getSizeInBits() > 128) {
22968 int LaneElts = 128 / VT.getScalarSizeInBits();
22970 for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
22971 for (int j = 0; j < LaneElts; ++j)
22972 assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
22973 "Mask doesn't repeat in high 128-bit lanes!");
22975 Mask.resize(LaneElts);
22978 switch (N.getOpcode()) {
22979 case X86ISD::PSHUFD:
22981 case X86ISD::PSHUFLW:
22984 case X86ISD::PSHUFHW:
22985 Mask.erase(Mask.begin(), Mask.begin() + 4);
22986 for (int &M : Mask)
22990 llvm_unreachable("No valid shuffle instruction found!");
22994 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
22996 /// We walk up the chain and look for a combinable shuffle, skipping over
22997 /// shuffles that we could hoist this shuffle's transformation past without
22998 /// altering anything.
23000 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
23002 TargetLowering::DAGCombinerInfo &DCI) {
23003 assert(N.getOpcode() == X86ISD::PSHUFD &&
23004 "Called with something other than an x86 128-bit half shuffle!");
23007 // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
23008 // of the shuffles in the chain so that we can form a fresh chain to replace
23010 SmallVector<SDValue, 8> Chain;
23011 SDValue V = N.getOperand(0);
23012 for (; V.hasOneUse(); V = V.getOperand(0)) {
23013 switch (V.getOpcode()) {
23015 return SDValue(); // Nothing combined!
23018 // Skip bitcasts as we always know the type for the target specific
23022 case X86ISD::PSHUFD:
23023 // Found another dword shuffle.
23026 case X86ISD::PSHUFLW:
23027 // Check that the low words (being shuffled) are the identity in the
23028 // dword shuffle, and the high words are self-contained.
23029 if (Mask[0] != 0 || Mask[1] != 1 ||
23030 !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
23033 Chain.push_back(V);
23036 case X86ISD::PSHUFHW:
23037 // Check that the high words (being shuffled) are the identity in the
23038 // dword shuffle, and the low words are self-contained.
23039 if (Mask[2] != 2 || Mask[3] != 3 ||
23040 !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
23043 Chain.push_back(V);
23046 case X86ISD::UNPCKL:
23047 case X86ISD::UNPCKH:
23048 // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
23049 // shuffle into a preceding word shuffle.
23050 if (V.getSimpleValueType().getVectorElementType() != MVT::i8 &&
23051 V.getSimpleValueType().getVectorElementType() != MVT::i16)
23054 // Search for a half-shuffle which we can combine with.
23055 unsigned CombineOp =
23056 V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
23057 if (V.getOperand(0) != V.getOperand(1) ||
23058 !V->isOnlyUserOf(V.getOperand(0).getNode()))
23060 Chain.push_back(V);
23061 V = V.getOperand(0);
23063 switch (V.getOpcode()) {
23065 return SDValue(); // Nothing to combine.
23067 case X86ISD::PSHUFLW:
23068 case X86ISD::PSHUFHW:
23069 if (V.getOpcode() == CombineOp)
23072 Chain.push_back(V);
23076 V = V.getOperand(0);
23080 } while (V.hasOneUse());
23083 // Break out of the loop if we break out of the switch.
23087 if (!V.hasOneUse())
23088 // We fell out of the loop without finding a viable combining instruction.
23091 // Merge this node's mask and our incoming mask.
23092 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
23093 for (int &M : Mask)
23095 V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
23096 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
23098 // Rebuild the chain around this new shuffle.
23099 while (!Chain.empty()) {
23100 SDValue W = Chain.pop_back_val();
23102 if (V.getValueType() != W.getOperand(0).getValueType())
23103 V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
23105 switch (W.getOpcode()) {
23107 llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
23109 case X86ISD::UNPCKL:
23110 case X86ISD::UNPCKH:
23111 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
23114 case X86ISD::PSHUFD:
23115 case X86ISD::PSHUFLW:
23116 case X86ISD::PSHUFHW:
23117 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
23121 if (V.getValueType() != N.getValueType())
23122 V = DAG.getBitcast(N.getValueType(), V);
23124 // Return the new chain to replace N.
23128 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or
23131 /// We walk up the chain, skipping shuffles of the other half and looking
23132 /// through shuffles which switch halves trying to find a shuffle of the same
23133 /// pair of dwords.
23134 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
23136 TargetLowering::DAGCombinerInfo &DCI) {
23138 (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
23139 "Called with something other than an x86 128-bit half shuffle!");
23141 unsigned CombineOpcode = N.getOpcode();
23143 // Walk up a single-use chain looking for a combinable shuffle.
23144 SDValue V = N.getOperand(0);
23145 for (; V.hasOneUse(); V = V.getOperand(0)) {
23146 switch (V.getOpcode()) {
23148 return false; // Nothing combined!
23151 // Skip bitcasts as we always know the type for the target specific
23155 case X86ISD::PSHUFLW:
23156 case X86ISD::PSHUFHW:
23157 if (V.getOpcode() == CombineOpcode)
23160 // Other-half shuffles are no-ops.
23163 // Break out of the loop if we break out of the switch.
23167 if (!V.hasOneUse())
23168 // We fell out of the loop without finding a viable combining instruction.
23171 // Combine away the bottom node as its shuffle will be accumulated into
23172 // a preceding shuffle.
23173 DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
23175 // Record the old value.
23178 // Merge this node's mask and our incoming mask (adjusted to account for all
23179 // the pshufd instructions encountered).
23180 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
23181 for (int &M : Mask)
23183 V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
23184 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
23186 // Check that the shuffles didn't cancel each other out. If not, we need to
23187 // combine to the new one.
23189 // Replace the combinable shuffle with the combined one, updating all users
23190 // so that we re-evaluate the chain here.
23191 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
23196 /// \brief Try to combine x86 target specific shuffles.
23197 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
23198 TargetLowering::DAGCombinerInfo &DCI,
23199 const X86Subtarget *Subtarget) {
23201 MVT VT = N.getSimpleValueType();
23202 SmallVector<int, 4> Mask;
23204 switch (N.getOpcode()) {
23205 case X86ISD::PSHUFD:
23206 case X86ISD::PSHUFLW:
23207 case X86ISD::PSHUFHW:
23208 Mask = getPSHUFShuffleMask(N);
23209 assert(Mask.size() == 4);
23211 case X86ISD::UNPCKL: {
23212 // Combine X86ISD::UNPCKL and ISD::VECTOR_SHUFFLE into X86ISD::UNPCKH, in
23213 // which X86ISD::UNPCKL has a ISD::UNDEF operand, and ISD::VECTOR_SHUFFLE
23214 // moves upper half elements into the lower half part. For example:
23216 // t2: v16i8 = vector_shuffle<8,9,10,11,12,13,14,15,u,u,u,u,u,u,u,u> t1,
23218 // t3: v16i8 = X86ISD::UNPCKL undef:v16i8, t2
23220 // will be combined to:
23222 // t3: v16i8 = X86ISD::UNPCKH undef:v16i8, t1
23224 // This is only for 128-bit vectors. From SSE4.1 onward this combine may not
23225 // happen due to advanced instructions.
23226 if (!VT.is128BitVector())
23229 auto Op0 = N.getOperand(0);
23230 auto Op1 = N.getOperand(1);
23231 if (Op0.getOpcode() == ISD::UNDEF &&
23232 Op1.getNode()->getOpcode() == ISD::VECTOR_SHUFFLE) {
23233 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op1.getNode())->getMask();
23235 unsigned NumElts = VT.getVectorNumElements();
23236 SmallVector<int, 8> ExpectedMask(NumElts, -1);
23237 std::iota(ExpectedMask.begin(), ExpectedMask.begin() + NumElts / 2,
23240 auto ShufOp = Op1.getOperand(0);
23241 if (isShuffleEquivalent(Op1, ShufOp, Mask, ExpectedMask))
23242 return DAG.getNode(X86ISD::UNPCKH, DL, VT, N.getOperand(0), ShufOp);
23250 // Nuke no-op shuffles that show up after combining.
23251 if (isNoopShuffleMask(Mask))
23252 return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
23254 // Look for simplifications involving one or two shuffle instructions.
23255 SDValue V = N.getOperand(0);
23256 switch (N.getOpcode()) {
23259 case X86ISD::PSHUFLW:
23260 case X86ISD::PSHUFHW:
23261 assert(VT.getVectorElementType() == MVT::i16 && "Bad word shuffle type!");
23263 if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
23264 return SDValue(); // We combined away this shuffle, so we're done.
23266 // See if this reduces to a PSHUFD which is no more expensive and can
23267 // combine with more operations. Note that it has to at least flip the
23268 // dwords as otherwise it would have been removed as a no-op.
23269 if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
23270 int DMask[] = {0, 1, 2, 3};
23271 int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
23272 DMask[DOffset + 0] = DOffset + 1;
23273 DMask[DOffset + 1] = DOffset + 0;
23274 MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
23275 V = DAG.getBitcast(DVT, V);
23276 DCI.AddToWorklist(V.getNode());
23277 V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
23278 getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
23279 DCI.AddToWorklist(V.getNode());
23280 return DAG.getBitcast(VT, V);
23283 // Look for shuffle patterns which can be implemented as a single unpack.
23284 // FIXME: This doesn't handle the location of the PSHUFD generically, and
23285 // only works when we have a PSHUFD followed by two half-shuffles.
23286 if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
23287 (V.getOpcode() == X86ISD::PSHUFLW ||
23288 V.getOpcode() == X86ISD::PSHUFHW) &&
23289 V.getOpcode() != N.getOpcode() &&
23291 SDValue D = V.getOperand(0);
23292 while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
23293 D = D.getOperand(0);
23294 if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
23295 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
23296 SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
23297 int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
23298 int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
23300 for (int i = 0; i < 4; ++i) {
23301 WordMask[i + NOffset] = Mask[i] + NOffset;
23302 WordMask[i + VOffset] = VMask[i] + VOffset;
23304 // Map the word mask through the DWord mask.
23306 for (int i = 0; i < 8; ++i)
23307 MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
23308 if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
23309 makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
23310 // We can replace all three shuffles with an unpack.
23311 V = DAG.getBitcast(VT, D.getOperand(0));
23312 DCI.AddToWorklist(V.getNode());
23313 return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
23322 case X86ISD::PSHUFD:
23323 if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
23332 /// \brief Try to combine a shuffle into a target-specific add-sub node.
23334 /// We combine this directly on the abstract vector shuffle nodes so it is
23335 /// easier to generically match. We also insert dummy vector shuffle nodes for
23336 /// the operands which explicitly discard the lanes which are unused by this
23337 /// operation to try to flow through the rest of the combiner the fact that
23338 /// they're unused.
23339 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
23341 EVT VT = N->getValueType(0);
23343 // We only handle target-independent shuffles.
23344 // FIXME: It would be easy and harmless to use the target shuffle mask
23345 // extraction tool to support more.
23346 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
23349 auto *SVN = cast<ShuffleVectorSDNode>(N);
23350 SmallVector<int, 8> Mask;
23351 for (int M : SVN->getMask())
23354 SDValue V1 = N->getOperand(0);
23355 SDValue V2 = N->getOperand(1);
23357 // We require the first shuffle operand to be the FSUB node, and the second to
23358 // be the FADD node.
23359 if (V1.getOpcode() == ISD::FADD && V2.getOpcode() == ISD::FSUB) {
23360 ShuffleVectorSDNode::commuteMask(Mask);
23362 } else if (V1.getOpcode() != ISD::FSUB || V2.getOpcode() != ISD::FADD)
23365 // If there are other uses of these operations we can't fold them.
23366 if (!V1->hasOneUse() || !V2->hasOneUse())
23369 // Ensure that both operations have the same operands. Note that we can
23370 // commute the FADD operands.
23371 SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
23372 if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
23373 (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
23376 // We're looking for blends between FADD and FSUB nodes. We insist on these
23377 // nodes being lined up in a specific expected pattern.
23378 if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
23379 isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
23380 isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
23383 // Only specific types are legal at this point, assert so we notice if and
23384 // when these change.
23385 assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
23386 VT == MVT::v4f64) &&
23387 "Unknown vector type encountered!");
23389 return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
23392 /// PerformShuffleCombine - Performs several different shuffle combines.
23393 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
23394 TargetLowering::DAGCombinerInfo &DCI,
23395 const X86Subtarget *Subtarget) {
23397 SDValue N0 = N->getOperand(0);
23398 SDValue N1 = N->getOperand(1);
23399 EVT VT = N->getValueType(0);
23401 // Don't create instructions with illegal types after legalize types has run.
23402 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23403 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
23406 // If we have legalized the vector types, look for blends of FADD and FSUB
23407 // nodes that we can fuse into an ADDSUB node.
23408 if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
23409 if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
23412 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
23413 if (TLI.isTypeLegal(VT) && Subtarget->hasFp256() && VT.is256BitVector() &&
23414 N->getOpcode() == ISD::VECTOR_SHUFFLE)
23415 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
23417 // During Type Legalization, when promoting illegal vector types,
23418 // the backend might introduce new shuffle dag nodes and bitcasts.
23420 // This code performs the following transformation:
23421 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
23422 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
23424 // We do this only if both the bitcast and the BINOP dag nodes have
23425 // one use. Also, perform this transformation only if the new binary
23426 // operation is legal. This is to avoid introducing dag nodes that
23427 // potentially need to be further expanded (or custom lowered) into a
23428 // less optimal sequence of dag nodes.
23429 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
23430 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
23431 N0.getOpcode() == ISD::BITCAST) {
23432 SDValue BC0 = N0.getOperand(0);
23433 EVT SVT = BC0.getValueType();
23434 unsigned Opcode = BC0.getOpcode();
23435 unsigned NumElts = VT.getVectorNumElements();
23437 if (BC0.hasOneUse() && SVT.isVector() &&
23438 SVT.getVectorNumElements() * 2 == NumElts &&
23439 TLI.isOperationLegal(Opcode, VT)) {
23440 bool CanFold = false;
23452 unsigned SVTNumElts = SVT.getVectorNumElements();
23453 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
23454 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
23455 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
23456 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
23457 CanFold = SVOp->getMaskElt(i) < 0;
23460 SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
23461 SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
23462 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
23463 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
23468 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
23469 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
23470 // consecutive, non-overlapping, and in the right order.
23471 SmallVector<SDValue, 16> Elts;
23472 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
23473 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
23475 if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
23478 if (isTargetShuffle(N->getOpcode())) {
23480 PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
23481 if (Shuffle.getNode())
23484 // Try recursively combining arbitrary sequences of x86 shuffle
23485 // instructions into higher-order shuffles. We do this after combining
23486 // specific PSHUF instruction sequences into their minimal form so that we
23487 // can evaluate how many specialized shuffle instructions are involved in
23488 // a particular chain.
23489 SmallVector<int, 1> NonceMask; // Just a placeholder.
23490 NonceMask.push_back(0);
23491 if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
23492 /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
23494 return SDValue(); // This routine will use CombineTo to replace N.
23500 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
23501 /// specific shuffle of a load can be folded into a single element load.
23502 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
23503 /// shuffles have been custom lowered so we need to handle those here.
23504 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
23505 TargetLowering::DAGCombinerInfo &DCI) {
23506 if (DCI.isBeforeLegalizeOps())
23509 SDValue InVec = N->getOperand(0);
23510 SDValue EltNo = N->getOperand(1);
23512 if (!isa<ConstantSDNode>(EltNo))
23515 EVT OriginalVT = InVec.getValueType();
23517 if (InVec.getOpcode() == ISD::BITCAST) {
23518 // Don't duplicate a load with other uses.
23519 if (!InVec.hasOneUse())
23521 EVT BCVT = InVec.getOperand(0).getValueType();
23522 if (!BCVT.isVector() ||
23523 BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
23525 InVec = InVec.getOperand(0);
23528 EVT CurrentVT = InVec.getValueType();
23530 if (!isTargetShuffle(InVec.getOpcode()))
23533 // Don't duplicate a load with other uses.
23534 if (!InVec.hasOneUse())
23537 SmallVector<int, 16> ShuffleMask;
23539 if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
23540 ShuffleMask, UnaryShuffle))
23543 // Select the input vector, guarding against out of range extract vector.
23544 unsigned NumElems = CurrentVT.getVectorNumElements();
23545 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
23546 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
23547 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
23548 : InVec.getOperand(1);
23550 // If inputs to shuffle are the same for both ops, then allow 2 uses
23551 unsigned AllowedUses = InVec.getNumOperands() > 1 &&
23552 InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
23554 if (LdNode.getOpcode() == ISD::BITCAST) {
23555 // Don't duplicate a load with other uses.
23556 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
23559 AllowedUses = 1; // only allow 1 load use if we have a bitcast
23560 LdNode = LdNode.getOperand(0);
23563 if (!ISD::isNormalLoad(LdNode.getNode()))
23566 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
23568 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
23571 EVT EltVT = N->getValueType(0);
23572 // If there's a bitcast before the shuffle, check if the load type and
23573 // alignment is valid.
23574 unsigned Align = LN0->getAlignment();
23575 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23576 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
23577 EltVT.getTypeForEVT(*DAG.getContext()));
23579 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
23582 // All checks match so transform back to vector_shuffle so that DAG combiner
23583 // can finish the job
23586 // Create shuffle node taking into account the case that its a unary shuffle
23587 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
23588 : InVec.getOperand(1);
23589 Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
23590 InVec.getOperand(0), Shuffle,
23592 Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
23593 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
23597 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG,
23598 const X86Subtarget *Subtarget) {
23599 SDValue N0 = N->getOperand(0);
23600 EVT VT = N->getValueType(0);
23602 // Detect bitcasts between i32 to x86mmx low word. Since MMX types are
23603 // special and don't usually play with other vector types, it's better to
23604 // handle them early to be sure we emit efficient code by avoiding
23605 // store-load conversions.
23606 if (VT == MVT::x86mmx && N0.getOpcode() == ISD::BUILD_VECTOR &&
23607 N0.getValueType() == MVT::v2i32 &&
23608 isNullConstant(N0.getOperand(1))) {
23609 SDValue N00 = N0->getOperand(0);
23610 if (N00.getValueType() == MVT::i32)
23611 return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(N00), VT, N00);
23614 // Convert a bitcasted integer logic operation that has one bitcasted
23615 // floating-point operand and one constant operand into a floating-point
23616 // logic operation. This may create a load of the constant, but that is
23617 // cheaper than materializing the constant in an integer register and
23618 // transferring it to an SSE register or transferring the SSE operand to
23619 // integer register and back.
23621 switch (N0.getOpcode()) {
23622 case ISD::AND: FPOpcode = X86ISD::FAND; break;
23623 case ISD::OR: FPOpcode = X86ISD::FOR; break;
23624 case ISD::XOR: FPOpcode = X86ISD::FXOR; break;
23625 default: return SDValue();
23627 if (((Subtarget->hasSSE1() && VT == MVT::f32) ||
23628 (Subtarget->hasSSE2() && VT == MVT::f64)) &&
23629 isa<ConstantSDNode>(N0.getOperand(1)) &&
23630 N0.getOperand(0).getOpcode() == ISD::BITCAST &&
23631 N0.getOperand(0).getOperand(0).getValueType() == VT) {
23632 SDValue N000 = N0.getOperand(0).getOperand(0);
23633 SDValue FPConst = DAG.getBitcast(VT, N0.getOperand(1));
23634 return DAG.getNode(FPOpcode, SDLoc(N0), VT, N000, FPConst);
23640 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
23641 /// generation and convert it from being a bunch of shuffles and extracts
23642 /// into a somewhat faster sequence. For i686, the best sequence is apparently
23643 /// storing the value and loading scalars back, while for x64 we should
23644 /// use 64-bit extracts and shifts.
23645 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
23646 TargetLowering::DAGCombinerInfo &DCI) {
23647 if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
23650 SDValue InputVector = N->getOperand(0);
23651 SDLoc dl(InputVector);
23652 // Detect mmx to i32 conversion through a v2i32 elt extract.
23653 if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
23654 N->getValueType(0) == MVT::i32 &&
23655 InputVector.getValueType() == MVT::v2i32) {
23657 // The bitcast source is a direct mmx result.
23658 SDValue MMXSrc = InputVector.getNode()->getOperand(0);
23659 if (MMXSrc.getValueType() == MVT::x86mmx)
23660 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
23661 N->getValueType(0),
23662 InputVector.getNode()->getOperand(0));
23664 // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
23665 if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
23666 MMXSrc.getValueType() == MVT::i64) {
23667 SDValue MMXSrcOp = MMXSrc.getOperand(0);
23668 if (MMXSrcOp.hasOneUse() && MMXSrcOp.getOpcode() == ISD::BITCAST &&
23669 MMXSrcOp.getValueType() == MVT::v1i64 &&
23670 MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
23671 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
23672 N->getValueType(0), MMXSrcOp.getOperand(0));
23676 EVT VT = N->getValueType(0);
23678 if (VT == MVT::i1 && isa<ConstantSDNode>(N->getOperand(1)) &&
23679 InputVector.getOpcode() == ISD::BITCAST &&
23680 isa<ConstantSDNode>(InputVector.getOperand(0))) {
23681 uint64_t ExtractedElt =
23682 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
23683 uint64_t InputValue =
23684 cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
23685 uint64_t Res = (InputValue >> ExtractedElt) & 1;
23686 return DAG.getConstant(Res, dl, MVT::i1);
23688 // Only operate on vectors of 4 elements, where the alternative shuffling
23689 // gets to be more expensive.
23690 if (InputVector.getValueType() != MVT::v4i32)
23693 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
23694 // single use which is a sign-extend or zero-extend, and all elements are
23696 SmallVector<SDNode *, 4> Uses;
23697 unsigned ExtractedElements = 0;
23698 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
23699 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
23700 if (UI.getUse().getResNo() != InputVector.getResNo())
23703 SDNode *Extract = *UI;
23704 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
23707 if (Extract->getValueType(0) != MVT::i32)
23709 if (!Extract->hasOneUse())
23711 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
23712 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
23714 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
23717 // Record which element was extracted.
23718 ExtractedElements |=
23719 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
23721 Uses.push_back(Extract);
23724 // If not all the elements were used, this may not be worthwhile.
23725 if (ExtractedElements != 15)
23728 // Ok, we've now decided to do the transformation.
23729 // If 64-bit shifts are legal, use the extract-shift sequence,
23730 // otherwise bounce the vector off the cache.
23731 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23734 if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
23735 SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
23736 auto &DL = DAG.getDataLayout();
23737 EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
23738 SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
23739 DAG.getConstant(0, dl, VecIdxTy));
23740 SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
23741 DAG.getConstant(1, dl, VecIdxTy));
23743 SDValue ShAmt = DAG.getConstant(
23744 32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
23745 Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
23746 Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
23747 DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
23748 Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
23749 Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
23750 DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
23752 // Store the value to a temporary stack slot.
23753 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
23754 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
23755 MachinePointerInfo(), false, false, 0);
23757 EVT ElementType = InputVector.getValueType().getVectorElementType();
23758 unsigned EltSize = ElementType.getSizeInBits() / 8;
23760 // Replace each use (extract) with a load of the appropriate element.
23761 for (unsigned i = 0; i < 4; ++i) {
23762 uint64_t Offset = EltSize * i;
23763 auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
23764 SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
23766 SDValue ScalarAddr =
23767 DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
23769 // Load the scalar.
23770 Vals[i] = DAG.getLoad(ElementType, dl, Ch,
23771 ScalarAddr, MachinePointerInfo(),
23772 false, false, false, 0);
23777 // Replace the extracts
23778 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
23779 UE = Uses.end(); UI != UE; ++UI) {
23780 SDNode *Extract = *UI;
23782 SDValue Idx = Extract->getOperand(1);
23783 uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
23784 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
23787 // The replacement was made in place; don't return anything.
23792 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
23793 const X86Subtarget *Subtarget) {
23795 SDValue Cond = N->getOperand(0);
23796 SDValue LHS = N->getOperand(1);
23797 SDValue RHS = N->getOperand(2);
23799 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
23800 SDValue CondSrc = Cond->getOperand(0);
23801 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
23802 Cond = CondSrc->getOperand(0);
23805 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
23808 // A vselect where all conditions and data are constants can be optimized into
23809 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
23810 if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
23811 ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
23814 unsigned MaskValue = 0;
23815 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
23818 MVT VT = N->getSimpleValueType(0);
23819 unsigned NumElems = VT.getVectorNumElements();
23820 SmallVector<int, 8> ShuffleMask(NumElems, -1);
23821 for (unsigned i = 0; i < NumElems; ++i) {
23822 // Be sure we emit undef where we can.
23823 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
23824 ShuffleMask[i] = -1;
23826 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
23829 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23830 if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
23832 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
23835 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
23837 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
23838 TargetLowering::DAGCombinerInfo &DCI,
23839 const X86Subtarget *Subtarget) {
23841 SDValue Cond = N->getOperand(0);
23842 // Get the LHS/RHS of the select.
23843 SDValue LHS = N->getOperand(1);
23844 SDValue RHS = N->getOperand(2);
23845 EVT VT = LHS.getValueType();
23846 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23848 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
23849 // instructions match the semantics of the common C idiom x<y?x:y but not
23850 // x<=y?x:y, because of how they handle negative zero (which can be
23851 // ignored in unsafe-math mode).
23852 // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
23853 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
23854 VT != MVT::f80 && VT != MVT::f128 &&
23855 (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
23856 (Subtarget->hasSSE2() ||
23857 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
23858 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
23860 unsigned Opcode = 0;
23861 // Check for x CC y ? x : y.
23862 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
23863 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
23867 // Converting this to a min would handle NaNs incorrectly, and swapping
23868 // the operands would cause it to handle comparisons between positive
23869 // and negative zero incorrectly.
23870 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
23871 if (!DAG.getTarget().Options.UnsafeFPMath &&
23872 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
23874 std::swap(LHS, RHS);
23876 Opcode = X86ISD::FMIN;
23879 // Converting this to a min would handle comparisons between positive
23880 // and negative zero incorrectly.
23881 if (!DAG.getTarget().Options.UnsafeFPMath &&
23882 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
23884 Opcode = X86ISD::FMIN;
23887 // Converting this to a min would handle both negative zeros and NaNs
23888 // incorrectly, but we can swap the operands to fix both.
23889 std::swap(LHS, RHS);
23893 Opcode = X86ISD::FMIN;
23897 // Converting this to a max would handle comparisons between positive
23898 // and negative zero incorrectly.
23899 if (!DAG.getTarget().Options.UnsafeFPMath &&
23900 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
23902 Opcode = X86ISD::FMAX;
23905 // Converting this to a max would handle NaNs incorrectly, and swapping
23906 // the operands would cause it to handle comparisons between positive
23907 // and negative zero incorrectly.
23908 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
23909 if (!DAG.getTarget().Options.UnsafeFPMath &&
23910 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
23912 std::swap(LHS, RHS);
23914 Opcode = X86ISD::FMAX;
23917 // Converting this to a max would handle both negative zeros and NaNs
23918 // incorrectly, but we can swap the operands to fix both.
23919 std::swap(LHS, RHS);
23923 Opcode = X86ISD::FMAX;
23926 // Check for x CC y ? y : x -- a min/max with reversed arms.
23927 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
23928 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
23932 // Converting this to a min would handle comparisons between positive
23933 // and negative zero incorrectly, and swapping the operands would
23934 // cause it to handle NaNs incorrectly.
23935 if (!DAG.getTarget().Options.UnsafeFPMath &&
23936 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
23937 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23939 std::swap(LHS, RHS);
23941 Opcode = X86ISD::FMIN;
23944 // Converting this to a min would handle NaNs incorrectly.
23945 if (!DAG.getTarget().Options.UnsafeFPMath &&
23946 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
23948 Opcode = X86ISD::FMIN;
23951 // Converting this to a min would handle both negative zeros and NaNs
23952 // incorrectly, but we can swap the operands to fix both.
23953 std::swap(LHS, RHS);
23957 Opcode = X86ISD::FMIN;
23961 // Converting this to a max would handle NaNs incorrectly.
23962 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23964 Opcode = X86ISD::FMAX;
23967 // Converting this to a max would handle comparisons between positive
23968 // and negative zero incorrectly, and swapping the operands would
23969 // cause it to handle NaNs incorrectly.
23970 if (!DAG.getTarget().Options.UnsafeFPMath &&
23971 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
23972 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
23974 std::swap(LHS, RHS);
23976 Opcode = X86ISD::FMAX;
23979 // Converting this to a max would handle both negative zeros and NaNs
23980 // incorrectly, but we can swap the operands to fix both.
23981 std::swap(LHS, RHS);
23985 Opcode = X86ISD::FMAX;
23991 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
23994 EVT CondVT = Cond.getValueType();
23995 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
23996 CondVT.getVectorElementType() == MVT::i1) {
23997 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
23998 // lowering on KNL. In this case we convert it to
23999 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
24000 // The same situation for all 128 and 256-bit vectors of i8 and i16.
24001 // Since SKX these selects have a proper lowering.
24002 EVT OpVT = LHS.getValueType();
24003 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
24004 (OpVT.getVectorElementType() == MVT::i8 ||
24005 OpVT.getVectorElementType() == MVT::i16) &&
24006 !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
24007 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
24008 DCI.AddToWorklist(Cond.getNode());
24009 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
24012 // If this is a select between two integer constants, try to do some
24014 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
24015 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
24016 // Don't do this for crazy integer types.
24017 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
24018 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
24019 // so that TrueC (the true value) is larger than FalseC.
24020 bool NeedsCondInvert = false;
24022 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
24023 // Efficiently invertible.
24024 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
24025 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
24026 isa<ConstantSDNode>(Cond.getOperand(1))))) {
24027 NeedsCondInvert = true;
24028 std::swap(TrueC, FalseC);
24031 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
24032 if (FalseC->getAPIntValue() == 0 &&
24033 TrueC->getAPIntValue().isPowerOf2()) {
24034 if (NeedsCondInvert) // Invert the condition if needed.
24035 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
24036 DAG.getConstant(1, DL, Cond.getValueType()));
24038 // Zero extend the condition if needed.
24039 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
24041 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
24042 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
24043 DAG.getConstant(ShAmt, DL, MVT::i8));
24046 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
24047 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
24048 if (NeedsCondInvert) // Invert the condition if needed.
24049 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
24050 DAG.getConstant(1, DL, Cond.getValueType()));
24052 // Zero extend the condition if needed.
24053 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
24054 FalseC->getValueType(0), Cond);
24055 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24056 SDValue(FalseC, 0));
24059 // Optimize cases that will turn into an LEA instruction. This requires
24060 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
24061 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
24062 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
24063 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
24065 bool isFastMultiplier = false;
24067 switch ((unsigned char)Diff) {
24069 case 1: // result = add base, cond
24070 case 2: // result = lea base( , cond*2)
24071 case 3: // result = lea base(cond, cond*2)
24072 case 4: // result = lea base( , cond*4)
24073 case 5: // result = lea base(cond, cond*4)
24074 case 8: // result = lea base( , cond*8)
24075 case 9: // result = lea base(cond, cond*8)
24076 isFastMultiplier = true;
24081 if (isFastMultiplier) {
24082 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
24083 if (NeedsCondInvert) // Invert the condition if needed.
24084 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
24085 DAG.getConstant(1, DL, Cond.getValueType()));
24087 // Zero extend the condition if needed.
24088 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
24090 // Scale the condition by the difference.
24092 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
24093 DAG.getConstant(Diff, DL,
24094 Cond.getValueType()));
24096 // Add the base if non-zero.
24097 if (FalseC->getAPIntValue() != 0)
24098 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24099 SDValue(FalseC, 0));
24106 // Canonicalize max and min:
24107 // (x > y) ? x : y -> (x >= y) ? x : y
24108 // (x < y) ? x : y -> (x <= y) ? x : y
24109 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
24110 // the need for an extra compare
24111 // against zero. e.g.
24112 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
24114 // testl %edi, %edi
24116 // cmovgl %edi, %eax
24120 // cmovsl %eax, %edi
24121 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
24122 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
24123 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
24124 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
24129 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
24130 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
24131 Cond.getOperand(0), Cond.getOperand(1), NewCC);
24132 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
24137 // Early exit check
24138 if (!TLI.isTypeLegal(VT))
24141 // Match VSELECTs into subs with unsigned saturation.
24142 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
24143 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
24144 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
24145 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
24146 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
24148 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
24149 // left side invert the predicate to simplify logic below.
24151 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
24153 CC = ISD::getSetCCInverse(CC, true);
24154 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
24158 if (Other.getNode() && Other->getNumOperands() == 2 &&
24159 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
24160 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
24161 SDValue CondRHS = Cond->getOperand(1);
24163 // Look for a general sub with unsigned saturation first.
24164 // x >= y ? x-y : 0 --> subus x, y
24165 // x > y ? x-y : 0 --> subus x, y
24166 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
24167 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
24168 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
24170 if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
24171 if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
24172 if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
24173 if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
24174 // If the RHS is a constant we have to reverse the const
24175 // canonicalization.
24176 // x > C-1 ? x+-C : 0 --> subus x, C
24177 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
24178 CondRHSConst->getAPIntValue() ==
24179 (-OpRHSConst->getAPIntValue() - 1))
24180 return DAG.getNode(
24181 X86ISD::SUBUS, DL, VT, OpLHS,
24182 DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
24184 // Another special case: If C was a sign bit, the sub has been
24185 // canonicalized into a xor.
24186 // FIXME: Would it be better to use computeKnownBits to determine
24187 // whether it's safe to decanonicalize the xor?
24188 // x s< 0 ? x^C : 0 --> subus x, C
24189 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
24190 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
24191 OpRHSConst->getAPIntValue().isSignBit())
24192 // Note that we have to rebuild the RHS constant here to ensure we
24193 // don't rely on particular values of undef lanes.
24194 return DAG.getNode(
24195 X86ISD::SUBUS, DL, VT, OpLHS,
24196 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
24201 // Simplify vector selection if condition value type matches vselect
24203 if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
24204 assert(Cond.getValueType().isVector() &&
24205 "vector select expects a vector selector!");
24207 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
24208 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
24210 // Try invert the condition if true value is not all 1s and false value
24212 if (!TValIsAllOnes && !FValIsAllZeros &&
24213 // Check if the selector will be produced by CMPP*/PCMP*
24214 Cond.getOpcode() == ISD::SETCC &&
24215 // Check if SETCC has already been promoted
24216 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
24218 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
24219 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
24221 if (TValIsAllZeros || FValIsAllOnes) {
24222 SDValue CC = Cond.getOperand(2);
24223 ISD::CondCode NewCC =
24224 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
24225 Cond.getOperand(0).getValueType().isInteger());
24226 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
24227 std::swap(LHS, RHS);
24228 TValIsAllOnes = FValIsAllOnes;
24229 FValIsAllZeros = TValIsAllZeros;
24233 if (TValIsAllOnes || FValIsAllZeros) {
24236 if (TValIsAllOnes && FValIsAllZeros)
24238 else if (TValIsAllOnes)
24240 DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
24241 else if (FValIsAllZeros)
24242 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
24243 DAG.getBitcast(CondVT, LHS));
24245 return DAG.getBitcast(VT, Ret);
24249 // We should generate an X86ISD::BLENDI from a vselect if its argument
24250 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
24251 // constants. This specific pattern gets generated when we split a
24252 // selector for a 512 bit vector in a machine without AVX512 (but with
24253 // 256-bit vectors), during legalization:
24255 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
24257 // Iff we find this pattern and the build_vectors are built from
24258 // constants, we translate the vselect into a shuffle_vector that we
24259 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
24260 if ((N->getOpcode() == ISD::VSELECT ||
24261 N->getOpcode() == X86ISD::SHRUNKBLEND) &&
24262 !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
24263 SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
24264 if (Shuffle.getNode())
24268 // If this is a *dynamic* select (non-constant condition) and we can match
24269 // this node with one of the variable blend instructions, restructure the
24270 // condition so that the blends can use the high bit of each element and use
24271 // SimplifyDemandedBits to simplify the condition operand.
24272 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
24273 !DCI.isBeforeLegalize() &&
24274 !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
24275 unsigned BitWidth = Cond.getValueType().getScalarSizeInBits();
24277 // Don't optimize vector selects that map to mask-registers.
24281 // We can only handle the cases where VSELECT is directly legal on the
24282 // subtarget. We custom lower VSELECT nodes with constant conditions and
24283 // this makes it hard to see whether a dynamic VSELECT will correctly
24284 // lower, so we both check the operation's status and explicitly handle the
24285 // cases where a *dynamic* blend will fail even though a constant-condition
24286 // blend could be custom lowered.
24287 // FIXME: We should find a better way to handle this class of problems.
24288 // Potentially, we should combine constant-condition vselect nodes
24289 // pre-legalization into shuffles and not mark as many types as custom
24291 if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
24293 // FIXME: We don't support i16-element blends currently. We could and
24294 // should support them by making *all* the bits in the condition be set
24295 // rather than just the high bit and using an i8-element blend.
24296 if (VT.getVectorElementType() == MVT::i16)
24298 // Dynamic blending was only available from SSE4.1 onward.
24299 if (VT.is128BitVector() && !Subtarget->hasSSE41())
24301 // Byte blends are only available in AVX2
24302 if (VT == MVT::v32i8 && !Subtarget->hasAVX2())
24305 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
24306 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
24308 APInt KnownZero, KnownOne;
24309 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
24310 DCI.isBeforeLegalizeOps());
24311 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
24312 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
24314 // If we changed the computation somewhere in the DAG, this change
24315 // will affect all users of Cond.
24316 // Make sure it is fine and update all the nodes so that we do not
24317 // use the generic VSELECT anymore. Otherwise, we may perform
24318 // wrong optimizations as we messed up with the actual expectation
24319 // for the vector boolean values.
24320 if (Cond != TLO.Old) {
24321 // Check all uses of that condition operand to check whether it will be
24322 // consumed by non-BLEND instructions, which may depend on all bits are
24324 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
24326 if (I->getOpcode() != ISD::VSELECT)
24327 // TODO: Add other opcodes eventually lowered into BLEND.
24330 // Update all the users of the condition, before committing the change,
24331 // so that the VSELECT optimizations that expect the correct vector
24332 // boolean value will not be triggered.
24333 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
24335 DAG.ReplaceAllUsesOfValueWith(
24337 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
24338 Cond, I->getOperand(1), I->getOperand(2)));
24339 DCI.CommitTargetLoweringOpt(TLO);
24342 // At this point, only Cond is changed. Change the condition
24343 // just for N to keep the opportunity to optimize all other
24344 // users their own way.
24345 DAG.ReplaceAllUsesOfValueWith(
24347 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
24348 TLO.New, N->getOperand(1), N->getOperand(2)));
24356 // Check whether a boolean test is testing a boolean value generated by
24357 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
24360 // Simplify the following patterns:
24361 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
24362 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
24363 // to (Op EFLAGS Cond)
24365 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
24366 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
24367 // to (Op EFLAGS !Cond)
24369 // where Op could be BRCOND or CMOV.
24371 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
24372 // Quit if not CMP and SUB with its value result used.
24373 if (Cmp.getOpcode() != X86ISD::CMP &&
24374 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
24377 // Quit if not used as a boolean value.
24378 if (CC != X86::COND_E && CC != X86::COND_NE)
24381 // Check CMP operands. One of them should be 0 or 1 and the other should be
24382 // an SetCC or extended from it.
24383 SDValue Op1 = Cmp.getOperand(0);
24384 SDValue Op2 = Cmp.getOperand(1);
24387 const ConstantSDNode* C = nullptr;
24388 bool needOppositeCond = (CC == X86::COND_E);
24389 bool checkAgainstTrue = false; // Is it a comparison against 1?
24391 if ((C = dyn_cast<ConstantSDNode>(Op1)))
24393 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
24395 else // Quit if all operands are not constants.
24398 if (C->getZExtValue() == 1) {
24399 needOppositeCond = !needOppositeCond;
24400 checkAgainstTrue = true;
24401 } else if (C->getZExtValue() != 0)
24402 // Quit if the constant is neither 0 or 1.
24405 bool truncatedToBoolWithAnd = false;
24406 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
24407 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
24408 SetCC.getOpcode() == ISD::TRUNCATE ||
24409 SetCC.getOpcode() == ISD::AND) {
24410 if (SetCC.getOpcode() == ISD::AND) {
24412 if (isOneConstant(SetCC.getOperand(0)))
24414 if (isOneConstant(SetCC.getOperand(1)))
24418 SetCC = SetCC.getOperand(OpIdx);
24419 truncatedToBoolWithAnd = true;
24421 SetCC = SetCC.getOperand(0);
24424 switch (SetCC.getOpcode()) {
24425 case X86ISD::SETCC_CARRY:
24426 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
24427 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
24428 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
24429 // truncated to i1 using 'and'.
24430 if (checkAgainstTrue && !truncatedToBoolWithAnd)
24432 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
24433 "Invalid use of SETCC_CARRY!");
24435 case X86ISD::SETCC:
24436 // Set the condition code or opposite one if necessary.
24437 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
24438 if (needOppositeCond)
24439 CC = X86::GetOppositeBranchCondition(CC);
24440 return SetCC.getOperand(1);
24441 case X86ISD::CMOV: {
24442 // Check whether false/true value has canonical one, i.e. 0 or 1.
24443 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
24444 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
24445 // Quit if true value is not a constant.
24448 // Quit if false value is not a constant.
24450 SDValue Op = SetCC.getOperand(0);
24451 // Skip 'zext' or 'trunc' node.
24452 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
24453 Op.getOpcode() == ISD::TRUNCATE)
24454 Op = Op.getOperand(0);
24455 // A special case for rdrand/rdseed, where 0 is set if false cond is
24457 if ((Op.getOpcode() != X86ISD::RDRAND &&
24458 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
24461 // Quit if false value is not the constant 0 or 1.
24462 bool FValIsFalse = true;
24463 if (FVal && FVal->getZExtValue() != 0) {
24464 if (FVal->getZExtValue() != 1)
24466 // If FVal is 1, opposite cond is needed.
24467 needOppositeCond = !needOppositeCond;
24468 FValIsFalse = false;
24470 // Quit if TVal is not the constant opposite of FVal.
24471 if (FValIsFalse && TVal->getZExtValue() != 1)
24473 if (!FValIsFalse && TVal->getZExtValue() != 0)
24475 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
24476 if (needOppositeCond)
24477 CC = X86::GetOppositeBranchCondition(CC);
24478 return SetCC.getOperand(3);
24485 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
24487 /// (X86or (X86setcc) (X86setcc))
24488 /// (X86cmp (and (X86setcc) (X86setcc)), 0)
24489 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
24490 X86::CondCode &CC1, SDValue &Flags,
24492 if (Cond->getOpcode() == X86ISD::CMP) {
24493 if (!isNullConstant(Cond->getOperand(1)))
24496 Cond = Cond->getOperand(0);
24501 SDValue SetCC0, SetCC1;
24502 switch (Cond->getOpcode()) {
24503 default: return false;
24510 SetCC0 = Cond->getOperand(0);
24511 SetCC1 = Cond->getOperand(1);
24515 // Make sure we have SETCC nodes, using the same flags value.
24516 if (SetCC0.getOpcode() != X86ISD::SETCC ||
24517 SetCC1.getOpcode() != X86ISD::SETCC ||
24518 SetCC0->getOperand(1) != SetCC1->getOperand(1))
24521 CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
24522 CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
24523 Flags = SetCC0->getOperand(1);
24527 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
24528 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
24529 TargetLowering::DAGCombinerInfo &DCI,
24530 const X86Subtarget *Subtarget) {
24533 // If the flag operand isn't dead, don't touch this CMOV.
24534 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
24537 SDValue FalseOp = N->getOperand(0);
24538 SDValue TrueOp = N->getOperand(1);
24539 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
24540 SDValue Cond = N->getOperand(3);
24542 if (CC == X86::COND_E || CC == X86::COND_NE) {
24543 switch (Cond.getOpcode()) {
24547 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
24548 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
24549 return (CC == X86::COND_E) ? FalseOp : TrueOp;
24555 Flags = checkBoolTestSetCCCombine(Cond, CC);
24556 if (Flags.getNode() &&
24557 // Extra check as FCMOV only supports a subset of X86 cond.
24558 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
24559 SDValue Ops[] = { FalseOp, TrueOp,
24560 DAG.getConstant(CC, DL, MVT::i8), Flags };
24561 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
24564 // If this is a select between two integer constants, try to do some
24565 // optimizations. Note that the operands are ordered the opposite of SELECT
24567 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
24568 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
24569 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
24570 // larger than FalseC (the false value).
24571 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
24572 CC = X86::GetOppositeBranchCondition(CC);
24573 std::swap(TrueC, FalseC);
24574 std::swap(TrueOp, FalseOp);
24577 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
24578 // This is efficient for any integer data type (including i8/i16) and
24580 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
24581 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
24582 DAG.getConstant(CC, DL, MVT::i8), Cond);
24584 // Zero extend the condition if needed.
24585 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
24587 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
24588 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
24589 DAG.getConstant(ShAmt, DL, MVT::i8));
24590 if (N->getNumValues() == 2) // Dead flag value?
24591 return DCI.CombineTo(N, Cond, SDValue());
24595 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
24596 // for any integer data type, including i8/i16.
24597 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
24598 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
24599 DAG.getConstant(CC, DL, MVT::i8), Cond);
24601 // Zero extend the condition if needed.
24602 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
24603 FalseC->getValueType(0), Cond);
24604 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24605 SDValue(FalseC, 0));
24607 if (N->getNumValues() == 2) // Dead flag value?
24608 return DCI.CombineTo(N, Cond, SDValue());
24612 // Optimize cases that will turn into an LEA instruction. This requires
24613 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
24614 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
24615 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
24616 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
24618 bool isFastMultiplier = false;
24620 switch ((unsigned char)Diff) {
24622 case 1: // result = add base, cond
24623 case 2: // result = lea base( , cond*2)
24624 case 3: // result = lea base(cond, cond*2)
24625 case 4: // result = lea base( , cond*4)
24626 case 5: // result = lea base(cond, cond*4)
24627 case 8: // result = lea base( , cond*8)
24628 case 9: // result = lea base(cond, cond*8)
24629 isFastMultiplier = true;
24634 if (isFastMultiplier) {
24635 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
24636 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
24637 DAG.getConstant(CC, DL, MVT::i8), Cond);
24638 // Zero extend the condition if needed.
24639 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
24641 // Scale the condition by the difference.
24643 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
24644 DAG.getConstant(Diff, DL, Cond.getValueType()));
24646 // Add the base if non-zero.
24647 if (FalseC->getAPIntValue() != 0)
24648 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
24649 SDValue(FalseC, 0));
24650 if (N->getNumValues() == 2) // Dead flag value?
24651 return DCI.CombineTo(N, Cond, SDValue());
24658 // Handle these cases:
24659 // (select (x != c), e, c) -> select (x != c), e, x),
24660 // (select (x == c), c, e) -> select (x == c), x, e)
24661 // where the c is an integer constant, and the "select" is the combination
24662 // of CMOV and CMP.
24664 // The rationale for this change is that the conditional-move from a constant
24665 // needs two instructions, however, conditional-move from a register needs
24666 // only one instruction.
24668 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
24669 // some instruction-combining opportunities. This opt needs to be
24670 // postponed as late as possible.
24672 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
24673 // the DCI.xxxx conditions are provided to postpone the optimization as
24674 // late as possible.
24676 ConstantSDNode *CmpAgainst = nullptr;
24677 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
24678 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
24679 !isa<ConstantSDNode>(Cond.getOperand(0))) {
24681 if (CC == X86::COND_NE &&
24682 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
24683 CC = X86::GetOppositeBranchCondition(CC);
24684 std::swap(TrueOp, FalseOp);
24687 if (CC == X86::COND_E &&
24688 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
24689 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
24690 DAG.getConstant(CC, DL, MVT::i8), Cond };
24691 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
24696 // Fold and/or of setcc's to double CMOV:
24697 // (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
24698 // (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
24700 // This combine lets us generate:
24701 // cmovcc1 (jcc1 if we don't have CMOV)
24707 // cmovne (jne if we don't have CMOV)
24708 // When we can't use the CMOV instruction, it might increase branch
24710 // When we can use CMOV, or when there is no mispredict, this improves
24711 // throughput and reduces register pressure.
24713 if (CC == X86::COND_NE) {
24715 X86::CondCode CC0, CC1;
24717 if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
24719 std::swap(FalseOp, TrueOp);
24720 CC0 = X86::GetOppositeBranchCondition(CC0);
24721 CC1 = X86::GetOppositeBranchCondition(CC1);
24724 SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
24726 SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
24727 SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
24728 SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
24729 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
24737 /// PerformMulCombine - Optimize a single multiply with constant into two
24738 /// in order to implement it with two cheaper instructions, e.g.
24739 /// LEA + SHL, LEA + LEA.
24740 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
24741 TargetLowering::DAGCombinerInfo &DCI) {
24742 // An imul is usually smaller than the alternative sequence.
24743 if (DAG.getMachineFunction().getFunction()->optForMinSize())
24746 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
24749 EVT VT = N->getValueType(0);
24750 if (VT != MVT::i64 && VT != MVT::i32)
24753 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
24756 uint64_t MulAmt = C->getZExtValue();
24757 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
24760 uint64_t MulAmt1 = 0;
24761 uint64_t MulAmt2 = 0;
24762 if ((MulAmt % 9) == 0) {
24764 MulAmt2 = MulAmt / 9;
24765 } else if ((MulAmt % 5) == 0) {
24767 MulAmt2 = MulAmt / 5;
24768 } else if ((MulAmt % 3) == 0) {
24770 MulAmt2 = MulAmt / 3;
24776 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
24778 if (isPowerOf2_64(MulAmt2) &&
24779 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
24780 // If second multiplifer is pow2, issue it first. We want the multiply by
24781 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
24783 std::swap(MulAmt1, MulAmt2);
24785 if (isPowerOf2_64(MulAmt1))
24786 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
24787 DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
24789 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
24790 DAG.getConstant(MulAmt1, DL, VT));
24792 if (isPowerOf2_64(MulAmt2))
24793 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
24794 DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
24796 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
24797 DAG.getConstant(MulAmt2, DL, VT));
24801 assert(MulAmt != 0 && MulAmt != (VT == MVT::i64 ? UINT64_MAX : UINT32_MAX)
24802 && "Both cases that could cause potential overflows should have "
24803 "already been handled.");
24804 if (isPowerOf2_64(MulAmt - 1))
24805 // (mul x, 2^N + 1) => (add (shl x, N), x)
24806 NewMul = DAG.getNode(ISD::ADD, DL, VT, N->getOperand(0),
24807 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
24808 DAG.getConstant(Log2_64(MulAmt - 1), DL,
24811 else if (isPowerOf2_64(MulAmt + 1))
24812 // (mul x, 2^N - 1) => (sub (shl x, N), x)
24813 NewMul = DAG.getNode(ISD::SUB, DL, VT, DAG.getNode(ISD::SHL, DL, VT,
24815 DAG.getConstant(Log2_64(MulAmt + 1),
24816 DL, MVT::i8)), N->getOperand(0));
24820 // Do not add new nodes to DAG combiner worklist.
24821 DCI.CombineTo(N, NewMul, false);
24826 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
24827 SDValue N0 = N->getOperand(0);
24828 SDValue N1 = N->getOperand(1);
24829 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
24830 EVT VT = N0.getValueType();
24832 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
24833 // since the result of setcc_c is all zero's or all ones.
24834 if (VT.isInteger() && !VT.isVector() &&
24835 N1C && N0.getOpcode() == ISD::AND &&
24836 N0.getOperand(1).getOpcode() == ISD::Constant) {
24837 SDValue N00 = N0.getOperand(0);
24838 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
24839 APInt ShAmt = N1C->getAPIntValue();
24840 Mask = Mask.shl(ShAmt);
24841 bool MaskOK = false;
24842 // We can handle cases concerning bit-widening nodes containing setcc_c if
24843 // we carefully interrogate the mask to make sure we are semantics
24845 // The transform is not safe if the result of C1 << C2 exceeds the bitwidth
24846 // of the underlying setcc_c operation if the setcc_c was zero extended.
24847 // Consider the following example:
24848 // zext(setcc_c) -> i32 0x0000FFFF
24849 // c1 -> i32 0x0000FFFF
24850 // c2 -> i32 0x00000001
24851 // (shl (and (setcc_c), c1), c2) -> i32 0x0001FFFE
24852 // (and setcc_c, (c1 << c2)) -> i32 0x0000FFFE
24853 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24855 } else if (N00.getOpcode() == ISD::SIGN_EXTEND &&
24856 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
24858 } else if ((N00.getOpcode() == ISD::ZERO_EXTEND ||
24859 N00.getOpcode() == ISD::ANY_EXTEND) &&
24860 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
24861 MaskOK = Mask.isIntN(N00.getOperand(0).getValueSizeInBits());
24863 if (MaskOK && Mask != 0) {
24865 return DAG.getNode(ISD::AND, DL, VT, N00, DAG.getConstant(Mask, DL, VT));
24869 // Hardware support for vector shifts is sparse which makes us scalarize the
24870 // vector operations in many cases. Also, on sandybridge ADD is faster than
24872 // (shl V, 1) -> add V,V
24873 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
24874 if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
24875 assert(N0.getValueType().isVector() && "Invalid vector shift type");
24876 // We shift all of the values by one. In many cases we do not have
24877 // hardware support for this operation. This is better expressed as an ADD
24879 if (N1SplatC->getAPIntValue() == 1)
24880 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
24886 /// \brief Returns a vector of 0s if the node in input is a vector logical
24887 /// shift by a constant amount which is known to be bigger than or equal
24888 /// to the vector element size in bits.
24889 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
24890 const X86Subtarget *Subtarget) {
24891 EVT VT = N->getValueType(0);
24893 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
24894 (!Subtarget->hasInt256() ||
24895 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
24898 SDValue Amt = N->getOperand(1);
24900 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
24901 if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
24902 APInt ShiftAmt = AmtSplat->getAPIntValue();
24903 unsigned MaxAmount =
24904 VT.getSimpleVT().getVectorElementType().getSizeInBits();
24906 // SSE2/AVX2 logical shifts always return a vector of 0s
24907 // if the shift amount is bigger than or equal to
24908 // the element size. The constant shift amount will be
24909 // encoded as a 8-bit immediate.
24910 if (ShiftAmt.trunc(8).uge(MaxAmount))
24911 return getZeroVector(VT.getSimpleVT(), Subtarget, DAG, DL);
24917 /// PerformShiftCombine - Combine shifts.
24918 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
24919 TargetLowering::DAGCombinerInfo &DCI,
24920 const X86Subtarget *Subtarget) {
24921 if (N->getOpcode() == ISD::SHL)
24922 if (SDValue V = PerformSHLCombine(N, DAG))
24925 // Try to fold this logical shift into a zero vector.
24926 if (N->getOpcode() != ISD::SRA)
24927 if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
24933 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
24934 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
24935 // and friends. Likewise for OR -> CMPNEQSS.
24936 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
24937 TargetLowering::DAGCombinerInfo &DCI,
24938 const X86Subtarget *Subtarget) {
24941 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
24942 // we're requiring SSE2 for both.
24943 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
24944 SDValue N0 = N->getOperand(0);
24945 SDValue N1 = N->getOperand(1);
24946 SDValue CMP0 = N0->getOperand(1);
24947 SDValue CMP1 = N1->getOperand(1);
24950 // The SETCCs should both refer to the same CMP.
24951 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
24954 SDValue CMP00 = CMP0->getOperand(0);
24955 SDValue CMP01 = CMP0->getOperand(1);
24956 EVT VT = CMP00.getValueType();
24958 if (VT == MVT::f32 || VT == MVT::f64) {
24959 bool ExpectingFlags = false;
24960 // Check for any users that want flags:
24961 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
24962 !ExpectingFlags && UI != UE; ++UI)
24963 switch (UI->getOpcode()) {
24968 ExpectingFlags = true;
24970 case ISD::CopyToReg:
24971 case ISD::SIGN_EXTEND:
24972 case ISD::ZERO_EXTEND:
24973 case ISD::ANY_EXTEND:
24977 if (!ExpectingFlags) {
24978 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
24979 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
24981 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
24982 X86::CondCode tmp = cc0;
24987 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
24988 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
24989 // FIXME: need symbolic constants for these magic numbers.
24990 // See X86ATTInstPrinter.cpp:printSSECC().
24991 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
24992 if (Subtarget->hasAVX512()) {
24993 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
24995 DAG.getConstant(x86cc, DL, MVT::i8));
24996 if (N->getValueType(0) != MVT::i1)
24997 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
25001 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
25002 CMP00.getValueType(), CMP00, CMP01,
25003 DAG.getConstant(x86cc, DL,
25006 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
25007 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
25009 if (is64BitFP && !Subtarget->is64Bit()) {
25010 // On a 32-bit target, we cannot bitcast the 64-bit float to a
25011 // 64-bit integer, since that's not a legal type. Since
25012 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
25013 // bits, but can do this little dance to extract the lowest 32 bits
25014 // and work with those going forward.
25015 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
25017 SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
25018 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
25019 Vector32, DAG.getIntPtrConstant(0, DL));
25023 SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
25024 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
25025 DAG.getConstant(1, DL, IntVT));
25026 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
25028 return OneBitOfTruth;
25036 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
25037 /// so it can be folded inside ANDNP.
25038 static bool CanFoldXORWithAllOnes(const SDNode *N) {
25039 EVT VT = N->getValueType(0);
25041 // Match direct AllOnes for 128 and 256-bit vectors
25042 if (ISD::isBuildVectorAllOnes(N))
25045 // Look through a bit convert.
25046 if (N->getOpcode() == ISD::BITCAST)
25047 N = N->getOperand(0).getNode();
25049 // Sometimes the operand may come from a insert_subvector building a 256-bit
25051 if (VT.is256BitVector() &&
25052 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
25053 SDValue V1 = N->getOperand(0);
25054 SDValue V2 = N->getOperand(1);
25056 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
25057 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
25058 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
25059 ISD::isBuildVectorAllOnes(V2.getNode()))
25066 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
25067 // register. In most cases we actually compare or select YMM-sized registers
25068 // and mixing the two types creates horrible code. This method optimizes
25069 // some of the transition sequences.
25070 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
25071 TargetLowering::DAGCombinerInfo &DCI,
25072 const X86Subtarget *Subtarget) {
25073 EVT VT = N->getValueType(0);
25074 if (!VT.is256BitVector())
25077 assert((N->getOpcode() == ISD::ANY_EXTEND ||
25078 N->getOpcode() == ISD::ZERO_EXTEND ||
25079 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
25081 SDValue Narrow = N->getOperand(0);
25082 EVT NarrowVT = Narrow->getValueType(0);
25083 if (!NarrowVT.is128BitVector())
25086 if (Narrow->getOpcode() != ISD::XOR &&
25087 Narrow->getOpcode() != ISD::AND &&
25088 Narrow->getOpcode() != ISD::OR)
25091 SDValue N0 = Narrow->getOperand(0);
25092 SDValue N1 = Narrow->getOperand(1);
25095 // The Left side has to be a trunc.
25096 if (N0.getOpcode() != ISD::TRUNCATE)
25099 // The type of the truncated inputs.
25100 EVT WideVT = N0->getOperand(0)->getValueType(0);
25104 // The right side has to be a 'trunc' or a constant vector.
25105 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
25106 ConstantSDNode *RHSConstSplat = nullptr;
25107 if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
25108 RHSConstSplat = RHSBV->getConstantSplatNode();
25109 if (!RHSTrunc && !RHSConstSplat)
25112 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25114 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
25117 // Set N0 and N1 to hold the inputs to the new wide operation.
25118 N0 = N0->getOperand(0);
25119 if (RHSConstSplat) {
25120 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getVectorElementType(),
25121 SDValue(RHSConstSplat, 0));
25122 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
25123 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
25124 } else if (RHSTrunc) {
25125 N1 = N1->getOperand(0);
25128 // Generate the wide operation.
25129 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
25130 unsigned Opcode = N->getOpcode();
25132 case ISD::ANY_EXTEND:
25134 case ISD::ZERO_EXTEND: {
25135 unsigned InBits = NarrowVT.getScalarSizeInBits();
25136 APInt Mask = APInt::getAllOnesValue(InBits);
25137 Mask = Mask.zext(VT.getScalarSizeInBits());
25138 return DAG.getNode(ISD::AND, DL, VT,
25139 Op, DAG.getConstant(Mask, DL, VT));
25141 case ISD::SIGN_EXTEND:
25142 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
25143 Op, DAG.getValueType(NarrowVT));
25145 llvm_unreachable("Unexpected opcode");
25149 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
25150 TargetLowering::DAGCombinerInfo &DCI,
25151 const X86Subtarget *Subtarget) {
25152 SDValue N0 = N->getOperand(0);
25153 SDValue N1 = N->getOperand(1);
25156 // A vector zext_in_reg may be represented as a shuffle,
25157 // feeding into a bitcast (this represents anyext) feeding into
25158 // an and with a mask.
25159 // We'd like to try to combine that into a shuffle with zero
25160 // plus a bitcast, removing the and.
25161 if (N0.getOpcode() != ISD::BITCAST ||
25162 N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
25165 // The other side of the AND should be a splat of 2^C, where C
25166 // is the number of bits in the source type.
25167 if (N1.getOpcode() == ISD::BITCAST)
25168 N1 = N1.getOperand(0);
25169 if (N1.getOpcode() != ISD::BUILD_VECTOR)
25171 BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
25173 ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
25174 EVT SrcType = Shuffle->getValueType(0);
25176 // We expect a single-source shuffle
25177 if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
25180 unsigned SrcSize = SrcType.getScalarSizeInBits();
25182 APInt SplatValue, SplatUndef;
25183 unsigned SplatBitSize;
25185 if (!Vector->isConstantSplat(SplatValue, SplatUndef,
25186 SplatBitSize, HasAnyUndefs))
25189 unsigned ResSize = N1.getValueType().getScalarSizeInBits();
25190 // Make sure the splat matches the mask we expect
25191 if (SplatBitSize > ResSize ||
25192 (SplatValue + 1).exactLogBase2() != (int)SrcSize)
25195 // Make sure the input and output size make sense
25196 if (SrcSize >= ResSize || ResSize % SrcSize)
25199 // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
25200 // The number of u's between each two values depends on the ratio between
25201 // the source and dest type.
25202 unsigned ZextRatio = ResSize / SrcSize;
25203 bool IsZext = true;
25204 for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
25205 if (i % ZextRatio) {
25206 if (Shuffle->getMaskElt(i) > 0) {
25212 if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
25213 // Expected element number
25223 // Ok, perform the transformation - replace the shuffle with
25224 // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
25225 // (instead of undef) where the k elements come from the zero vector.
25226 SmallVector<int, 8> Mask;
25227 unsigned NumElems = SrcType.getVectorNumElements();
25228 for (unsigned i = 0; i < NumElems; ++i)
25230 Mask.push_back(NumElems);
25232 Mask.push_back(i / ZextRatio);
25234 SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
25235 Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
25236 return DAG.getBitcast(N0.getValueType(), NewShuffle);
25239 /// If both input operands of a logic op are being cast from floating point
25240 /// types, try to convert this into a floating point logic node to avoid
25241 /// unnecessary moves from SSE to integer registers.
25242 static SDValue convertIntLogicToFPLogic(SDNode *N, SelectionDAG &DAG,
25243 const X86Subtarget *Subtarget) {
25244 unsigned FPOpcode = ISD::DELETED_NODE;
25245 if (N->getOpcode() == ISD::AND)
25246 FPOpcode = X86ISD::FAND;
25247 else if (N->getOpcode() == ISD::OR)
25248 FPOpcode = X86ISD::FOR;
25249 else if (N->getOpcode() == ISD::XOR)
25250 FPOpcode = X86ISD::FXOR;
25252 assert(FPOpcode != ISD::DELETED_NODE &&
25253 "Unexpected input node for FP logic conversion");
25255 EVT VT = N->getValueType(0);
25256 SDValue N0 = N->getOperand(0);
25257 SDValue N1 = N->getOperand(1);
25259 if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST &&
25260 ((Subtarget->hasSSE1() && VT == MVT::i32) ||
25261 (Subtarget->hasSSE2() && VT == MVT::i64))) {
25262 SDValue N00 = N0.getOperand(0);
25263 SDValue N10 = N1.getOperand(0);
25264 EVT N00Type = N00.getValueType();
25265 EVT N10Type = N10.getValueType();
25266 if (N00Type.isFloatingPoint() && N10Type.isFloatingPoint()) {
25267 SDValue FPLogic = DAG.getNode(FPOpcode, DL, N00Type, N00, N10);
25268 return DAG.getBitcast(VT, FPLogic);
25274 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
25275 TargetLowering::DAGCombinerInfo &DCI,
25276 const X86Subtarget *Subtarget) {
25277 if (DCI.isBeforeLegalizeOps())
25280 if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
25283 if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
25286 if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
25289 EVT VT = N->getValueType(0);
25290 SDValue N0 = N->getOperand(0);
25291 SDValue N1 = N->getOperand(1);
25294 // Create BEXTR instructions
25295 // BEXTR is ((X >> imm) & (2**size-1))
25296 if (VT == MVT::i32 || VT == MVT::i64) {
25297 // Check for BEXTR.
25298 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
25299 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
25300 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
25301 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
25302 if (MaskNode && ShiftNode) {
25303 uint64_t Mask = MaskNode->getZExtValue();
25304 uint64_t Shift = ShiftNode->getZExtValue();
25305 if (isMask_64(Mask)) {
25306 uint64_t MaskSize = countPopulation(Mask);
25307 if (Shift + MaskSize <= VT.getSizeInBits())
25308 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
25309 DAG.getConstant(Shift | (MaskSize << 8), DL,
25318 // Want to form ANDNP nodes:
25319 // 1) In the hopes of then easily combining them with OR and AND nodes
25320 // to form PBLEND/PSIGN.
25321 // 2) To match ANDN packed intrinsics
25322 if (VT != MVT::v2i64 && VT != MVT::v4i64)
25325 // Check LHS for vnot
25326 if (N0.getOpcode() == ISD::XOR &&
25327 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
25328 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
25329 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
25331 // Check RHS for vnot
25332 if (N1.getOpcode() == ISD::XOR &&
25333 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
25334 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
25335 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
25340 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
25341 TargetLowering::DAGCombinerInfo &DCI,
25342 const X86Subtarget *Subtarget) {
25343 if (DCI.isBeforeLegalizeOps())
25346 if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
25349 if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
25352 SDValue N0 = N->getOperand(0);
25353 SDValue N1 = N->getOperand(1);
25354 EVT VT = N->getValueType(0);
25356 // look for psign/blend
25357 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
25358 if (!Subtarget->hasSSSE3() ||
25359 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
25362 // Canonicalize pandn to RHS
25363 if (N0.getOpcode() == X86ISD::ANDNP)
25365 // or (and (m, y), (pandn m, x))
25366 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
25367 SDValue Mask = N1.getOperand(0);
25368 SDValue X = N1.getOperand(1);
25370 if (N0.getOperand(0) == Mask)
25371 Y = N0.getOperand(1);
25372 if (N0.getOperand(1) == Mask)
25373 Y = N0.getOperand(0);
25375 // Check to see if the mask appeared in both the AND and ANDNP and
25379 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
25380 // Look through mask bitcast.
25381 if (Mask.getOpcode() == ISD::BITCAST)
25382 Mask = Mask.getOperand(0);
25383 if (X.getOpcode() == ISD::BITCAST)
25384 X = X.getOperand(0);
25385 if (Y.getOpcode() == ISD::BITCAST)
25386 Y = Y.getOperand(0);
25388 EVT MaskVT = Mask.getValueType();
25390 // Validate that the Mask operand is a vector sra node.
25391 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
25392 // there is no psrai.b
25393 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
25394 unsigned SraAmt = ~0;
25395 if (Mask.getOpcode() == ISD::SRA) {
25396 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
25397 if (auto *AmtConst = AmtBV->getConstantSplatNode())
25398 SraAmt = AmtConst->getZExtValue();
25399 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
25400 SDValue SraC = Mask.getOperand(1);
25401 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
25403 if ((SraAmt + 1) != EltBits)
25408 // Now we know we at least have a plendvb with the mask val. See if
25409 // we can form a psignb/w/d.
25410 // psign = x.type == y.type == mask.type && y = sub(0, x);
25411 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
25412 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
25413 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
25414 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
25415 "Unsupported VT for PSIGN");
25416 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
25417 return DAG.getBitcast(VT, Mask);
25419 // PBLENDVB only available on SSE 4.1
25420 if (!Subtarget->hasSSE41())
25423 MVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
25425 X = DAG.getBitcast(BlendVT, X);
25426 Y = DAG.getBitcast(BlendVT, Y);
25427 Mask = DAG.getBitcast(BlendVT, Mask);
25428 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
25429 return DAG.getBitcast(VT, Mask);
25433 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
25436 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
25437 bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
25439 // SHLD/SHRD instructions have lower register pressure, but on some
25440 // platforms they have higher latency than the equivalent
25441 // series of shifts/or that would otherwise be generated.
25442 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
25443 // have higher latencies and we are not optimizing for size.
25444 if (!OptForSize && Subtarget->isSHLDSlow())
25447 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
25449 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
25451 if (!N0.hasOneUse() || !N1.hasOneUse())
25454 SDValue ShAmt0 = N0.getOperand(1);
25455 if (ShAmt0.getValueType() != MVT::i8)
25457 SDValue ShAmt1 = N1.getOperand(1);
25458 if (ShAmt1.getValueType() != MVT::i8)
25460 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
25461 ShAmt0 = ShAmt0.getOperand(0);
25462 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
25463 ShAmt1 = ShAmt1.getOperand(0);
25466 unsigned Opc = X86ISD::SHLD;
25467 SDValue Op0 = N0.getOperand(0);
25468 SDValue Op1 = N1.getOperand(0);
25469 if (ShAmt0.getOpcode() == ISD::SUB) {
25470 Opc = X86ISD::SHRD;
25471 std::swap(Op0, Op1);
25472 std::swap(ShAmt0, ShAmt1);
25475 unsigned Bits = VT.getSizeInBits();
25476 if (ShAmt1.getOpcode() == ISD::SUB) {
25477 SDValue Sum = ShAmt1.getOperand(0);
25478 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
25479 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
25480 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
25481 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
25482 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
25483 return DAG.getNode(Opc, DL, VT,
25485 DAG.getNode(ISD::TRUNCATE, DL,
25488 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
25489 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
25491 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
25492 return DAG.getNode(Opc, DL, VT,
25493 N0.getOperand(0), N1.getOperand(0),
25494 DAG.getNode(ISD::TRUNCATE, DL,
25501 // Generate NEG and CMOV for integer abs.
25502 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
25503 EVT VT = N->getValueType(0);
25505 // Since X86 does not have CMOV for 8-bit integer, we don't convert
25506 // 8-bit integer abs to NEG and CMOV.
25507 if (VT.isInteger() && VT.getSizeInBits() == 8)
25510 SDValue N0 = N->getOperand(0);
25511 SDValue N1 = N->getOperand(1);
25514 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
25515 // and change it to SUB and CMOV.
25516 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
25517 N0.getOpcode() == ISD::ADD &&
25518 N0.getOperand(1) == N1 &&
25519 N1.getOpcode() == ISD::SRA &&
25520 N1.getOperand(0) == N0.getOperand(0))
25521 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
25522 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
25523 // Generate SUB & CMOV.
25524 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
25525 DAG.getConstant(0, DL, VT), N0.getOperand(0));
25527 SDValue Ops[] = { N0.getOperand(0), Neg,
25528 DAG.getConstant(X86::COND_GE, DL, MVT::i8),
25529 SDValue(Neg.getNode(), 1) };
25530 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
25535 // Try to turn tests against the signbit in the form of:
25536 // XOR(TRUNCATE(SRL(X, size(X)-1)), 1)
25539 static SDValue foldXorTruncShiftIntoCmp(SDNode *N, SelectionDAG &DAG) {
25540 // This is only worth doing if the output type is i8.
25541 if (N->getValueType(0) != MVT::i8)
25544 SDValue N0 = N->getOperand(0);
25545 SDValue N1 = N->getOperand(1);
25547 // We should be performing an xor against a truncated shift.
25548 if (N0.getOpcode() != ISD::TRUNCATE || !N0.hasOneUse())
25551 // Make sure we are performing an xor against one.
25552 if (!isOneConstant(N1))
25555 // SetCC on x86 zero extends so only act on this if it's a logical shift.
25556 SDValue Shift = N0.getOperand(0);
25557 if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse())
25560 // Make sure we are truncating from one of i16, i32 or i64.
25561 EVT ShiftTy = Shift.getValueType();
25562 if (ShiftTy != MVT::i16 && ShiftTy != MVT::i32 && ShiftTy != MVT::i64)
25565 // Make sure the shift amount extracts the sign bit.
25566 if (!isa<ConstantSDNode>(Shift.getOperand(1)) ||
25567 Shift.getConstantOperandVal(1) != ShiftTy.getSizeInBits() - 1)
25570 // Create a greater-than comparison against -1.
25571 // N.B. Using SETGE against 0 works but we want a canonical looking
25572 // comparison, using SETGT matches up with what TranslateX86CC.
25574 SDValue ShiftOp = Shift.getOperand(0);
25575 EVT ShiftOpTy = ShiftOp.getValueType();
25576 SDValue Cond = DAG.getSetCC(DL, MVT::i8, ShiftOp,
25577 DAG.getConstant(-1, DL, ShiftOpTy), ISD::SETGT);
25581 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
25582 TargetLowering::DAGCombinerInfo &DCI,
25583 const X86Subtarget *Subtarget) {
25584 if (DCI.isBeforeLegalizeOps())
25587 if (SDValue RV = foldXorTruncShiftIntoCmp(N, DAG))
25590 if (Subtarget->hasCMov())
25591 if (SDValue RV = performIntegerAbsCombine(N, DAG))
25594 if (SDValue FPLogic = convertIntLogicToFPLogic(N, DAG, Subtarget))
25600 /// This function detects the AVG pattern between vectors of unsigned i8/i16,
25601 /// which is c = (a + b + 1) / 2, and replace this operation with the efficient
25602 /// X86ISD::AVG instruction.
25603 static SDValue detectAVGPattern(SDValue In, EVT VT, SelectionDAG &DAG,
25604 const X86Subtarget *Subtarget, SDLoc DL) {
25605 if (!VT.isVector() || !VT.isSimple())
25607 EVT InVT = In.getValueType();
25608 unsigned NumElems = VT.getVectorNumElements();
25610 EVT ScalarVT = VT.getVectorElementType();
25611 if (!((ScalarVT == MVT::i8 || ScalarVT == MVT::i16) &&
25612 isPowerOf2_32(NumElems)))
25615 // InScalarVT is the intermediate type in AVG pattern and it should be greater
25616 // than the original input type (i8/i16).
25617 EVT InScalarVT = InVT.getVectorElementType();
25618 if (InScalarVT.getSizeInBits() <= ScalarVT.getSizeInBits())
25621 if (Subtarget->hasAVX512()) {
25622 if (VT.getSizeInBits() > 512)
25624 } else if (Subtarget->hasAVX2()) {
25625 if (VT.getSizeInBits() > 256)
25628 if (VT.getSizeInBits() > 128)
25632 // Detect the following pattern:
25634 // %1 = zext <N x i8> %a to <N x i32>
25635 // %2 = zext <N x i8> %b to <N x i32>
25636 // %3 = add nuw nsw <N x i32> %1, <i32 1 x N>
25637 // %4 = add nuw nsw <N x i32> %3, %2
25638 // %5 = lshr <N x i32> %N, <i32 1 x N>
25639 // %6 = trunc <N x i32> %5 to <N x i8>
25641 // In AVX512, the last instruction can also be a trunc store.
25643 if (In.getOpcode() != ISD::SRL)
25646 // A lambda checking the given SDValue is a constant vector and each element
25647 // is in the range [Min, Max].
25648 auto IsConstVectorInRange = [](SDValue V, unsigned Min, unsigned Max) {
25649 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(V);
25650 if (!BV || !BV->isConstant())
25652 for (unsigned i = 0, e = V.getNumOperands(); i < e; i++) {
25653 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(i));
25656 uint64_t Val = C->getZExtValue();
25657 if (Val < Min || Val > Max)
25663 // Check if each element of the vector is left-shifted by one.
25664 auto LHS = In.getOperand(0);
25665 auto RHS = In.getOperand(1);
25666 if (!IsConstVectorInRange(RHS, 1, 1))
25668 if (LHS.getOpcode() != ISD::ADD)
25671 // Detect a pattern of a + b + 1 where the order doesn't matter.
25672 SDValue Operands[3];
25673 Operands[0] = LHS.getOperand(0);
25674 Operands[1] = LHS.getOperand(1);
25676 // Take care of the case when one of the operands is a constant vector whose
25677 // element is in the range [1, 256].
25678 if (IsConstVectorInRange(Operands[1], 1, ScalarVT == MVT::i8 ? 256 : 65536) &&
25679 Operands[0].getOpcode() == ISD::ZERO_EXTEND &&
25680 Operands[0].getOperand(0).getValueType() == VT) {
25681 // The pattern is detected. Subtract one from the constant vector, then
25682 // demote it and emit X86ISD::AVG instruction.
25683 SDValue One = DAG.getConstant(1, DL, InScalarVT);
25684 SDValue Ones = DAG.getNode(ISD::BUILD_VECTOR, DL, InVT,
25685 SmallVector<SDValue, 8>(NumElems, One));
25686 Operands[1] = DAG.getNode(ISD::SUB, DL, InVT, Operands[1], Ones);
25687 Operands[1] = DAG.getNode(ISD::TRUNCATE, DL, VT, Operands[1]);
25688 return DAG.getNode(X86ISD::AVG, DL, VT, Operands[0].getOperand(0),
25692 if (Operands[0].getOpcode() == ISD::ADD)
25693 std::swap(Operands[0], Operands[1]);
25694 else if (Operands[1].getOpcode() != ISD::ADD)
25696 Operands[2] = Operands[1].getOperand(0);
25697 Operands[1] = Operands[1].getOperand(1);
25699 // Now we have three operands of two additions. Check that one of them is a
25700 // constant vector with ones, and the other two are promoted from i8/i16.
25701 for (int i = 0; i < 3; ++i) {
25702 if (!IsConstVectorInRange(Operands[i], 1, 1))
25704 std::swap(Operands[i], Operands[2]);
25706 // Check if Operands[0] and Operands[1] are results of type promotion.
25707 for (int j = 0; j < 2; ++j)
25708 if (Operands[j].getOpcode() != ISD::ZERO_EXTEND ||
25709 Operands[j].getOperand(0).getValueType() != VT)
25712 // The pattern is detected, emit X86ISD::AVG instruction.
25713 return DAG.getNode(X86ISD::AVG, DL, VT, Operands[0].getOperand(0),
25714 Operands[1].getOperand(0));
25720 static SDValue PerformTRUNCATECombine(SDNode *N, SelectionDAG &DAG,
25721 const X86Subtarget *Subtarget) {
25722 return detectAVGPattern(N->getOperand(0), N->getValueType(0), DAG, Subtarget,
25726 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
25727 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
25728 TargetLowering::DAGCombinerInfo &DCI,
25729 const X86Subtarget *Subtarget) {
25730 LoadSDNode *Ld = cast<LoadSDNode>(N);
25731 EVT RegVT = Ld->getValueType(0);
25732 EVT MemVT = Ld->getMemoryVT();
25734 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25736 // For chips with slow 32-byte unaligned loads, break the 32-byte operation
25737 // into two 16-byte operations.
25738 ISD::LoadExtType Ext = Ld->getExtensionType();
25740 unsigned AddressSpace = Ld->getAddressSpace();
25741 unsigned Alignment = Ld->getAlignment();
25742 if (RegVT.is256BitVector() && !DCI.isBeforeLegalizeOps() &&
25743 Ext == ISD::NON_EXTLOAD &&
25744 TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), RegVT,
25745 AddressSpace, Alignment, &Fast) && !Fast) {
25746 unsigned NumElems = RegVT.getVectorNumElements();
25750 SDValue Ptr = Ld->getBasePtr();
25751 SDValue Increment =
25752 DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
25754 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
25756 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
25757 Ld->getPointerInfo(), Ld->isVolatile(),
25758 Ld->isNonTemporal(), Ld->isInvariant(),
25760 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
25761 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
25762 Ld->getPointerInfo(), Ld->isVolatile(),
25763 Ld->isNonTemporal(), Ld->isInvariant(),
25764 std::min(16U, Alignment));
25765 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
25767 Load2.getValue(1));
25769 SDValue NewVec = DAG.getUNDEF(RegVT);
25770 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
25771 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
25772 return DCI.CombineTo(N, NewVec, TF, true);
25778 /// PerformMLOADCombine - Resolve extending loads
25779 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
25780 TargetLowering::DAGCombinerInfo &DCI,
25781 const X86Subtarget *Subtarget) {
25782 MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
25783 if (Mld->getExtensionType() != ISD::SEXTLOAD)
25786 EVT VT = Mld->getValueType(0);
25787 unsigned NumElems = VT.getVectorNumElements();
25788 EVT LdVT = Mld->getMemoryVT();
25791 assert(LdVT != VT && "Cannot extend to the same type");
25792 unsigned ToSz = VT.getVectorElementType().getSizeInBits();
25793 unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
25794 // From, To sizes and ElemCount must be pow of two
25795 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
25796 "Unexpected size for extending masked load");
25798 unsigned SizeRatio = ToSz / FromSz;
25799 assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
25801 // Create a type on which we perform the shuffle
25802 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
25803 LdVT.getScalarType(), NumElems*SizeRatio);
25804 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
25806 // Convert Src0 value
25807 SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
25808 if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
25809 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
25810 for (unsigned i = 0; i != NumElems; ++i)
25811 ShuffleVec[i] = i * SizeRatio;
25813 // Can't shuffle using an illegal type.
25814 assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
25815 "WideVecVT should be legal");
25816 WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
25817 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
25819 // Prepare the new mask
25821 SDValue Mask = Mld->getMask();
25822 if (Mask.getValueType() == VT) {
25823 // Mask and original value have the same type
25824 NewMask = DAG.getBitcast(WideVecVT, Mask);
25825 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
25826 for (unsigned i = 0; i != NumElems; ++i)
25827 ShuffleVec[i] = i * SizeRatio;
25828 for (unsigned i = NumElems; i != NumElems * SizeRatio; ++i)
25829 ShuffleVec[i] = NumElems * SizeRatio;
25830 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
25831 DAG.getConstant(0, dl, WideVecVT),
25835 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
25836 unsigned WidenNumElts = NumElems*SizeRatio;
25837 unsigned MaskNumElts = VT.getVectorNumElements();
25838 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
25841 unsigned NumConcat = WidenNumElts / MaskNumElts;
25842 SmallVector<SDValue, 16> Ops(NumConcat);
25843 SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
25845 for (unsigned i = 1; i != NumConcat; ++i)
25848 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
25851 SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
25852 Mld->getBasePtr(), NewMask, WideSrc0,
25853 Mld->getMemoryVT(), Mld->getMemOperand(),
25855 SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
25856 return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
25858 /// PerformMSTORECombine - Resolve truncating stores
25859 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
25860 const X86Subtarget *Subtarget) {
25861 MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
25862 if (!Mst->isTruncatingStore())
25865 EVT VT = Mst->getValue().getValueType();
25866 unsigned NumElems = VT.getVectorNumElements();
25867 EVT StVT = Mst->getMemoryVT();
25870 assert(StVT != VT && "Cannot truncate to the same type");
25871 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
25872 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
25874 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25876 // The truncating store is legal in some cases. For example
25877 // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
25878 // are designated for truncate store.
25879 // In this case we don't need any further transformations.
25880 if (TLI.isTruncStoreLegal(VT, StVT))
25883 // From, To sizes and ElemCount must be pow of two
25884 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
25885 "Unexpected size for truncating masked store");
25886 // We are going to use the original vector elt for storing.
25887 // Accumulated smaller vector elements must be a multiple of the store size.
25888 assert (((NumElems * FromSz) % ToSz) == 0 &&
25889 "Unexpected ratio for truncating masked store");
25891 unsigned SizeRatio = FromSz / ToSz;
25892 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
25894 // Create a type on which we perform the shuffle
25895 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
25896 StVT.getScalarType(), NumElems*SizeRatio);
25898 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
25900 SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
25901 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
25902 for (unsigned i = 0; i != NumElems; ++i)
25903 ShuffleVec[i] = i * SizeRatio;
25905 // Can't shuffle using an illegal type.
25906 assert(DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT) &&
25907 "WideVecVT should be legal");
25909 SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
25910 DAG.getUNDEF(WideVecVT),
25914 SDValue Mask = Mst->getMask();
25915 if (Mask.getValueType() == VT) {
25916 // Mask and original value have the same type
25917 NewMask = DAG.getBitcast(WideVecVT, Mask);
25918 for (unsigned i = 0; i != NumElems; ++i)
25919 ShuffleVec[i] = i * SizeRatio;
25920 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
25921 ShuffleVec[i] = NumElems*SizeRatio;
25922 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
25923 DAG.getConstant(0, dl, WideVecVT),
25927 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
25928 unsigned WidenNumElts = NumElems*SizeRatio;
25929 unsigned MaskNumElts = VT.getVectorNumElements();
25930 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
25933 unsigned NumConcat = WidenNumElts / MaskNumElts;
25934 SmallVector<SDValue, 16> Ops(NumConcat);
25935 SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
25937 for (unsigned i = 1; i != NumConcat; ++i)
25940 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
25943 return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal,
25944 Mst->getBasePtr(), NewMask, StVT,
25945 Mst->getMemOperand(), false);
25947 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
25948 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
25949 const X86Subtarget *Subtarget) {
25950 StoreSDNode *St = cast<StoreSDNode>(N);
25951 EVT VT = St->getValue().getValueType();
25952 EVT StVT = St->getMemoryVT();
25954 SDValue StoredVal = St->getOperand(1);
25955 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25957 // If we are saving a concatenation of two XMM registers and 32-byte stores
25958 // are slow, such as on Sandy Bridge, perform two 16-byte stores.
25960 unsigned AddressSpace = St->getAddressSpace();
25961 unsigned Alignment = St->getAlignment();
25962 if (VT.is256BitVector() && StVT == VT &&
25963 TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
25964 AddressSpace, Alignment, &Fast) && !Fast) {
25965 unsigned NumElems = VT.getVectorNumElements();
25969 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
25970 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
25973 DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
25974 SDValue Ptr0 = St->getBasePtr();
25975 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
25977 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
25978 St->getPointerInfo(), St->isVolatile(),
25979 St->isNonTemporal(), Alignment);
25980 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
25981 St->getPointerInfo(), St->isVolatile(),
25982 St->isNonTemporal(),
25983 std::min(16U, Alignment));
25984 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
25987 // Optimize trunc store (of multiple scalars) to shuffle and store.
25988 // First, pack all of the elements in one place. Next, store to memory
25989 // in fewer chunks.
25990 if (St->isTruncatingStore() && VT.isVector()) {
25991 // Check if we can detect an AVG pattern from the truncation. If yes,
25992 // replace the trunc store by a normal store with the result of X86ISD::AVG
25995 detectAVGPattern(St->getValue(), St->getMemoryVT(), DAG, Subtarget, dl);
25997 return DAG.getStore(St->getChain(), dl, Avg, St->getBasePtr(),
25998 St->getPointerInfo(), St->isVolatile(),
25999 St->isNonTemporal(), St->getAlignment());
26001 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26002 unsigned NumElems = VT.getVectorNumElements();
26003 assert(StVT != VT && "Cannot truncate to the same type");
26004 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
26005 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
26007 // The truncating store is legal in some cases. For example
26008 // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
26009 // are designated for truncate store.
26010 // In this case we don't need any further transformations.
26011 if (TLI.isTruncStoreLegal(VT, StVT))
26014 // From, To sizes and ElemCount must be pow of two
26015 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
26016 // We are going to use the original vector elt for storing.
26017 // Accumulated smaller vector elements must be a multiple of the store size.
26018 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
26020 unsigned SizeRatio = FromSz / ToSz;
26022 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
26024 // Create a type on which we perform the shuffle
26025 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
26026 StVT.getScalarType(), NumElems*SizeRatio);
26028 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
26030 SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
26031 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
26032 for (unsigned i = 0; i != NumElems; ++i)
26033 ShuffleVec[i] = i * SizeRatio;
26035 // Can't shuffle using an illegal type.
26036 if (!TLI.isTypeLegal(WideVecVT))
26039 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
26040 DAG.getUNDEF(WideVecVT),
26042 // At this point all of the data is stored at the bottom of the
26043 // register. We now need to save it to mem.
26045 // Find the largest store unit
26046 MVT StoreType = MVT::i8;
26047 for (MVT Tp : MVT::integer_valuetypes()) {
26048 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
26052 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
26053 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
26054 (64 <= NumElems * ToSz))
26055 StoreType = MVT::f64;
26057 // Bitcast the original vector into a vector of store-size units
26058 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
26059 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
26060 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
26061 SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
26062 SmallVector<SDValue, 8> Chains;
26063 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
26064 TLI.getPointerTy(DAG.getDataLayout()));
26065 SDValue Ptr = St->getBasePtr();
26067 // Perform one or more big stores into memory.
26068 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
26069 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
26070 StoreType, ShuffWide,
26071 DAG.getIntPtrConstant(i, dl));
26072 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
26073 St->getPointerInfo(), St->isVolatile(),
26074 St->isNonTemporal(), St->getAlignment());
26075 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
26076 Chains.push_back(Ch);
26079 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
26082 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
26083 // the FP state in cases where an emms may be missing.
26084 // A preferable solution to the general problem is to figure out the right
26085 // places to insert EMMS. This qualifies as a quick hack.
26087 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
26088 if (VT.getSizeInBits() != 64)
26091 const Function *F = DAG.getMachineFunction().getFunction();
26092 bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
26094 !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
26095 if ((VT.isVector() ||
26096 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
26097 isa<LoadSDNode>(St->getValue()) &&
26098 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
26099 St->getChain().hasOneUse() && !St->isVolatile()) {
26100 SDNode* LdVal = St->getValue().getNode();
26101 LoadSDNode *Ld = nullptr;
26102 int TokenFactorIndex = -1;
26103 SmallVector<SDValue, 8> Ops;
26104 SDNode* ChainVal = St->getChain().getNode();
26105 // Must be a store of a load. We currently handle two cases: the load
26106 // is a direct child, and it's under an intervening TokenFactor. It is
26107 // possible to dig deeper under nested TokenFactors.
26108 if (ChainVal == LdVal)
26109 Ld = cast<LoadSDNode>(St->getChain());
26110 else if (St->getValue().hasOneUse() &&
26111 ChainVal->getOpcode() == ISD::TokenFactor) {
26112 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
26113 if (ChainVal->getOperand(i).getNode() == LdVal) {
26114 TokenFactorIndex = i;
26115 Ld = cast<LoadSDNode>(St->getValue());
26117 Ops.push_back(ChainVal->getOperand(i));
26121 if (!Ld || !ISD::isNormalLoad(Ld))
26124 // If this is not the MMX case, i.e. we are just turning i64 load/store
26125 // into f64 load/store, avoid the transformation if there are multiple
26126 // uses of the loaded value.
26127 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
26132 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
26133 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
26135 if (Subtarget->is64Bit() || F64IsLegal) {
26136 MVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
26137 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
26138 Ld->getPointerInfo(), Ld->isVolatile(),
26139 Ld->isNonTemporal(), Ld->isInvariant(),
26140 Ld->getAlignment());
26141 SDValue NewChain = NewLd.getValue(1);
26142 if (TokenFactorIndex != -1) {
26143 Ops.push_back(NewChain);
26144 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
26146 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
26147 St->getPointerInfo(),
26148 St->isVolatile(), St->isNonTemporal(),
26149 St->getAlignment());
26152 // Otherwise, lower to two pairs of 32-bit loads / stores.
26153 SDValue LoAddr = Ld->getBasePtr();
26154 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
26155 DAG.getConstant(4, LdDL, MVT::i32));
26157 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
26158 Ld->getPointerInfo(),
26159 Ld->isVolatile(), Ld->isNonTemporal(),
26160 Ld->isInvariant(), Ld->getAlignment());
26161 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
26162 Ld->getPointerInfo().getWithOffset(4),
26163 Ld->isVolatile(), Ld->isNonTemporal(),
26165 MinAlign(Ld->getAlignment(), 4));
26167 SDValue NewChain = LoLd.getValue(1);
26168 if (TokenFactorIndex != -1) {
26169 Ops.push_back(LoLd);
26170 Ops.push_back(HiLd);
26171 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
26174 LoAddr = St->getBasePtr();
26175 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
26176 DAG.getConstant(4, StDL, MVT::i32));
26178 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
26179 St->getPointerInfo(),
26180 St->isVolatile(), St->isNonTemporal(),
26181 St->getAlignment());
26182 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
26183 St->getPointerInfo().getWithOffset(4),
26185 St->isNonTemporal(),
26186 MinAlign(St->getAlignment(), 4));
26187 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
26190 // This is similar to the above case, but here we handle a scalar 64-bit
26191 // integer store that is extracted from a vector on a 32-bit target.
26192 // If we have SSE2, then we can treat it like a floating-point double
26193 // to get past legalization. The execution dependencies fixup pass will
26194 // choose the optimal machine instruction for the store if this really is
26195 // an integer or v2f32 rather than an f64.
26196 if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
26197 St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
26198 SDValue OldExtract = St->getOperand(1);
26199 SDValue ExtOp0 = OldExtract.getOperand(0);
26200 unsigned VecSize = ExtOp0.getValueSizeInBits();
26201 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
26202 SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
26203 SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
26204 BitCast, OldExtract.getOperand(1));
26205 return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
26206 St->getPointerInfo(), St->isVolatile(),
26207 St->isNonTemporal(), St->getAlignment());
26213 /// Return 'true' if this vector operation is "horizontal"
26214 /// and return the operands for the horizontal operation in LHS and RHS. A
26215 /// horizontal operation performs the binary operation on successive elements
26216 /// of its first operand, then on successive elements of its second operand,
26217 /// returning the resulting values in a vector. For example, if
26218 /// A = < float a0, float a1, float a2, float a3 >
26220 /// B = < float b0, float b1, float b2, float b3 >
26221 /// then the result of doing a horizontal operation on A and B is
26222 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
26223 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
26224 /// A horizontal-op B, for some already available A and B, and if so then LHS is
26225 /// set to A, RHS to B, and the routine returns 'true'.
26226 /// Note that the binary operation should have the property that if one of the
26227 /// operands is UNDEF then the result is UNDEF.
26228 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
26229 // Look for the following pattern: if
26230 // A = < float a0, float a1, float a2, float a3 >
26231 // B = < float b0, float b1, float b2, float b3 >
26233 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
26234 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
26235 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
26236 // which is A horizontal-op B.
26238 // At least one of the operands should be a vector shuffle.
26239 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
26240 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
26243 MVT VT = LHS.getSimpleValueType();
26245 assert((VT.is128BitVector() || VT.is256BitVector()) &&
26246 "Unsupported vector type for horizontal add/sub");
26248 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
26249 // operate independently on 128-bit lanes.
26250 unsigned NumElts = VT.getVectorNumElements();
26251 unsigned NumLanes = VT.getSizeInBits()/128;
26252 unsigned NumLaneElts = NumElts / NumLanes;
26253 assert((NumLaneElts % 2 == 0) &&
26254 "Vector type should have an even number of elements in each lane");
26255 unsigned HalfLaneElts = NumLaneElts/2;
26257 // View LHS in the form
26258 // LHS = VECTOR_SHUFFLE A, B, LMask
26259 // If LHS is not a shuffle then pretend it is the shuffle
26260 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
26261 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
26264 SmallVector<int, 16> LMask(NumElts);
26265 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
26266 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
26267 A = LHS.getOperand(0);
26268 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
26269 B = LHS.getOperand(1);
26270 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
26271 std::copy(Mask.begin(), Mask.end(), LMask.begin());
26273 if (LHS.getOpcode() != ISD::UNDEF)
26275 for (unsigned i = 0; i != NumElts; ++i)
26279 // Likewise, view RHS in the form
26280 // RHS = VECTOR_SHUFFLE C, D, RMask
26282 SmallVector<int, 16> RMask(NumElts);
26283 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
26284 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
26285 C = RHS.getOperand(0);
26286 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
26287 D = RHS.getOperand(1);
26288 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
26289 std::copy(Mask.begin(), Mask.end(), RMask.begin());
26291 if (RHS.getOpcode() != ISD::UNDEF)
26293 for (unsigned i = 0; i != NumElts; ++i)
26297 // Check that the shuffles are both shuffling the same vectors.
26298 if (!(A == C && B == D) && !(A == D && B == C))
26301 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
26302 if (!A.getNode() && !B.getNode())
26305 // If A and B occur in reverse order in RHS, then "swap" them (which means
26306 // rewriting the mask).
26308 ShuffleVectorSDNode::commuteMask(RMask);
26310 // At this point LHS and RHS are equivalent to
26311 // LHS = VECTOR_SHUFFLE A, B, LMask
26312 // RHS = VECTOR_SHUFFLE A, B, RMask
26313 // Check that the masks correspond to performing a horizontal operation.
26314 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
26315 for (unsigned i = 0; i != NumLaneElts; ++i) {
26316 int LIdx = LMask[i+l], RIdx = RMask[i+l];
26318 // Ignore any UNDEF components.
26319 if (LIdx < 0 || RIdx < 0 ||
26320 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
26321 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
26324 // Check that successive elements are being operated on. If not, this is
26325 // not a horizontal operation.
26326 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
26327 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
26328 if (!(LIdx == Index && RIdx == Index + 1) &&
26329 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
26334 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
26335 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
26339 /// Do target-specific dag combines on floating point adds.
26340 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
26341 const X86Subtarget *Subtarget) {
26342 EVT VT = N->getValueType(0);
26343 SDValue LHS = N->getOperand(0);
26344 SDValue RHS = N->getOperand(1);
26346 // Try to synthesize horizontal adds from adds of shuffles.
26347 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
26348 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
26349 isHorizontalBinOp(LHS, RHS, true))
26350 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
26354 /// Do target-specific dag combines on floating point subs.
26355 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
26356 const X86Subtarget *Subtarget) {
26357 EVT VT = N->getValueType(0);
26358 SDValue LHS = N->getOperand(0);
26359 SDValue RHS = N->getOperand(1);
26361 // Try to synthesize horizontal subs from subs of shuffles.
26362 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
26363 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
26364 isHorizontalBinOp(LHS, RHS, false))
26365 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
26369 /// Do target-specific dag combines on floating point negations.
26370 static SDValue PerformFNEGCombine(SDNode *N, SelectionDAG &DAG,
26371 const X86Subtarget *Subtarget) {
26372 EVT VT = N->getValueType(0);
26373 EVT SVT = VT.getScalarType();
26374 SDValue Arg = N->getOperand(0);
26377 // Let legalize expand this if it isn't a legal type yet.
26378 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
26381 // If we're negating a FMUL node on a target with FMA, then we can avoid the
26382 // use of a constant by performing (-0 - A*B) instead.
26383 // FIXME: Check rounding control flags as well once it becomes available.
26384 if (Arg.getOpcode() == ISD::FMUL && (SVT == MVT::f32 || SVT == MVT::f64) &&
26385 Arg->getFlags()->hasNoSignedZeros() && Subtarget->hasAnyFMA()) {
26386 SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
26387 return DAG.getNode(X86ISD::FNMSUB, DL, VT, Arg.getOperand(0),
26388 Arg.getOperand(1), Zero);
26391 // If we're negating a FMA node, then we can adjust the
26392 // instruction to include the extra negation.
26393 if (Arg.hasOneUse()) {
26394 switch (Arg.getOpcode()) {
26395 case X86ISD::FMADD:
26396 return DAG.getNode(X86ISD::FNMSUB, DL, VT, Arg.getOperand(0),
26397 Arg.getOperand(1), Arg.getOperand(2));
26398 case X86ISD::FMSUB:
26399 return DAG.getNode(X86ISD::FNMADD, DL, VT, Arg.getOperand(0),
26400 Arg.getOperand(1), Arg.getOperand(2));
26401 case X86ISD::FNMADD:
26402 return DAG.getNode(X86ISD::FMSUB, DL, VT, Arg.getOperand(0),
26403 Arg.getOperand(1), Arg.getOperand(2));
26404 case X86ISD::FNMSUB:
26405 return DAG.getNode(X86ISD::FMADD, DL, VT, Arg.getOperand(0),
26406 Arg.getOperand(1), Arg.getOperand(2));
26412 static SDValue lowerX86FPLogicOp(SDNode *N, SelectionDAG &DAG,
26413 const X86Subtarget *Subtarget) {
26414 EVT VT = N->getValueType(0);
26415 if (VT.is512BitVector() && !Subtarget->hasDQI()) {
26416 // VXORPS, VORPS, VANDPS, VANDNPS are supported only under DQ extention.
26417 // These logic operations may be executed in the integer domain.
26419 MVT IntScalar = MVT::getIntegerVT(VT.getScalarSizeInBits());
26420 MVT IntVT = MVT::getVectorVT(IntScalar, VT.getVectorNumElements());
26422 SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(0));
26423 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, IntVT, N->getOperand(1));
26424 unsigned IntOpcode = 0;
26425 switch (N->getOpcode()) {
26426 default: llvm_unreachable("Unexpected FP logic op");
26427 case X86ISD::FOR: IntOpcode = ISD::OR; break;
26428 case X86ISD::FXOR: IntOpcode = ISD::XOR; break;
26429 case X86ISD::FAND: IntOpcode = ISD::AND; break;
26430 case X86ISD::FANDN: IntOpcode = X86ISD::ANDNP; break;
26432 SDValue IntOp = DAG.getNode(IntOpcode, dl, IntVT, Op0, Op1);
26433 return DAG.getNode(ISD::BITCAST, dl, VT, IntOp);
26437 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
26438 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG,
26439 const X86Subtarget *Subtarget) {
26440 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
26442 // F[X]OR(0.0, x) -> x
26443 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
26444 if (C->getValueAPF().isPosZero())
26445 return N->getOperand(1);
26447 // F[X]OR(x, 0.0) -> x
26448 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
26449 if (C->getValueAPF().isPosZero())
26450 return N->getOperand(0);
26452 return lowerX86FPLogicOp(N, DAG, Subtarget);
26455 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
26456 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
26457 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
26459 // Only perform optimizations if UnsafeMath is used.
26460 if (!DAG.getTarget().Options.UnsafeFPMath)
26463 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
26464 // into FMINC and FMAXC, which are Commutative operations.
26465 unsigned NewOp = 0;
26466 switch (N->getOpcode()) {
26467 default: llvm_unreachable("unknown opcode");
26468 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
26469 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
26472 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
26473 N->getOperand(0), N->getOperand(1));
26476 /// Do target-specific dag combines on X86ISD::FAND nodes.
26477 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG,
26478 const X86Subtarget *Subtarget) {
26479 // FAND(0.0, x) -> 0.0
26480 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
26481 if (C->getValueAPF().isPosZero())
26482 return N->getOperand(0);
26484 // FAND(x, 0.0) -> 0.0
26485 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
26486 if (C->getValueAPF().isPosZero())
26487 return N->getOperand(1);
26489 return lowerX86FPLogicOp(N, DAG, Subtarget);
26492 /// Do target-specific dag combines on X86ISD::FANDN nodes
26493 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG,
26494 const X86Subtarget *Subtarget) {
26495 // FANDN(0.0, x) -> x
26496 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
26497 if (C->getValueAPF().isPosZero())
26498 return N->getOperand(1);
26500 // FANDN(x, 0.0) -> 0.0
26501 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
26502 if (C->getValueAPF().isPosZero())
26503 return N->getOperand(1);
26505 return lowerX86FPLogicOp(N, DAG, Subtarget);
26508 static SDValue PerformBTCombine(SDNode *N,
26510 TargetLowering::DAGCombinerInfo &DCI) {
26511 // BT ignores high bits in the bit index operand.
26512 SDValue Op1 = N->getOperand(1);
26513 if (Op1.hasOneUse()) {
26514 unsigned BitWidth = Op1.getValueSizeInBits();
26515 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
26516 APInt KnownZero, KnownOne;
26517 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
26518 !DCI.isBeforeLegalizeOps());
26519 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
26520 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
26521 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
26522 DCI.CommitTargetLoweringOpt(TLO);
26527 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
26528 SDValue Op = N->getOperand(0);
26529 if (Op.getOpcode() == ISD::BITCAST)
26530 Op = Op.getOperand(0);
26531 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
26532 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
26533 VT.getVectorElementType().getSizeInBits() ==
26534 OpVT.getVectorElementType().getSizeInBits()) {
26535 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
26540 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
26541 const X86Subtarget *Subtarget) {
26542 EVT VT = N->getValueType(0);
26543 if (!VT.isVector())
26546 SDValue N0 = N->getOperand(0);
26547 SDValue N1 = N->getOperand(1);
26548 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
26551 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
26552 // both SSE and AVX2 since there is no sign-extended shift right
26553 // operation on a vector with 64-bit elements.
26554 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
26555 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
26556 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
26557 N0.getOpcode() == ISD::SIGN_EXTEND)) {
26558 SDValue N00 = N0.getOperand(0);
26560 // EXTLOAD has a better solution on AVX2,
26561 // it may be replaced with X86ISD::VSEXT node.
26562 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
26563 if (!ISD::isNormalLoad(N00.getNode()))
26566 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
26567 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
26569 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
26575 /// sext(add_nsw(x, C)) --> add(sext(x), C_sext)
26576 /// Promoting a sign extension ahead of an 'add nsw' exposes opportunities
26577 /// to combine math ops, use an LEA, or use a complex addressing mode. This can
26578 /// eliminate extend, add, and shift instructions.
26579 static SDValue promoteSextBeforeAddNSW(SDNode *Sext, SelectionDAG &DAG,
26580 const X86Subtarget *Subtarget) {
26581 // TODO: This should be valid for other integer types.
26582 EVT VT = Sext->getValueType(0);
26583 if (VT != MVT::i64)
26586 // We need an 'add nsw' feeding into the 'sext'.
26587 SDValue Add = Sext->getOperand(0);
26588 if (Add.getOpcode() != ISD::ADD || !Add->getFlags()->hasNoSignedWrap())
26591 // Having a constant operand to the 'add' ensures that we are not increasing
26592 // the instruction count because the constant is extended for free below.
26593 // A constant operand can also become the displacement field of an LEA.
26594 auto *AddOp1 = dyn_cast<ConstantSDNode>(Add.getOperand(1));
26598 // Don't make the 'add' bigger if there's no hope of combining it with some
26599 // other 'add' or 'shl' instruction.
26600 // TODO: It may be profitable to generate simpler LEA instructions in place
26601 // of single 'add' instructions, but the cost model for selecting an LEA
26602 // currently has a high threshold.
26603 bool HasLEAPotential = false;
26604 for (auto *User : Sext->uses()) {
26605 if (User->getOpcode() == ISD::ADD || User->getOpcode() == ISD::SHL) {
26606 HasLEAPotential = true;
26610 if (!HasLEAPotential)
26613 // Everything looks good, so pull the 'sext' ahead of the 'add'.
26614 int64_t AddConstant = AddOp1->getSExtValue();
26615 SDValue AddOp0 = Add.getOperand(0);
26616 SDValue NewSext = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(Sext), VT, AddOp0);
26617 SDValue NewConstant = DAG.getConstant(AddConstant, SDLoc(Add), VT);
26619 // The wider add is guaranteed to not wrap because both operands are
26622 Flags.setNoSignedWrap(true);
26623 return DAG.getNode(ISD::ADD, SDLoc(Add), VT, NewSext, NewConstant, &Flags);
26626 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
26627 TargetLowering::DAGCombinerInfo &DCI,
26628 const X86Subtarget *Subtarget) {
26629 SDValue N0 = N->getOperand(0);
26630 EVT VT = N->getValueType(0);
26631 EVT SVT = VT.getScalarType();
26632 EVT InVT = N0.getValueType();
26633 EVT InSVT = InVT.getScalarType();
26636 // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
26637 // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
26638 // This exposes the sext to the sdivrem lowering, so that it directly extends
26639 // from AH (which we otherwise need to do contortions to access).
26640 if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
26641 InVT == MVT::i8 && VT == MVT::i32) {
26642 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
26643 SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
26644 N0.getOperand(0), N0.getOperand(1));
26645 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
26646 return R.getValue(1);
26649 if (!DCI.isBeforeLegalizeOps()) {
26650 if (InVT == MVT::i1) {
26651 SDValue Zero = DAG.getConstant(0, DL, VT);
26653 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
26654 return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
26659 if (VT.isVector() && Subtarget->hasSSE2()) {
26660 auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
26661 EVT InVT = N.getValueType();
26662 EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
26663 Size / InVT.getScalarSizeInBits());
26664 SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
26665 DAG.getUNDEF(InVT));
26667 return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
26670 // If target-size is less than 128-bits, extend to a type that would extend
26671 // to 128 bits, extend that and extract the original target vector.
26672 if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
26673 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
26674 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
26675 unsigned Scale = 128 / VT.getSizeInBits();
26677 EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
26678 SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
26679 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
26680 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
26681 DAG.getIntPtrConstant(0, DL));
26684 // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
26685 // which ensures lowering to X86ISD::VSEXT (pmovsx*).
26686 if (VT.getSizeInBits() == 128 &&
26687 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
26688 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
26689 SDValue ExOp = ExtendVecSize(DL, N0, 128);
26690 return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
26693 // On pre-AVX2 targets, split into 128-bit nodes of
26694 // ISD::SIGN_EXTEND_VECTOR_INREG.
26695 if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
26696 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
26697 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
26698 unsigned NumVecs = VT.getSizeInBits() / 128;
26699 unsigned NumSubElts = 128 / SVT.getSizeInBits();
26700 EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
26701 EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
26703 SmallVector<SDValue, 8> Opnds;
26704 for (unsigned i = 0, Offset = 0; i != NumVecs;
26705 ++i, Offset += NumSubElts) {
26706 SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
26707 DAG.getIntPtrConstant(Offset, DL));
26708 SrcVec = ExtendVecSize(DL, SrcVec, 128);
26709 SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
26710 Opnds.push_back(SrcVec);
26712 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
26716 if (Subtarget->hasAVX() && VT.is256BitVector())
26717 if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
26720 if (SDValue NewAdd = promoteSextBeforeAddNSW(N, DAG, Subtarget))
26726 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
26727 const X86Subtarget* Subtarget) {
26729 EVT VT = N->getValueType(0);
26731 // Let legalize expand this if it isn't a legal type yet.
26732 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
26735 EVT ScalarVT = VT.getScalarType();
26736 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) || !Subtarget->hasAnyFMA())
26739 SDValue A = N->getOperand(0);
26740 SDValue B = N->getOperand(1);
26741 SDValue C = N->getOperand(2);
26743 bool NegA = (A.getOpcode() == ISD::FNEG);
26744 bool NegB = (B.getOpcode() == ISD::FNEG);
26745 bool NegC = (C.getOpcode() == ISD::FNEG);
26747 // Negative multiplication when NegA xor NegB
26748 bool NegMul = (NegA != NegB);
26750 A = A.getOperand(0);
26752 B = B.getOperand(0);
26754 C = C.getOperand(0);
26758 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
26760 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
26762 return DAG.getNode(Opcode, dl, VT, A, B, C);
26765 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
26766 TargetLowering::DAGCombinerInfo &DCI,
26767 const X86Subtarget *Subtarget) {
26768 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
26769 // (and (i32 x86isd::setcc_carry), 1)
26770 // This eliminates the zext. This transformation is necessary because
26771 // ISD::SETCC is always legalized to i8.
26773 SDValue N0 = N->getOperand(0);
26774 EVT VT = N->getValueType(0);
26776 if (N0.getOpcode() == ISD::AND &&
26778 N0.getOperand(0).hasOneUse()) {
26779 SDValue N00 = N0.getOperand(0);
26780 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
26781 if (!isOneConstant(N0.getOperand(1)))
26783 return DAG.getNode(ISD::AND, dl, VT,
26784 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
26785 N00.getOperand(0), N00.getOperand(1)),
26786 DAG.getConstant(1, dl, VT));
26790 if (N0.getOpcode() == ISD::TRUNCATE &&
26792 N0.getOperand(0).hasOneUse()) {
26793 SDValue N00 = N0.getOperand(0);
26794 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
26795 return DAG.getNode(ISD::AND, dl, VT,
26796 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
26797 N00.getOperand(0), N00.getOperand(1)),
26798 DAG.getConstant(1, dl, VT));
26802 if (VT.is256BitVector())
26803 if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
26806 // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
26807 // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
26808 // This exposes the zext to the udivrem lowering, so that it directly extends
26809 // from AH (which we otherwise need to do contortions to access).
26810 if (N0.getOpcode() == ISD::UDIVREM &&
26811 N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
26812 (VT == MVT::i32 || VT == MVT::i64)) {
26813 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
26814 SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
26815 N0.getOperand(0), N0.getOperand(1));
26816 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
26817 return R.getValue(1);
26823 // Optimize x == -y --> x+y == 0
26824 // x != -y --> x+y != 0
26825 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
26826 const X86Subtarget* Subtarget) {
26827 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
26828 SDValue LHS = N->getOperand(0);
26829 SDValue RHS = N->getOperand(1);
26830 EVT VT = N->getValueType(0);
26833 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
26834 if (isNullConstant(LHS.getOperand(0)) && LHS.hasOneUse()) {
26835 SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
26836 LHS.getOperand(1));
26837 return DAG.getSetCC(DL, N->getValueType(0), addV,
26838 DAG.getConstant(0, DL, addV.getValueType()), CC);
26840 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
26841 if (isNullConstant(RHS.getOperand(0)) && RHS.hasOneUse()) {
26842 SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
26843 RHS.getOperand(1));
26844 return DAG.getSetCC(DL, N->getValueType(0), addV,
26845 DAG.getConstant(0, DL, addV.getValueType()), CC);
26848 if (VT.getScalarType() == MVT::i1 &&
26849 (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
26851 (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
26852 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
26853 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
26855 if (!IsSEXT0 || !IsVZero1) {
26856 // Swap the operands and update the condition code.
26857 std::swap(LHS, RHS);
26858 CC = ISD::getSetCCSwappedOperands(CC);
26860 IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
26861 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
26862 IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
26865 if (IsSEXT0 && IsVZero1) {
26866 assert(VT == LHS.getOperand(0).getValueType() &&
26867 "Uexpected operand type");
26868 if (CC == ISD::SETGT)
26869 return DAG.getConstant(0, DL, VT);
26870 if (CC == ISD::SETLE)
26871 return DAG.getConstant(1, DL, VT);
26872 if (CC == ISD::SETEQ || CC == ISD::SETGE)
26873 return DAG.getNOT(DL, LHS.getOperand(0), VT);
26875 assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
26876 "Unexpected condition code!");
26877 return LHS.getOperand(0);
26884 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
26885 SDValue V0 = N->getOperand(0);
26886 SDValue V1 = N->getOperand(1);
26888 EVT VT = N->getValueType(0);
26890 // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
26891 // operands and changing the mask to 1. This saves us a bunch of
26892 // pattern-matching possibilities related to scalar math ops in SSE/AVX.
26893 // x86InstrInfo knows how to commute this back after instruction selection
26894 // if it would help register allocation.
26896 // TODO: If optimizing for size or a processor that doesn't suffer from
26897 // partial register update stalls, this should be transformed into a MOVSD
26898 // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
26900 if (VT == MVT::v2f64)
26901 if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
26902 if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
26903 SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
26904 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
26910 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
26911 // as "sbb reg,reg", since it can be extended without zext and produces
26912 // an all-ones bit which is more useful than 0/1 in some cases.
26913 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
26916 return DAG.getNode(ISD::AND, DL, VT,
26917 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
26918 DAG.getConstant(X86::COND_B, DL, MVT::i8),
26920 DAG.getConstant(1, DL, VT));
26921 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
26922 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
26923 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
26924 DAG.getConstant(X86::COND_B, DL, MVT::i8),
26928 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
26929 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
26930 TargetLowering::DAGCombinerInfo &DCI,
26931 const X86Subtarget *Subtarget) {
26933 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
26934 SDValue EFLAGS = N->getOperand(1);
26936 if (CC == X86::COND_A) {
26937 // Try to convert COND_A into COND_B in an attempt to facilitate
26938 // materializing "setb reg".
26940 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
26941 // cannot take an immediate as its first operand.
26943 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
26944 EFLAGS.getValueType().isInteger() &&
26945 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
26946 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
26947 EFLAGS.getNode()->getVTList(),
26948 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
26949 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
26950 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
26954 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
26955 // a zext and produces an all-ones bit which is more useful than 0/1 in some
26957 if (CC == X86::COND_B)
26958 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
26960 if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
26961 SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
26962 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
26968 // Optimize branch condition evaluation.
26970 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
26971 TargetLowering::DAGCombinerInfo &DCI,
26972 const X86Subtarget *Subtarget) {
26974 SDValue Chain = N->getOperand(0);
26975 SDValue Dest = N->getOperand(1);
26976 SDValue EFLAGS = N->getOperand(3);
26977 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
26979 if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
26980 SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
26981 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
26988 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
26989 SelectionDAG &DAG) {
26990 // Take advantage of vector comparisons producing 0 or -1 in each lane to
26991 // optimize away operation when it's from a constant.
26993 // The general transformation is:
26994 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
26995 // AND(VECTOR_CMP(x,y), constant2)
26996 // constant2 = UNARYOP(constant)
26998 // Early exit if this isn't a vector operation, the operand of the
26999 // unary operation isn't a bitwise AND, or if the sizes of the operations
27000 // aren't the same.
27001 EVT VT = N->getValueType(0);
27002 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
27003 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
27004 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
27007 // Now check that the other operand of the AND is a constant. We could
27008 // make the transformation for non-constant splats as well, but it's unclear
27009 // that would be a benefit as it would not eliminate any operations, just
27010 // perform one more step in scalar code before moving to the vector unit.
27011 if (BuildVectorSDNode *BV =
27012 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
27013 // Bail out if the vector isn't a constant.
27014 if (!BV->isConstant())
27017 // Everything checks out. Build up the new and improved node.
27019 EVT IntVT = BV->getValueType(0);
27020 // Create a new constant of the appropriate type for the transformed
27022 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
27023 // The AND node needs bitcasts to/from an integer vector type around it.
27024 SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
27025 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
27026 N->getOperand(0)->getOperand(0), MaskConst);
27027 SDValue Res = DAG.getBitcast(VT, NewAnd);
27034 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
27035 const X86Subtarget *Subtarget) {
27036 SDValue Op0 = N->getOperand(0);
27037 EVT VT = N->getValueType(0);
27038 EVT InVT = Op0.getValueType();
27039 EVT InSVT = InVT.getScalarType();
27040 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
27042 // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
27043 // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
27044 if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
27046 EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
27047 InVT.getVectorNumElements());
27048 SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
27050 if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
27051 return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
27053 return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
27059 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
27060 const X86Subtarget *Subtarget) {
27061 // First try to optimize away the conversion entirely when it's
27062 // conditionally from a constant. Vectors only.
27063 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
27066 // Now move on to more general possibilities.
27067 SDValue Op0 = N->getOperand(0);
27068 EVT VT = N->getValueType(0);
27069 EVT InVT = Op0.getValueType();
27070 EVT InSVT = InVT.getScalarType();
27072 // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
27073 // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
27074 if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
27076 EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
27077 InVT.getVectorNumElements());
27078 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
27079 return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
27082 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
27083 // a 32-bit target where SSE doesn't support i64->FP operations.
27084 if (!Subtarget->useSoftFloat() && Op0.getOpcode() == ISD::LOAD) {
27085 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
27086 EVT LdVT = Ld->getValueType(0);
27088 // This transformation is not supported if the result type is f16
27089 if (VT == MVT::f16)
27092 if (!Ld->isVolatile() && !VT.isVector() &&
27093 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
27094 !Subtarget->is64Bit() && LdVT == MVT::i64) {
27095 SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
27096 SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
27097 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
27104 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
27105 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
27106 X86TargetLowering::DAGCombinerInfo &DCI) {
27107 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
27108 // the result is either zero or one (depending on the input carry bit).
27109 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
27110 if (X86::isZeroNode(N->getOperand(0)) &&
27111 X86::isZeroNode(N->getOperand(1)) &&
27112 // We don't have a good way to replace an EFLAGS use, so only do this when
27114 SDValue(N, 1).use_empty()) {
27116 EVT VT = N->getValueType(0);
27117 SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
27118 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
27119 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
27120 DAG.getConstant(X86::COND_B, DL,
27123 DAG.getConstant(1, DL, VT));
27124 return DCI.CombineTo(N, Res1, CarryOut);
27130 // fold (add Y, (sete X, 0)) -> adc 0, Y
27131 // (add Y, (setne X, 0)) -> sbb -1, Y
27132 // (sub (sete X, 0), Y) -> sbb 0, Y
27133 // (sub (setne X, 0), Y) -> adc -1, Y
27134 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
27137 // Look through ZExts.
27138 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
27139 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
27142 SDValue SetCC = Ext.getOperand(0);
27143 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
27146 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
27147 if (CC != X86::COND_E && CC != X86::COND_NE)
27150 SDValue Cmp = SetCC.getOperand(1);
27151 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
27152 !X86::isZeroNode(Cmp.getOperand(1)) ||
27153 !Cmp.getOperand(0).getValueType().isInteger())
27156 SDValue CmpOp0 = Cmp.getOperand(0);
27157 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
27158 DAG.getConstant(1, DL, CmpOp0.getValueType()));
27160 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
27161 if (CC == X86::COND_NE)
27162 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
27163 DL, OtherVal.getValueType(), OtherVal,
27164 DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
27166 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
27167 DL, OtherVal.getValueType(), OtherVal,
27168 DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
27171 /// PerformADDCombine - Do target-specific dag combines on integer adds.
27172 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
27173 const X86Subtarget *Subtarget) {
27174 EVT VT = N->getValueType(0);
27175 SDValue Op0 = N->getOperand(0);
27176 SDValue Op1 = N->getOperand(1);
27178 // Try to synthesize horizontal adds from adds of shuffles.
27179 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
27180 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
27181 isHorizontalBinOp(Op0, Op1, true))
27182 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
27184 return OptimizeConditionalInDecrement(N, DAG);
27187 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
27188 const X86Subtarget *Subtarget) {
27189 SDValue Op0 = N->getOperand(0);
27190 SDValue Op1 = N->getOperand(1);
27192 // X86 can't encode an immediate LHS of a sub. See if we can push the
27193 // negation into a preceding instruction.
27194 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
27195 // If the RHS of the sub is a XOR with one use and a constant, invert the
27196 // immediate. Then add one to the LHS of the sub so we can turn
27197 // X-Y -> X+~Y+1, saving one register.
27198 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
27199 isa<ConstantSDNode>(Op1.getOperand(1))) {
27200 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
27201 EVT VT = Op0.getValueType();
27202 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
27204 DAG.getConstant(~XorC, SDLoc(Op1), VT));
27205 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
27206 DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
27210 // Try to synthesize horizontal adds from adds of shuffles.
27211 EVT VT = N->getValueType(0);
27212 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
27213 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
27214 isHorizontalBinOp(Op0, Op1, true))
27215 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
27217 return OptimizeConditionalInDecrement(N, DAG);
27220 /// performVZEXTCombine - Performs build vector combines
27221 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
27222 TargetLowering::DAGCombinerInfo &DCI,
27223 const X86Subtarget *Subtarget) {
27225 MVT VT = N->getSimpleValueType(0);
27226 SDValue Op = N->getOperand(0);
27227 MVT OpVT = Op.getSimpleValueType();
27228 MVT OpEltVT = OpVT.getVectorElementType();
27229 unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
27231 // (vzext (bitcast (vzext (x)) -> (vzext x)
27233 while (V.getOpcode() == ISD::BITCAST)
27234 V = V.getOperand(0);
27236 if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
27237 MVT InnerVT = V.getSimpleValueType();
27238 MVT InnerEltVT = InnerVT.getVectorElementType();
27240 // If the element sizes match exactly, we can just do one larger vzext. This
27241 // is always an exact type match as vzext operates on integer types.
27242 if (OpEltVT == InnerEltVT) {
27243 assert(OpVT == InnerVT && "Types must match for vzext!");
27244 return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
27247 // The only other way we can combine them is if only a single element of the
27248 // inner vzext is used in the input to the outer vzext.
27249 if (InnerEltVT.getSizeInBits() < InputBits)
27252 // In this case, the inner vzext is completely dead because we're going to
27253 // only look at bits inside of the low element. Just do the outer vzext on
27254 // a bitcast of the input to the inner.
27255 return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
27258 // Check if we can bypass extracting and re-inserting an element of an input
27259 // vector. Essentially:
27260 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
27261 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
27262 V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
27263 V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
27264 SDValue ExtractedV = V.getOperand(0);
27265 SDValue OrigV = ExtractedV.getOperand(0);
27266 if (isNullConstant(ExtractedV.getOperand(1))) {
27267 MVT OrigVT = OrigV.getSimpleValueType();
27268 // Extract a subvector if necessary...
27269 if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
27270 int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
27271 OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
27272 OrigVT.getVectorNumElements() / Ratio);
27273 OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
27274 DAG.getIntPtrConstant(0, DL));
27276 Op = DAG.getBitcast(OpVT, OrigV);
27277 return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
27284 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
27285 DAGCombinerInfo &DCI) const {
27286 SelectionDAG &DAG = DCI.DAG;
27287 switch (N->getOpcode()) {
27289 case ISD::EXTRACT_VECTOR_ELT:
27290 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
27293 case X86ISD::SHRUNKBLEND:
27294 return PerformSELECTCombine(N, DAG, DCI, Subtarget);
27295 case ISD::BITCAST: return PerformBITCASTCombine(N, DAG, Subtarget);
27296 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
27297 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
27298 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
27299 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
27300 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
27303 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
27304 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
27305 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
27306 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
27307 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
27308 case ISD::MLOAD: return PerformMLOADCombine(N, DAG, DCI, Subtarget);
27309 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
27310 case ISD::MSTORE: return PerformMSTORECombine(N, DAG, Subtarget);
27311 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
27312 case ISD::UINT_TO_FP: return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
27313 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
27314 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
27315 case ISD::FNEG: return PerformFNEGCombine(N, DAG, Subtarget);
27316 case ISD::TRUNCATE: return PerformTRUNCATECombine(N, DAG, Subtarget);
27318 case X86ISD::FOR: return PerformFORCombine(N, DAG, Subtarget);
27320 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
27321 case X86ISD::FAND: return PerformFANDCombine(N, DAG, Subtarget);
27322 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG, Subtarget);
27323 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
27324 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
27325 case ISD::ANY_EXTEND:
27326 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
27327 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
27328 case ISD::SIGN_EXTEND_INREG:
27329 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
27330 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
27331 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
27332 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
27333 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
27334 case X86ISD::SHUFP: // Handle all target specific shuffles
27335 case X86ISD::PALIGNR:
27336 case X86ISD::UNPCKH:
27337 case X86ISD::UNPCKL:
27338 case X86ISD::MOVHLPS:
27339 case X86ISD::MOVLHPS:
27340 case X86ISD::PSHUFB:
27341 case X86ISD::PSHUFD:
27342 case X86ISD::PSHUFHW:
27343 case X86ISD::PSHUFLW:
27344 case X86ISD::MOVSS:
27345 case X86ISD::MOVSD:
27346 case X86ISD::VPERMILPI:
27347 case X86ISD::VPERM2X128:
27348 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
27349 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
27350 case X86ISD::BLENDI: return PerformBLENDICombine(N, DAG);
27356 /// isTypeDesirableForOp - Return true if the target has native support for
27357 /// the specified value type and it is 'desirable' to use the type for the
27358 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
27359 /// instruction encodings are longer and some i16 instructions are slow.
27360 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
27361 if (!isTypeLegal(VT))
27363 if (VT != MVT::i16)
27370 case ISD::SIGN_EXTEND:
27371 case ISD::ZERO_EXTEND:
27372 case ISD::ANY_EXTEND:
27385 /// IsDesirableToPromoteOp - This method query the target whether it is
27386 /// beneficial for dag combiner to promote the specified node. If true, it
27387 /// should return the desired promotion type by reference.
27388 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
27389 EVT VT = Op.getValueType();
27390 if (VT != MVT::i16)
27393 bool Promote = false;
27394 bool Commute = false;
27395 switch (Op.getOpcode()) {
27398 LoadSDNode *LD = cast<LoadSDNode>(Op);
27399 // If the non-extending load has a single use and it's not live out, then it
27400 // might be folded.
27401 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
27402 Op.hasOneUse()*/) {
27403 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
27404 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
27405 // The only case where we'd want to promote LOAD (rather then it being
27406 // promoted as an operand is when it's only use is liveout.
27407 if (UI->getOpcode() != ISD::CopyToReg)
27414 case ISD::SIGN_EXTEND:
27415 case ISD::ZERO_EXTEND:
27416 case ISD::ANY_EXTEND:
27421 SDValue N0 = Op.getOperand(0);
27422 // Look out for (store (shl (load), x)).
27423 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
27436 SDValue N0 = Op.getOperand(0);
27437 SDValue N1 = Op.getOperand(1);
27438 if (!Commute && MayFoldLoad(N1))
27440 // Avoid disabling potential load folding opportunities.
27441 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
27443 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
27453 //===----------------------------------------------------------------------===//
27454 // X86 Inline Assembly Support
27455 //===----------------------------------------------------------------------===//
27457 // Helper to match a string separated by whitespace.
27458 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
27459 S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
27461 for (StringRef Piece : Pieces) {
27462 if (!S.startswith(Piece)) // Check if the piece matches.
27465 S = S.substr(Piece.size());
27466 StringRef::size_type Pos = S.find_first_not_of(" \t");
27467 if (Pos == 0) // We matched a prefix.
27476 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
27478 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
27479 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
27480 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
27481 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
27483 if (AsmPieces.size() == 3)
27485 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
27492 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
27493 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
27495 std::string AsmStr = IA->getAsmString();
27497 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
27498 if (!Ty || Ty->getBitWidth() % 16 != 0)
27501 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
27502 SmallVector<StringRef, 4> AsmPieces;
27503 SplitString(AsmStr, AsmPieces, ";\n");
27505 switch (AsmPieces.size()) {
27506 default: return false;
27508 // FIXME: this should verify that we are targeting a 486 or better. If not,
27509 // we will turn this bswap into something that will be lowered to logical
27510 // ops instead of emitting the bswap asm. For now, we don't support 486 or
27511 // lower so don't worry about this.
27513 if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
27514 matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
27515 matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
27516 matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
27517 matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
27518 matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
27519 // No need to check constraints, nothing other than the equivalent of
27520 // "=r,0" would be valid here.
27521 return IntrinsicLowering::LowerToByteSwap(CI);
27524 // rorw $$8, ${0:w} --> llvm.bswap.i16
27525 if (CI->getType()->isIntegerTy(16) &&
27526 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
27527 (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
27528 matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
27530 StringRef ConstraintsStr = IA->getConstraintString();
27531 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
27532 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
27533 if (clobbersFlagRegisters(AsmPieces))
27534 return IntrinsicLowering::LowerToByteSwap(CI);
27538 if (CI->getType()->isIntegerTy(32) &&
27539 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
27540 matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
27541 matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
27542 matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
27544 StringRef ConstraintsStr = IA->getConstraintString();
27545 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
27546 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
27547 if (clobbersFlagRegisters(AsmPieces))
27548 return IntrinsicLowering::LowerToByteSwap(CI);
27551 if (CI->getType()->isIntegerTy(64)) {
27552 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
27553 if (Constraints.size() >= 2 &&
27554 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
27555 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
27556 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
27557 if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
27558 matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
27559 matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
27560 return IntrinsicLowering::LowerToByteSwap(CI);
27568 /// getConstraintType - Given a constraint letter, return the type of
27569 /// constraint it is for this target.
27570 X86TargetLowering::ConstraintType
27571 X86TargetLowering::getConstraintType(StringRef Constraint) const {
27572 if (Constraint.size() == 1) {
27573 switch (Constraint[0]) {
27584 return C_RegisterClass;
27608 return TargetLowering::getConstraintType(Constraint);
27611 /// Examine constraint type and operand type and determine a weight value.
27612 /// This object must already have been set up with the operand type
27613 /// and the current alternative constraint selected.
27614 TargetLowering::ConstraintWeight
27615 X86TargetLowering::getSingleConstraintMatchWeight(
27616 AsmOperandInfo &info, const char *constraint) const {
27617 ConstraintWeight weight = CW_Invalid;
27618 Value *CallOperandVal = info.CallOperandVal;
27619 // If we don't have a value, we can't do a match,
27620 // but allow it at the lowest weight.
27621 if (!CallOperandVal)
27623 Type *type = CallOperandVal->getType();
27624 // Look at the constraint type.
27625 switch (*constraint) {
27627 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
27638 if (CallOperandVal->getType()->isIntegerTy())
27639 weight = CW_SpecificReg;
27644 if (type->isFloatingPointTy())
27645 weight = CW_SpecificReg;
27648 if (type->isX86_MMXTy() && Subtarget->hasMMX())
27649 weight = CW_SpecificReg;
27653 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
27654 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
27655 weight = CW_Register;
27658 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
27659 if (C->getZExtValue() <= 31)
27660 weight = CW_Constant;
27664 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27665 if (C->getZExtValue() <= 63)
27666 weight = CW_Constant;
27670 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27671 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
27672 weight = CW_Constant;
27676 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27677 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
27678 weight = CW_Constant;
27682 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27683 if (C->getZExtValue() <= 3)
27684 weight = CW_Constant;
27688 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27689 if (C->getZExtValue() <= 0xff)
27690 weight = CW_Constant;
27695 if (isa<ConstantFP>(CallOperandVal)) {
27696 weight = CW_Constant;
27700 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27701 if ((C->getSExtValue() >= -0x80000000LL) &&
27702 (C->getSExtValue() <= 0x7fffffffLL))
27703 weight = CW_Constant;
27707 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
27708 if (C->getZExtValue() <= 0xffffffff)
27709 weight = CW_Constant;
27716 /// LowerXConstraint - try to replace an X constraint, which matches anything,
27717 /// with another that has more specific requirements based on the type of the
27718 /// corresponding operand.
27719 const char *X86TargetLowering::
27720 LowerXConstraint(EVT ConstraintVT) const {
27721 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
27722 // 'f' like normal targets.
27723 if (ConstraintVT.isFloatingPoint()) {
27724 if (Subtarget->hasSSE2())
27726 if (Subtarget->hasSSE1())
27730 return TargetLowering::LowerXConstraint(ConstraintVT);
27733 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
27734 /// vector. If it is invalid, don't add anything to Ops.
27735 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
27736 std::string &Constraint,
27737 std::vector<SDValue>&Ops,
27738 SelectionDAG &DAG) const {
27741 // Only support length 1 constraints for now.
27742 if (Constraint.length() > 1) return;
27744 char ConstraintLetter = Constraint[0];
27745 switch (ConstraintLetter) {
27748 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27749 if (C->getZExtValue() <= 31) {
27750 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27751 Op.getValueType());
27757 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27758 if (C->getZExtValue() <= 63) {
27759 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27760 Op.getValueType());
27766 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27767 if (isInt<8>(C->getSExtValue())) {
27768 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27769 Op.getValueType());
27775 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27776 if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
27777 (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
27778 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
27779 Op.getValueType());
27785 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27786 if (C->getZExtValue() <= 3) {
27787 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27788 Op.getValueType());
27794 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27795 if (C->getZExtValue() <= 255) {
27796 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27797 Op.getValueType());
27803 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27804 if (C->getZExtValue() <= 127) {
27805 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27806 Op.getValueType());
27812 // 32-bit signed value
27813 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27814 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
27815 C->getSExtValue())) {
27816 // Widen to 64 bits here to get it sign extended.
27817 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
27820 // FIXME gcc accepts some relocatable values here too, but only in certain
27821 // memory models; it's complicated.
27826 // 32-bit unsigned value
27827 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
27828 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
27829 C->getZExtValue())) {
27830 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
27831 Op.getValueType());
27835 // FIXME gcc accepts some relocatable values here too, but only in certain
27836 // memory models; it's complicated.
27840 // Literal immediates are always ok.
27841 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
27842 // Widen to 64 bits here to get it sign extended.
27843 Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
27847 // In any sort of PIC mode addresses need to be computed at runtime by
27848 // adding in a register or some sort of table lookup. These can't
27849 // be used as immediates.
27850 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
27853 // If we are in non-pic codegen mode, we allow the address of a global (with
27854 // an optional displacement) to be used with 'i'.
27855 GlobalAddressSDNode *GA = nullptr;
27856 int64_t Offset = 0;
27858 // Match either (GA), (GA+C), (GA+C1+C2), etc.
27860 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
27861 Offset += GA->getOffset();
27863 } else if (Op.getOpcode() == ISD::ADD) {
27864 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
27865 Offset += C->getZExtValue();
27866 Op = Op.getOperand(0);
27869 } else if (Op.getOpcode() == ISD::SUB) {
27870 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
27871 Offset += -C->getZExtValue();
27872 Op = Op.getOperand(0);
27877 // Otherwise, this isn't something we can handle, reject it.
27881 const GlobalValue *GV = GA->getGlobal();
27882 // If we require an extra load to get this address, as in PIC mode, we
27883 // can't accept it.
27884 if (isGlobalStubReference(
27885 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
27888 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
27889 GA->getValueType(0), Offset);
27894 if (Result.getNode()) {
27895 Ops.push_back(Result);
27898 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
27901 std::pair<unsigned, const TargetRegisterClass *>
27902 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
27903 StringRef Constraint,
27905 // First, see if this is a constraint that directly corresponds to an LLVM
27907 if (Constraint.size() == 1) {
27908 // GCC Constraint Letters
27909 switch (Constraint[0]) {
27911 // TODO: Slight differences here in allocation order and leaving
27912 // RIP in the class. Do they matter any more here than they do
27913 // in the normal allocation?
27914 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
27915 if (Subtarget->is64Bit()) {
27916 if (VT == MVT::i32 || VT == MVT::f32)
27917 return std::make_pair(0U, &X86::GR32RegClass);
27918 if (VT == MVT::i16)
27919 return std::make_pair(0U, &X86::GR16RegClass);
27920 if (VT == MVT::i8 || VT == MVT::i1)
27921 return std::make_pair(0U, &X86::GR8RegClass);
27922 if (VT == MVT::i64 || VT == MVT::f64)
27923 return std::make_pair(0U, &X86::GR64RegClass);
27926 // 32-bit fallthrough
27927 case 'Q': // Q_REGS
27928 if (VT == MVT::i32 || VT == MVT::f32)
27929 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
27930 if (VT == MVT::i16)
27931 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
27932 if (VT == MVT::i8 || VT == MVT::i1)
27933 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
27934 if (VT == MVT::i64)
27935 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
27937 case 'r': // GENERAL_REGS
27938 case 'l': // INDEX_REGS
27939 if (VT == MVT::i8 || VT == MVT::i1)
27940 return std::make_pair(0U, &X86::GR8RegClass);
27941 if (VT == MVT::i16)
27942 return std::make_pair(0U, &X86::GR16RegClass);
27943 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
27944 return std::make_pair(0U, &X86::GR32RegClass);
27945 return std::make_pair(0U, &X86::GR64RegClass);
27946 case 'R': // LEGACY_REGS
27947 if (VT == MVT::i8 || VT == MVT::i1)
27948 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
27949 if (VT == MVT::i16)
27950 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
27951 if (VT == MVT::i32 || !Subtarget->is64Bit())
27952 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
27953 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
27954 case 'f': // FP Stack registers.
27955 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
27956 // value to the correct fpstack register class.
27957 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
27958 return std::make_pair(0U, &X86::RFP32RegClass);
27959 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
27960 return std::make_pair(0U, &X86::RFP64RegClass);
27961 return std::make_pair(0U, &X86::RFP80RegClass);
27962 case 'y': // MMX_REGS if MMX allowed.
27963 if (!Subtarget->hasMMX()) break;
27964 return std::make_pair(0U, &X86::VR64RegClass);
27965 case 'Y': // SSE_REGS if SSE2 allowed
27966 if (!Subtarget->hasSSE2()) break;
27968 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
27969 if (!Subtarget->hasSSE1()) break;
27971 switch (VT.SimpleTy) {
27973 // Scalar SSE types.
27976 return std::make_pair(0U, &X86::FR32RegClass);
27979 return std::make_pair(0U, &X86::FR64RegClass);
27980 // TODO: Handle f128 and i128 in FR128RegClass after it is tested well.
27988 return std::make_pair(0U, &X86::VR128RegClass);
27996 return std::make_pair(0U, &X86::VR256RegClass);
28001 return std::make_pair(0U, &X86::VR512RegClass);
28007 // Use the default implementation in TargetLowering to convert the register
28008 // constraint into a member of a register class.
28009 std::pair<unsigned, const TargetRegisterClass*> Res;
28010 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
28012 // Not found as a standard register?
28014 // Map st(0) -> st(7) -> ST0
28015 if (Constraint.size() == 7 && Constraint[0] == '{' &&
28016 tolower(Constraint[1]) == 's' &&
28017 tolower(Constraint[2]) == 't' &&
28018 Constraint[3] == '(' &&
28019 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
28020 Constraint[5] == ')' &&
28021 Constraint[6] == '}') {
28023 Res.first = X86::FP0+Constraint[4]-'0';
28024 Res.second = &X86::RFP80RegClass;
28028 // GCC allows "st(0)" to be called just plain "st".
28029 if (StringRef("{st}").equals_lower(Constraint)) {
28030 Res.first = X86::FP0;
28031 Res.second = &X86::RFP80RegClass;
28036 if (StringRef("{flags}").equals_lower(Constraint)) {
28037 Res.first = X86::EFLAGS;
28038 Res.second = &X86::CCRRegClass;
28042 // 'A' means EAX + EDX.
28043 if (Constraint == "A") {
28044 Res.first = X86::EAX;
28045 Res.second = &X86::GR32_ADRegClass;
28051 // Otherwise, check to see if this is a register class of the wrong value
28052 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
28053 // turn into {ax},{dx}.
28054 // MVT::Other is used to specify clobber names.
28055 if (Res.second->hasType(VT) || VT == MVT::Other)
28056 return Res; // Correct type already, nothing to do.
28058 // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
28059 // return "eax". This should even work for things like getting 64bit integer
28060 // registers when given an f64 type.
28061 const TargetRegisterClass *Class = Res.second;
28062 if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
28063 Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
28064 unsigned Size = VT.getSizeInBits();
28065 MVT::SimpleValueType SimpleTy = Size == 1 || Size == 8 ? MVT::i8
28066 : Size == 16 ? MVT::i16
28067 : Size == 32 ? MVT::i32
28068 : Size == 64 ? MVT::i64
28070 unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, SimpleTy);
28072 Res.first = DestReg;
28073 Res.second = SimpleTy == MVT::i8 ? &X86::GR8RegClass
28074 : SimpleTy == MVT::i16 ? &X86::GR16RegClass
28075 : SimpleTy == MVT::i32 ? &X86::GR32RegClass
28076 : &X86::GR64RegClass;
28077 assert(Res.second->contains(Res.first) && "Register in register class");
28079 // No register found/type mismatch.
28081 Res.second = nullptr;
28083 } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
28084 Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
28085 Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
28086 Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
28087 Class == &X86::VR512RegClass) {
28088 // Handle references to XMM physical registers that got mapped into the
28089 // wrong class. This can happen with constraints like {xmm0} where the
28090 // target independent register mapper will just pick the first match it can
28091 // find, ignoring the required type.
28093 // TODO: Handle f128 and i128 in FR128RegClass after it is tested well.
28094 if (VT == MVT::f32 || VT == MVT::i32)
28095 Res.second = &X86::FR32RegClass;
28096 else if (VT == MVT::f64 || VT == MVT::i64)
28097 Res.second = &X86::FR64RegClass;
28098 else if (X86::VR128RegClass.hasType(VT))
28099 Res.second = &X86::VR128RegClass;
28100 else if (X86::VR256RegClass.hasType(VT))
28101 Res.second = &X86::VR256RegClass;
28102 else if (X86::VR512RegClass.hasType(VT))
28103 Res.second = &X86::VR512RegClass;
28105 // Type mismatch and not a clobber: Return an error;
28107 Res.second = nullptr;
28114 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
28115 const AddrMode &AM, Type *Ty,
28116 unsigned AS) const {
28117 // Scaling factors are not free at all.
28118 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
28119 // will take 2 allocations in the out of order engine instead of 1
28120 // for plain addressing mode, i.e. inst (reg1).
28122 // vaddps (%rsi,%drx), %ymm0, %ymm1
28123 // Requires two allocations (one for the load, one for the computation)
28125 // vaddps (%rsi), %ymm0, %ymm1
28126 // Requires just 1 allocation, i.e., freeing allocations for other operations
28127 // and having less micro operations to execute.
28129 // For some X86 architectures, this is even worse because for instance for
28130 // stores, the complex addressing mode forces the instruction to use the
28131 // "load" ports instead of the dedicated "store" port.
28132 // E.g., on Haswell:
28133 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
28134 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
28135 if (isLegalAddressingMode(DL, AM, Ty, AS))
28136 // Scale represents reg2 * scale, thus account for 1
28137 // as soon as we use a second register.
28138 return AM.Scale != 0;
28142 bool X86TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const {
28143 // Integer division on x86 is expensive. However, when aggressively optimizing
28144 // for code size, we prefer to use a div instruction, as it is usually smaller
28145 // than the alternative sequence.
28146 // The exception to this is vector division. Since x86 doesn't have vector
28147 // integer division, leaving the division as-is is a loss even in terms of
28148 // size, because it will have to be scalarized, while the alternative code
28149 // sequence can be performed in vector form.
28150 bool OptSize = Attr.hasAttribute(AttributeSet::FunctionIndex,
28151 Attribute::MinSize);
28152 return OptSize && !VT.isVector();
28155 void X86TargetLowering::markInRegArguments(SelectionDAG &DAG,
28156 TargetLowering::ArgListTy& Args) const {
28157 // The MCU psABI requires some arguments to be passed in-register.
28158 // For regular calls, the inreg arguments are marked by the front-end.
28159 // However, for compiler generated library calls, we have to patch this
28161 if (!Subtarget->isTargetMCU() || !Args.size())
28164 unsigned FreeRegs = 3;
28165 for (auto &Arg : Args) {
28166 // For library functions, we do not expect any fancy types.
28167 unsigned Size = DAG.getDataLayout().getTypeSizeInBits(Arg.Ty);
28168 unsigned SizeInRegs = (Size + 31) / 32;
28169 if (SizeInRegs > 2 || SizeInRegs > FreeRegs)
28172 Arg.isInReg = true;
28173 FreeRegs -= SizeInRegs;