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/CodeGen/IntrinsicLowering.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/WinEHFuncInfo.h"
36 #include "llvm/IR/CallSite.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/DerivedTypes.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/IR/GlobalAlias.h"
42 #include "llvm/IR/GlobalVariable.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/Intrinsics.h"
45 #include "llvm/MC/MCAsmInfo.h"
46 #include "llvm/MC/MCContext.h"
47 #include "llvm/MC/MCExpr.h"
48 #include "llvm/MC/MCSymbol.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Target/TargetOptions.h"
54 #include "X86IntrinsicsInfo.h"
60 #define DEBUG_TYPE "x86-isel"
62 STATISTIC(NumTailCalls, "Number of tail calls");
64 static cl::opt<bool> ExperimentalVectorWideningLegalization(
65 "x86-experimental-vector-widening-legalization", cl::init(false),
66 cl::desc("Enable an experimental vector type legalization through widening "
67 "rather than promotion."),
70 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
71 const X86Subtarget &STI)
72 : TargetLowering(TM), Subtarget(&STI) {
73 X86ScalarSSEf64 = Subtarget->hasSSE2();
74 X86ScalarSSEf32 = Subtarget->hasSSE1();
75 MVT PtrVT = MVT::getIntegerVT(8 * TM.getPointerSize());
77 // Set up the TargetLowering object.
78 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
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);
118 // The _ftol2 runtime function has an unusual calling conv, which
119 // is modeled by a special pseudo-instruction.
120 setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
121 setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
122 setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
123 setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
126 if (Subtarget->isTargetDarwin()) {
127 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
128 setUseUnderscoreSetJmp(false);
129 setUseUnderscoreLongJmp(false);
130 } else if (Subtarget->isTargetWindowsGNU()) {
131 // MS runtime is weird: it exports _setjmp, but longjmp!
132 setUseUnderscoreSetJmp(true);
133 setUseUnderscoreLongJmp(false);
135 setUseUnderscoreSetJmp(true);
136 setUseUnderscoreLongJmp(true);
139 // Set up the register classes.
140 addRegisterClass(MVT::i8, &X86::GR8RegClass);
141 addRegisterClass(MVT::i16, &X86::GR16RegClass);
142 addRegisterClass(MVT::i32, &X86::GR32RegClass);
143 if (Subtarget->is64Bit())
144 addRegisterClass(MVT::i64, &X86::GR64RegClass);
146 for (MVT VT : MVT::integer_valuetypes())
147 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
149 // We don't accept any truncstore of integer registers.
150 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
151 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
152 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
153 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
154 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
155 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
157 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
159 // SETOEQ and SETUNE require checking two conditions.
160 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
161 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
162 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
163 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
164 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
165 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
167 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
169 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
170 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
171 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
173 if (Subtarget->is64Bit()) {
174 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
175 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
176 } else if (!Subtarget->useSoftFloat()) {
177 // We have an algorithm for SSE2->double, and we turn this into a
178 // 64-bit FILD followed by conditional FADD for other targets.
179 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
180 // We have an algorithm for SSE2, and we turn this into a 64-bit
181 // FILD for other targets.
182 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
185 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
187 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
188 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
190 if (!Subtarget->useSoftFloat()) {
191 // SSE has no i16 to fp conversion, only i32
192 if (X86ScalarSSEf32) {
193 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
194 // f32 and f64 cases are Legal, f80 case is not
195 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
197 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
198 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
201 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
202 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
205 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
206 // are Legal, f80 is custom lowered.
207 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
208 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
210 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
212 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
213 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
215 if (X86ScalarSSEf32) {
216 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
217 // f32 and f64 cases are Legal, f80 case is not
218 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
220 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
221 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
224 // Handle FP_TO_UINT by promoting the destination to a larger signed
226 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
227 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
228 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
230 if (Subtarget->is64Bit()) {
231 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
232 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
233 } else if (!Subtarget->useSoftFloat()) {
234 // Since AVX is a superset of SSE3, only check for SSE here.
235 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
236 // Expand FP_TO_UINT into a select.
237 // FIXME: We would like to use a Custom expander here eventually to do
238 // the optimal thing for SSE vs. the default expansion in the legalizer.
239 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
241 // With SSE3 we can use fisttpll to convert to a signed i64; without
242 // SSE, we're stuck with a fistpll.
243 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
246 if (isTargetFTOL()) {
247 // Use the _ftol2 runtime function, which has a pseudo-instruction
248 // to handle its weird calling convention.
249 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
252 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
253 if (!X86ScalarSSEf64) {
254 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
255 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
256 if (Subtarget->is64Bit()) {
257 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
258 // Without SSE, i64->f64 goes through memory.
259 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
263 // Scalar integer divide and remainder are lowered to use operations that
264 // produce two results, to match the available instructions. This exposes
265 // the two-result form to trivial CSE, which is able to combine x/y and x%y
266 // into a single instruction.
268 // Scalar integer multiply-high is also lowered to use two-result
269 // operations, to match the available instructions. However, plain multiply
270 // (low) operations are left as Legal, as there are single-result
271 // instructions for this in x86. Using the two-result multiply instructions
272 // when both high and low results are needed must be arranged by dagcombine.
273 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
275 setOperationAction(ISD::MULHS, VT, Expand);
276 setOperationAction(ISD::MULHU, VT, Expand);
277 setOperationAction(ISD::SDIV, VT, Expand);
278 setOperationAction(ISD::UDIV, VT, Expand);
279 setOperationAction(ISD::SREM, VT, Expand);
280 setOperationAction(ISD::UREM, VT, Expand);
282 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
283 setOperationAction(ISD::ADDC, VT, Custom);
284 setOperationAction(ISD::ADDE, VT, Custom);
285 setOperationAction(ISD::SUBC, VT, Custom);
286 setOperationAction(ISD::SUBE, VT, Custom);
289 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
290 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
291 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
292 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
293 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
294 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
295 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
296 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
297 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
298 setOperationAction(ISD::SELECT_CC , MVT::f32, Expand);
299 setOperationAction(ISD::SELECT_CC , MVT::f64, Expand);
300 setOperationAction(ISD::SELECT_CC , MVT::f80, Expand);
301 setOperationAction(ISD::SELECT_CC , MVT::i8, Expand);
302 setOperationAction(ISD::SELECT_CC , MVT::i16, Expand);
303 setOperationAction(ISD::SELECT_CC , MVT::i32, Expand);
304 setOperationAction(ISD::SELECT_CC , MVT::i64, Expand);
305 if (Subtarget->is64Bit())
306 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
307 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
308 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
309 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
310 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
311 setOperationAction(ISD::FREM , MVT::f32 , Expand);
312 setOperationAction(ISD::FREM , MVT::f64 , Expand);
313 setOperationAction(ISD::FREM , MVT::f80 , Expand);
314 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
316 // Promote the i8 variants and force them on up to i32 which has a shorter
318 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
319 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
320 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
321 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
322 if (Subtarget->hasBMI()) {
323 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
324 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
325 if (Subtarget->is64Bit())
326 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
328 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
329 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
330 if (Subtarget->is64Bit())
331 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
334 if (Subtarget->hasLZCNT()) {
335 // When promoting the i8 variants, force them to i32 for a shorter
337 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
338 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
339 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
340 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
341 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
342 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
343 if (Subtarget->is64Bit())
344 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
346 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
347 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
348 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
349 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
350 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
351 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
352 if (Subtarget->is64Bit()) {
353 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
354 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
358 // Special handling for half-precision floating point conversions.
359 // If we don't have F16C support, then lower half float conversions
360 // into library calls.
361 if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) {
362 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
363 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
366 // There's never any support for operations beyond MVT::f32.
367 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
368 setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
369 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
370 setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
372 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
373 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
374 setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
375 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
376 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
377 setTruncStoreAction(MVT::f80, MVT::f16, Expand);
379 if (Subtarget->hasPOPCNT()) {
380 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
382 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
383 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
384 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
385 if (Subtarget->is64Bit())
386 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
389 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
391 if (!Subtarget->hasMOVBE())
392 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
394 // These should be promoted to a larger select which is supported.
395 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
396 // X86 wants to expand cmov itself.
397 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
398 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
399 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
400 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
401 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
402 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
403 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
404 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
405 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
406 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
407 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
408 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
409 if (Subtarget->is64Bit()) {
410 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
411 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
413 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
414 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
415 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
416 // support continuation, user-level threading, and etc.. As a result, no
417 // other SjLj exception interfaces are implemented and please don't build
418 // your own exception handling based on them.
419 // LLVM/Clang supports zero-cost DWARF exception handling.
420 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
421 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
424 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
425 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
426 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
427 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
428 if (Subtarget->is64Bit())
429 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
430 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
431 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
432 if (Subtarget->is64Bit()) {
433 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
434 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
435 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
436 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
437 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
439 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
440 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
441 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
442 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
443 if (Subtarget->is64Bit()) {
444 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
445 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
446 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
449 if (Subtarget->hasSSE1())
450 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
452 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
454 // Expand certain atomics
455 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
457 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
458 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
459 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
462 if (Subtarget->hasCmpxchg16b()) {
463 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
466 // FIXME - use subtarget debug flags
467 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
468 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
469 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
472 if (Subtarget->is64Bit()) {
473 setExceptionPointerRegister(X86::RAX);
474 setExceptionSelectorRegister(X86::RDX);
476 setExceptionPointerRegister(X86::EAX);
477 setExceptionSelectorRegister(X86::EDX);
479 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
480 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
482 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
483 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
485 setOperationAction(ISD::TRAP, MVT::Other, Legal);
486 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
488 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
489 setOperationAction(ISD::VASTART , MVT::Other, Custom);
490 setOperationAction(ISD::VAEND , MVT::Other, Expand);
491 if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
492 // TargetInfo::X86_64ABIBuiltinVaList
493 setOperationAction(ISD::VAARG , MVT::Other, Custom);
494 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
496 // TargetInfo::CharPtrBuiltinVaList
497 setOperationAction(ISD::VAARG , MVT::Other, Expand);
498 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
501 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
502 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
504 setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
506 // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
507 setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
508 setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
510 if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
511 // f32 and f64 use SSE.
512 // Set up the FP register classes.
513 addRegisterClass(MVT::f32, &X86::FR32RegClass);
514 addRegisterClass(MVT::f64, &X86::FR64RegClass);
516 // Use ANDPD to simulate FABS.
517 setOperationAction(ISD::FABS , MVT::f64, Custom);
518 setOperationAction(ISD::FABS , MVT::f32, Custom);
520 // Use XORP to simulate FNEG.
521 setOperationAction(ISD::FNEG , MVT::f64, Custom);
522 setOperationAction(ISD::FNEG , MVT::f32, Custom);
524 // Use ANDPD and ORPD to simulate FCOPYSIGN.
525 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
526 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
528 // Lower this to FGETSIGNx86 plus an AND.
529 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
530 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
532 // We don't support sin/cos/fmod
533 setOperationAction(ISD::FSIN , MVT::f64, Expand);
534 setOperationAction(ISD::FCOS , MVT::f64, Expand);
535 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
536 setOperationAction(ISD::FSIN , MVT::f32, Expand);
537 setOperationAction(ISD::FCOS , MVT::f32, Expand);
538 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
540 // Expand FP immediates into loads from the stack, except for the special
542 addLegalFPImmediate(APFloat(+0.0)); // xorpd
543 addLegalFPImmediate(APFloat(+0.0f)); // xorps
544 } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
545 // Use SSE for f32, x87 for f64.
546 // Set up the FP register classes.
547 addRegisterClass(MVT::f32, &X86::FR32RegClass);
548 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
550 // Use ANDPS to simulate FABS.
551 setOperationAction(ISD::FABS , MVT::f32, Custom);
553 // Use XORP to simulate FNEG.
554 setOperationAction(ISD::FNEG , MVT::f32, Custom);
556 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
558 // Use ANDPS and ORPS to simulate FCOPYSIGN.
559 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
560 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
562 // We don't support sin/cos/fmod
563 setOperationAction(ISD::FSIN , MVT::f32, Expand);
564 setOperationAction(ISD::FCOS , MVT::f32, Expand);
565 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
567 // Special cases we handle for FP constants.
568 addLegalFPImmediate(APFloat(+0.0f)); // xorps
569 addLegalFPImmediate(APFloat(+0.0)); // FLD0
570 addLegalFPImmediate(APFloat(+1.0)); // FLD1
571 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
572 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
574 if (!TM.Options.UnsafeFPMath) {
575 setOperationAction(ISD::FSIN , MVT::f64, Expand);
576 setOperationAction(ISD::FCOS , MVT::f64, Expand);
577 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
579 } else if (!Subtarget->useSoftFloat()) {
580 // f32 and f64 in x87.
581 // Set up the FP register classes.
582 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
583 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
585 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
586 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
587 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
588 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
590 if (!TM.Options.UnsafeFPMath) {
591 setOperationAction(ISD::FSIN , MVT::f64, Expand);
592 setOperationAction(ISD::FSIN , MVT::f32, Expand);
593 setOperationAction(ISD::FCOS , MVT::f64, Expand);
594 setOperationAction(ISD::FCOS , MVT::f32, Expand);
595 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
596 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
598 addLegalFPImmediate(APFloat(+0.0)); // FLD0
599 addLegalFPImmediate(APFloat(+1.0)); // FLD1
600 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
601 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
602 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
603 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
604 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
605 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
608 // We don't support FMA.
609 setOperationAction(ISD::FMA, MVT::f64, Expand);
610 setOperationAction(ISD::FMA, MVT::f32, Expand);
612 // Long double always uses X87.
613 if (!Subtarget->useSoftFloat()) {
614 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
615 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
616 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
618 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
619 addLegalFPImmediate(TmpFlt); // FLD0
621 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
624 APFloat TmpFlt2(+1.0);
625 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
627 addLegalFPImmediate(TmpFlt2); // FLD1
628 TmpFlt2.changeSign();
629 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
632 if (!TM.Options.UnsafeFPMath) {
633 setOperationAction(ISD::FSIN , MVT::f80, Expand);
634 setOperationAction(ISD::FCOS , MVT::f80, Expand);
635 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
638 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
639 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
640 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
641 setOperationAction(ISD::FRINT, MVT::f80, Expand);
642 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
643 setOperationAction(ISD::FMA, MVT::f80, Expand);
646 // Always use a library call for pow.
647 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
648 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
649 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
651 setOperationAction(ISD::FLOG, MVT::f80, Expand);
652 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
653 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
654 setOperationAction(ISD::FEXP, MVT::f80, Expand);
655 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
656 setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
657 setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
659 // First set operation action for all vector types to either promote
660 // (for widening) or expand (for scalarization). Then we will selectively
661 // turn on ones that can be effectively codegen'd.
662 for (MVT VT : MVT::vector_valuetypes()) {
663 setOperationAction(ISD::ADD , VT, Expand);
664 setOperationAction(ISD::SUB , VT, Expand);
665 setOperationAction(ISD::FADD, VT, Expand);
666 setOperationAction(ISD::FNEG, VT, Expand);
667 setOperationAction(ISD::FSUB, VT, Expand);
668 setOperationAction(ISD::MUL , VT, Expand);
669 setOperationAction(ISD::FMUL, VT, Expand);
670 setOperationAction(ISD::SDIV, VT, Expand);
671 setOperationAction(ISD::UDIV, VT, Expand);
672 setOperationAction(ISD::FDIV, VT, Expand);
673 setOperationAction(ISD::SREM, VT, Expand);
674 setOperationAction(ISD::UREM, VT, Expand);
675 setOperationAction(ISD::LOAD, VT, Expand);
676 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
677 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
678 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
679 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
680 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
681 setOperationAction(ISD::FABS, VT, Expand);
682 setOperationAction(ISD::FSIN, VT, Expand);
683 setOperationAction(ISD::FSINCOS, VT, Expand);
684 setOperationAction(ISD::FCOS, VT, Expand);
685 setOperationAction(ISD::FSINCOS, VT, Expand);
686 setOperationAction(ISD::FREM, VT, Expand);
687 setOperationAction(ISD::FMA, VT, Expand);
688 setOperationAction(ISD::FPOWI, VT, Expand);
689 setOperationAction(ISD::FSQRT, VT, Expand);
690 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
691 setOperationAction(ISD::FFLOOR, VT, Expand);
692 setOperationAction(ISD::FCEIL, VT, Expand);
693 setOperationAction(ISD::FTRUNC, VT, Expand);
694 setOperationAction(ISD::FRINT, VT, Expand);
695 setOperationAction(ISD::FNEARBYINT, VT, Expand);
696 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
697 setOperationAction(ISD::MULHS, VT, Expand);
698 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
699 setOperationAction(ISD::MULHU, VT, Expand);
700 setOperationAction(ISD::SDIVREM, VT, Expand);
701 setOperationAction(ISD::UDIVREM, VT, Expand);
702 setOperationAction(ISD::FPOW, VT, Expand);
703 setOperationAction(ISD::CTPOP, VT, Expand);
704 setOperationAction(ISD::CTTZ, VT, Expand);
705 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
706 setOperationAction(ISD::CTLZ, VT, Expand);
707 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
708 setOperationAction(ISD::SHL, VT, Expand);
709 setOperationAction(ISD::SRA, VT, Expand);
710 setOperationAction(ISD::SRL, VT, Expand);
711 setOperationAction(ISD::ROTL, VT, Expand);
712 setOperationAction(ISD::ROTR, VT, Expand);
713 setOperationAction(ISD::BSWAP, VT, Expand);
714 setOperationAction(ISD::SETCC, VT, Expand);
715 setOperationAction(ISD::FLOG, VT, Expand);
716 setOperationAction(ISD::FLOG2, VT, Expand);
717 setOperationAction(ISD::FLOG10, VT, Expand);
718 setOperationAction(ISD::FEXP, VT, Expand);
719 setOperationAction(ISD::FEXP2, VT, Expand);
720 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
721 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
722 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
723 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
724 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
725 setOperationAction(ISD::TRUNCATE, VT, Expand);
726 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
727 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
728 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
729 setOperationAction(ISD::VSELECT, VT, Expand);
730 setOperationAction(ISD::SELECT_CC, VT, Expand);
731 for (MVT InnerVT : MVT::vector_valuetypes()) {
732 setTruncStoreAction(InnerVT, VT, Expand);
734 setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
735 setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
737 // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
738 // types, we have to deal with them whether we ask for Expansion or not.
739 // Setting Expand causes its own optimisation problems though, so leave
741 if (VT.getVectorElementType() == MVT::i1)
742 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
744 // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
745 // split/scalarized right now.
746 if (VT.getVectorElementType() == MVT::f16)
747 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
751 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
752 // with -msoft-float, disable use of MMX as well.
753 if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
754 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
755 // No operations on x86mmx supported, everything uses intrinsics.
758 // MMX-sized vectors (other than x86mmx) are expected to be expanded
759 // into smaller operations.
760 for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
761 setOperationAction(ISD::MULHS, MMXTy, Expand);
762 setOperationAction(ISD::AND, MMXTy, Expand);
763 setOperationAction(ISD::OR, MMXTy, Expand);
764 setOperationAction(ISD::XOR, MMXTy, Expand);
765 setOperationAction(ISD::SCALAR_TO_VECTOR, MMXTy, Expand);
766 setOperationAction(ISD::SELECT, MMXTy, Expand);
767 setOperationAction(ISD::BITCAST, MMXTy, Expand);
769 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
771 if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
772 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
774 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
775 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
776 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
777 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
778 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
779 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
780 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
781 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
782 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
783 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
784 setOperationAction(ISD::VSELECT, MVT::v4f32, Custom);
785 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
786 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
787 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
790 if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
791 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
793 // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
794 // registers cannot be used even for integer operations.
795 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
796 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
797 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
798 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
800 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
801 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
802 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
803 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
804 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
805 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
806 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
807 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
808 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
809 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
810 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
811 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
812 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
813 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
814 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
815 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
816 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
817 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
818 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
819 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
820 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
821 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
822 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
824 setOperationAction(ISD::SMAX, MVT::v8i16, Legal);
825 setOperationAction(ISD::UMAX, MVT::v16i8, Legal);
826 setOperationAction(ISD::SMIN, MVT::v8i16, Legal);
827 setOperationAction(ISD::UMIN, MVT::v16i8, Legal);
829 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
830 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
831 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
832 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
834 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
835 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
836 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
837 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
838 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
840 setOperationAction(ISD::CTPOP, MVT::v16i8, Custom);
841 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
842 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
843 setOperationAction(ISD::CTPOP, MVT::v2i64, Custom);
845 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
846 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
847 MVT VT = (MVT::SimpleValueType)i;
848 // Do not attempt to custom lower non-power-of-2 vectors
849 if (!isPowerOf2_32(VT.getVectorNumElements()))
851 // Do not attempt to custom lower non-128-bit vectors
852 if (!VT.is128BitVector())
854 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
855 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
856 setOperationAction(ISD::VSELECT, VT, Custom);
857 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
860 // We support custom legalizing of sext and anyext loads for specific
861 // memory vector types which we can load as a scalar (or sequence of
862 // scalars) and extend in-register to a legal 128-bit vector type. For sext
863 // loads these must work with a single scalar load.
864 for (MVT VT : MVT::integer_vector_valuetypes()) {
865 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
866 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
867 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
868 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
869 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
870 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
871 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
872 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
873 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
876 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
877 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
878 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
879 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
880 setOperationAction(ISD::VSELECT, MVT::v2f64, Custom);
881 setOperationAction(ISD::VSELECT, MVT::v2i64, Custom);
882 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
883 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
885 if (Subtarget->is64Bit()) {
886 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
887 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
890 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
891 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
892 MVT VT = (MVT::SimpleValueType)i;
894 // Do not attempt to promote non-128-bit vectors
895 if (!VT.is128BitVector())
898 setOperationAction(ISD::AND, VT, Promote);
899 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
900 setOperationAction(ISD::OR, VT, Promote);
901 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
902 setOperationAction(ISD::XOR, VT, Promote);
903 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
904 setOperationAction(ISD::LOAD, VT, Promote);
905 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
906 setOperationAction(ISD::SELECT, VT, Promote);
907 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
910 // Custom lower v2i64 and v2f64 selects.
911 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
912 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
913 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
914 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
916 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
917 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
919 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
921 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
922 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
923 // As there is no 64-bit GPR available, we need build a special custom
924 // sequence to convert from v2i32 to v2f32.
925 if (!Subtarget->is64Bit())
926 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
928 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
929 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
931 for (MVT VT : MVT::fp_vector_valuetypes())
932 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
934 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
935 setOperationAction(ISD::BITCAST, MVT::v4i16, Custom);
936 setOperationAction(ISD::BITCAST, MVT::v8i8, Custom);
939 if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
940 for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
941 setOperationAction(ISD::FFLOOR, RoundedTy, Legal);
942 setOperationAction(ISD::FCEIL, RoundedTy, Legal);
943 setOperationAction(ISD::FTRUNC, RoundedTy, Legal);
944 setOperationAction(ISD::FRINT, RoundedTy, Legal);
945 setOperationAction(ISD::FNEARBYINT, RoundedTy, Legal);
948 setOperationAction(ISD::SMAX, MVT::v16i8, Legal);
949 setOperationAction(ISD::SMAX, MVT::v4i32, Legal);
950 setOperationAction(ISD::UMAX, MVT::v8i16, Legal);
951 setOperationAction(ISD::UMAX, MVT::v4i32, Legal);
952 setOperationAction(ISD::SMIN, MVT::v16i8, Legal);
953 setOperationAction(ISD::SMIN, MVT::v4i32, Legal);
954 setOperationAction(ISD::UMIN, MVT::v8i16, Legal);
955 setOperationAction(ISD::UMIN, MVT::v4i32, Legal);
957 // FIXME: Do we need to handle scalar-to-vector here?
958 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
960 // We directly match byte blends in the backend as they match the VSELECT
962 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
964 // SSE41 brings specific instructions for doing vector sign extend even in
965 // cases where we don't have SRA.
966 for (MVT VT : MVT::integer_vector_valuetypes()) {
967 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
968 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
969 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
972 // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
973 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8, Legal);
974 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8, Legal);
975 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8, Legal);
976 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
977 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
978 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
980 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8, Legal);
981 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8, Legal);
982 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8, Legal);
983 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
984 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
985 setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
987 // i8 and i16 vectors are custom because the source register and source
988 // source memory operand types are not the same width. f32 vectors are
989 // custom since the immediate controlling the insert encodes additional
991 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
992 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
993 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
994 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
996 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
997 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
998 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
999 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1001 // FIXME: these should be Legal, but that's only for the case where
1002 // the index is constant. For now custom expand to deal with that.
1003 if (Subtarget->is64Bit()) {
1004 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1005 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1009 if (Subtarget->hasSSE2()) {
1010 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1011 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1012 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1014 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1015 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1017 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1018 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1020 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1021 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1023 // In the customized shift lowering, the legal cases in AVX2 will be
1025 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1026 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1028 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1029 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1031 setOperationAction(ISD::SRA, MVT::v2i64, Custom);
1032 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1035 if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1036 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1037 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1038 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1039 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1040 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1041 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1043 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1044 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1045 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1047 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1048 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1049 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1050 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1051 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1052 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1053 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1054 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1055 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1056 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1057 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1058 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1060 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1061 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1062 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1063 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1064 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1065 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1066 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1067 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1068 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1069 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1070 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1071 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1073 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1074 // even though v8i16 is a legal type.
1075 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1076 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1077 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1079 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1080 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1081 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1083 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1084 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1086 for (MVT VT : MVT::fp_vector_valuetypes())
1087 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1089 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1090 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1092 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1093 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1095 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1096 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1098 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1099 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1100 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1101 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1103 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1104 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1105 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1107 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1108 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1109 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1110 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1111 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1112 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1113 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1114 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1115 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1116 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1117 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1118 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1120 setOperationAction(ISD::CTPOP, MVT::v32i8, Custom);
1121 setOperationAction(ISD::CTPOP, MVT::v16i16, Custom);
1122 setOperationAction(ISD::CTPOP, MVT::v8i32, Custom);
1123 setOperationAction(ISD::CTPOP, MVT::v4i64, Custom);
1125 if (Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()) {
1126 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1127 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1128 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1129 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1130 setOperationAction(ISD::FMA, MVT::f32, Legal);
1131 setOperationAction(ISD::FMA, MVT::f64, Legal);
1134 if (Subtarget->hasInt256()) {
1135 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1136 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1137 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1138 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1140 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1141 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1142 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1143 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1145 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1146 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1147 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1148 setOperationAction(ISD::MUL, MVT::v32i8, Custom);
1150 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1151 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1152 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1153 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1155 setOperationAction(ISD::SMAX, MVT::v32i8, Legal);
1156 setOperationAction(ISD::SMAX, MVT::v16i16, Legal);
1157 setOperationAction(ISD::SMAX, MVT::v8i32, Legal);
1158 setOperationAction(ISD::UMAX, MVT::v32i8, Legal);
1159 setOperationAction(ISD::UMAX, MVT::v16i16, Legal);
1160 setOperationAction(ISD::UMAX, MVT::v8i32, Legal);
1161 setOperationAction(ISD::SMIN, MVT::v32i8, Legal);
1162 setOperationAction(ISD::SMIN, MVT::v16i16, Legal);
1163 setOperationAction(ISD::SMIN, MVT::v8i32, Legal);
1164 setOperationAction(ISD::UMIN, MVT::v32i8, Legal);
1165 setOperationAction(ISD::UMIN, MVT::v16i16, Legal);
1166 setOperationAction(ISD::UMIN, MVT::v8i32, Legal);
1168 // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1169 // when we have a 256bit-wide blend with immediate.
1170 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1172 // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1173 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1174 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1175 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1176 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1177 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1178 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1180 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1181 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32, MVT::v8i8, Legal);
1182 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i8, Legal);
1183 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32, MVT::v8i16, Legal);
1184 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i16, Legal);
1185 setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64, MVT::v4i32, Legal);
1187 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1188 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1189 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1190 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1192 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1193 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1194 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1195 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1197 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1198 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1199 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1200 setOperationAction(ISD::MUL, MVT::v32i8, Custom);
1203 // In the customized shift lowering, the legal cases in AVX2 will be
1205 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1206 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1208 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1209 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1211 setOperationAction(ISD::SRA, MVT::v4i64, Custom);
1212 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1214 // Custom lower several nodes for 256-bit types.
1215 for (MVT VT : MVT::vector_valuetypes()) {
1216 if (VT.getScalarSizeInBits() >= 32) {
1217 setOperationAction(ISD::MLOAD, VT, Legal);
1218 setOperationAction(ISD::MSTORE, VT, Legal);
1220 // Extract subvector is special because the value type
1221 // (result) is 128-bit but the source is 256-bit wide.
1222 if (VT.is128BitVector()) {
1223 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1225 // Do not attempt to custom lower other non-256-bit vectors
1226 if (!VT.is256BitVector())
1229 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1230 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1231 setOperationAction(ISD::VSELECT, VT, Custom);
1232 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1233 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1234 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1235 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1236 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1239 if (Subtarget->hasInt256())
1240 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1243 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1244 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1245 MVT VT = (MVT::SimpleValueType)i;
1247 // Do not attempt to promote non-256-bit vectors
1248 if (!VT.is256BitVector())
1251 setOperationAction(ISD::AND, VT, Promote);
1252 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1253 setOperationAction(ISD::OR, VT, Promote);
1254 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1255 setOperationAction(ISD::XOR, VT, Promote);
1256 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1257 setOperationAction(ISD::LOAD, VT, Promote);
1258 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1259 setOperationAction(ISD::SELECT, VT, Promote);
1260 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1264 if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1265 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1266 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1267 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1268 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1270 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1271 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1272 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1274 for (MVT VT : MVT::fp_vector_valuetypes())
1275 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1277 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1278 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1279 setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1280 setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1281 setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1282 setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1283 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64, MVT::v8i8, Legal);
1284 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64, MVT::v8i8, Legal);
1285 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64, MVT::v8i16, Legal);
1286 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64, MVT::v8i16, Legal);
1287 setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64, MVT::v8i32, Legal);
1288 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64, MVT::v8i32, Legal);
1290 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1291 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1292 setOperationAction(ISD::XOR, MVT::i1, Legal);
1293 setOperationAction(ISD::OR, MVT::i1, Legal);
1294 setOperationAction(ISD::AND, MVT::i1, Legal);
1295 setOperationAction(ISD::SUB, MVT::i1, Custom);
1296 setOperationAction(ISD::ADD, MVT::i1, Custom);
1297 setOperationAction(ISD::MUL, MVT::i1, Custom);
1298 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1299 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1300 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1301 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1302 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1304 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1305 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1306 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1307 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1308 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1309 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1311 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1312 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1313 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1314 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1315 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1316 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1317 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1318 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1320 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1321 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1322 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1323 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1324 if (Subtarget->is64Bit()) {
1325 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1326 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1327 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1328 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1330 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1331 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1332 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1333 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1334 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1335 setOperationAction(ISD::SINT_TO_FP, MVT::v8i1, Custom);
1336 setOperationAction(ISD::SINT_TO_FP, MVT::v16i1, Custom);
1337 setOperationAction(ISD::SINT_TO_FP, MVT::v16i8, Promote);
1338 setOperationAction(ISD::SINT_TO_FP, MVT::v16i16, Promote);
1339 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1340 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1341 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1342 setOperationAction(ISD::UINT_TO_FP, MVT::v16i8, Custom);
1343 setOperationAction(ISD::UINT_TO_FP, MVT::v16i16, Custom);
1344 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1345 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1347 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Legal);
1348 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Legal);
1349 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Legal);
1350 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Legal);
1351 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Legal);
1352 if (Subtarget->hasVLX()){
1353 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Legal);
1354 setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1355 setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1356 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Legal);
1357 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1359 setTruncStoreAction(MVT::v2i64, MVT::v2i8, Legal);
1360 setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1361 setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1362 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Legal);
1363 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1365 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1366 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1367 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1368 if (Subtarget->hasDQI()) {
1369 setOperationAction(ISD::TRUNCATE, MVT::v2i1, Custom);
1370 setOperationAction(ISD::TRUNCATE, MVT::v4i1, Custom);
1372 setOperationAction(ISD::SINT_TO_FP, MVT::v8i64, Legal);
1373 setOperationAction(ISD::UINT_TO_FP, MVT::v8i64, Legal);
1374 setOperationAction(ISD::FP_TO_SINT, MVT::v8i64, Legal);
1375 setOperationAction(ISD::FP_TO_UINT, MVT::v8i64, Legal);
1376 if (Subtarget->hasVLX()) {
1377 setOperationAction(ISD::SINT_TO_FP, MVT::v4i64, Legal);
1378 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
1379 setOperationAction(ISD::UINT_TO_FP, MVT::v4i64, Legal);
1380 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
1381 setOperationAction(ISD::FP_TO_SINT, MVT::v4i64, Legal);
1382 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
1383 setOperationAction(ISD::FP_TO_UINT, MVT::v4i64, Legal);
1384 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
1387 if (Subtarget->hasVLX()) {
1388 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1389 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1390 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1391 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1392 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1393 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1394 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1395 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1397 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1398 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1399 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1400 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1401 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1402 setOperationAction(ISD::ANY_EXTEND, MVT::v16i32, Custom);
1403 setOperationAction(ISD::ANY_EXTEND, MVT::v8i64, Custom);
1404 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1405 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1406 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1407 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1408 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1409 if (Subtarget->hasDQI()) {
1410 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Custom);
1411 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i64, Custom);
1413 setOperationAction(ISD::FFLOOR, MVT::v16f32, Legal);
1414 setOperationAction(ISD::FFLOOR, MVT::v8f64, Legal);
1415 setOperationAction(ISD::FCEIL, MVT::v16f32, Legal);
1416 setOperationAction(ISD::FCEIL, MVT::v8f64, Legal);
1417 setOperationAction(ISD::FTRUNC, MVT::v16f32, Legal);
1418 setOperationAction(ISD::FTRUNC, MVT::v8f64, Legal);
1419 setOperationAction(ISD::FRINT, MVT::v16f32, Legal);
1420 setOperationAction(ISD::FRINT, MVT::v8f64, Legal);
1421 setOperationAction(ISD::FNEARBYINT, MVT::v16f32, Legal);
1422 setOperationAction(ISD::FNEARBYINT, MVT::v8f64, Legal);
1424 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1425 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1426 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1427 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1428 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1430 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1431 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1433 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1435 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1436 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1437 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1438 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1439 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1440 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1441 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1442 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1443 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1444 setOperationAction(ISD::SELECT, MVT::v16i1, Custom);
1445 setOperationAction(ISD::SELECT, MVT::v8i1, Custom);
1447 setOperationAction(ISD::SMAX, MVT::v16i32, Legal);
1448 setOperationAction(ISD::SMAX, MVT::v8i64, Legal);
1449 setOperationAction(ISD::UMAX, MVT::v16i32, Legal);
1450 setOperationAction(ISD::UMAX, MVT::v8i64, Legal);
1451 setOperationAction(ISD::SMIN, MVT::v16i32, Legal);
1452 setOperationAction(ISD::SMIN, MVT::v8i64, Legal);
1453 setOperationAction(ISD::UMIN, MVT::v16i32, Legal);
1454 setOperationAction(ISD::UMIN, MVT::v8i64, Legal);
1456 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1457 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1459 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1460 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1462 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1464 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1465 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1467 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1468 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1470 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1471 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1473 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1474 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1475 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1476 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1477 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1478 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1480 if (Subtarget->hasCDI()) {
1481 setOperationAction(ISD::CTLZ, MVT::v8i64, Legal);
1482 setOperationAction(ISD::CTLZ, MVT::v16i32, Legal);
1484 if (Subtarget->hasDQI()) {
1485 setOperationAction(ISD::MUL, MVT::v2i64, Legal);
1486 setOperationAction(ISD::MUL, MVT::v4i64, Legal);
1487 setOperationAction(ISD::MUL, MVT::v8i64, Legal);
1489 // Custom lower several nodes.
1490 for (MVT VT : MVT::vector_valuetypes()) {
1491 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1493 setOperationAction(ISD::AND, VT, Legal);
1494 setOperationAction(ISD::OR, VT, Legal);
1495 setOperationAction(ISD::XOR, VT, Legal);
1497 if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1498 setOperationAction(ISD::MGATHER, VT, Custom);
1499 setOperationAction(ISD::MSCATTER, VT, Custom);
1501 // Extract subvector is special because the value type
1502 // (result) is 256/128-bit but the source is 512-bit wide.
1503 if (VT.is128BitVector() || VT.is256BitVector()) {
1504 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1506 if (VT.getVectorElementType() == MVT::i1)
1507 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1509 // Do not attempt to custom lower other non-512-bit vectors
1510 if (!VT.is512BitVector())
1513 if (EltSize >= 32) {
1514 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1515 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1516 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1517 setOperationAction(ISD::VSELECT, VT, Legal);
1518 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1519 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1520 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1521 setOperationAction(ISD::MLOAD, VT, Legal);
1522 setOperationAction(ISD::MSTORE, VT, Legal);
1525 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1526 MVT VT = (MVT::SimpleValueType)i;
1528 // Do not attempt to promote non-512-bit vectors.
1529 if (!VT.is512BitVector())
1532 setOperationAction(ISD::SELECT, VT, Promote);
1533 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1537 if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1538 addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1539 addRegisterClass(MVT::v64i8, &X86::VR512RegClass);
1541 addRegisterClass(MVT::v32i1, &X86::VK32RegClass);
1542 addRegisterClass(MVT::v64i1, &X86::VK64RegClass);
1544 setOperationAction(ISD::LOAD, MVT::v32i16, Legal);
1545 setOperationAction(ISD::LOAD, MVT::v64i8, Legal);
1546 setOperationAction(ISD::SETCC, MVT::v32i1, Custom);
1547 setOperationAction(ISD::SETCC, MVT::v64i1, Custom);
1548 setOperationAction(ISD::ADD, MVT::v32i16, Legal);
1549 setOperationAction(ISD::ADD, MVT::v64i8, Legal);
1550 setOperationAction(ISD::SUB, MVT::v32i16, Legal);
1551 setOperationAction(ISD::SUB, MVT::v64i8, Legal);
1552 setOperationAction(ISD::MUL, MVT::v32i16, Legal);
1553 setOperationAction(ISD::MULHS, MVT::v32i16, Legal);
1554 setOperationAction(ISD::MULHU, MVT::v32i16, Legal);
1555 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i1, Custom);
1556 setOperationAction(ISD::CONCAT_VECTORS, MVT::v64i1, Custom);
1557 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v32i1, Custom);
1558 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v64i1, Custom);
1559 setOperationAction(ISD::SELECT, MVT::v32i1, Custom);
1560 setOperationAction(ISD::SELECT, MVT::v64i1, Custom);
1561 setOperationAction(ISD::SIGN_EXTEND, MVT::v32i8, Custom);
1562 setOperationAction(ISD::ZERO_EXTEND, MVT::v32i8, Custom);
1563 setOperationAction(ISD::SIGN_EXTEND, MVT::v32i16, Custom);
1564 setOperationAction(ISD::ZERO_EXTEND, MVT::v32i16, Custom);
1565 setOperationAction(ISD::SIGN_EXTEND, MVT::v64i8, Custom);
1566 setOperationAction(ISD::ZERO_EXTEND, MVT::v64i8, Custom);
1567 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v32i1, Custom);
1568 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v64i1, Custom);
1569 setOperationAction(ISD::VSELECT, MVT::v32i16, Legal);
1570 setOperationAction(ISD::VSELECT, MVT::v64i8, Legal);
1571 setOperationAction(ISD::TRUNCATE, MVT::v32i1, Custom);
1572 setOperationAction(ISD::TRUNCATE, MVT::v64i1, Custom);
1573 setOperationAction(ISD::TRUNCATE, MVT::v32i8, Custom);
1575 setOperationAction(ISD::SMAX, MVT::v64i8, Legal);
1576 setOperationAction(ISD::SMAX, MVT::v32i16, Legal);
1577 setOperationAction(ISD::UMAX, MVT::v64i8, Legal);
1578 setOperationAction(ISD::UMAX, MVT::v32i16, Legal);
1579 setOperationAction(ISD::SMIN, MVT::v64i8, Legal);
1580 setOperationAction(ISD::SMIN, MVT::v32i16, Legal);
1581 setOperationAction(ISD::UMIN, MVT::v64i8, Legal);
1582 setOperationAction(ISD::UMIN, MVT::v32i16, Legal);
1584 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Legal);
1585 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Legal);
1586 if (Subtarget->hasVLX())
1587 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Legal);
1589 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1590 const MVT VT = (MVT::SimpleValueType)i;
1592 const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1594 // Do not attempt to promote non-512-bit vectors.
1595 if (!VT.is512BitVector())
1599 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1600 setOperationAction(ISD::VSELECT, VT, Legal);
1605 if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1606 addRegisterClass(MVT::v4i1, &X86::VK4RegClass);
1607 addRegisterClass(MVT::v2i1, &X86::VK2RegClass);
1609 setOperationAction(ISD::SETCC, MVT::v4i1, Custom);
1610 setOperationAction(ISD::SETCC, MVT::v2i1, Custom);
1611 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i1, Custom);
1612 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1613 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i1, Custom);
1614 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i1, Custom);
1615 setOperationAction(ISD::SELECT, MVT::v4i1, Custom);
1616 setOperationAction(ISD::SELECT, MVT::v2i1, Custom);
1617 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
1618 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i1, Custom);
1620 setOperationAction(ISD::AND, MVT::v8i32, Legal);
1621 setOperationAction(ISD::OR, MVT::v8i32, Legal);
1622 setOperationAction(ISD::XOR, MVT::v8i32, Legal);
1623 setOperationAction(ISD::AND, MVT::v4i32, Legal);
1624 setOperationAction(ISD::OR, MVT::v4i32, Legal);
1625 setOperationAction(ISD::XOR, MVT::v4i32, Legal);
1626 setOperationAction(ISD::SRA, MVT::v2i64, Custom);
1627 setOperationAction(ISD::SRA, MVT::v4i64, Custom);
1629 setOperationAction(ISD::SMAX, MVT::v2i64, Legal);
1630 setOperationAction(ISD::SMAX, MVT::v4i64, Legal);
1631 setOperationAction(ISD::UMAX, MVT::v2i64, Legal);
1632 setOperationAction(ISD::UMAX, MVT::v4i64, Legal);
1633 setOperationAction(ISD::SMIN, MVT::v2i64, Legal);
1634 setOperationAction(ISD::SMIN, MVT::v4i64, Legal);
1635 setOperationAction(ISD::UMIN, MVT::v2i64, Legal);
1636 setOperationAction(ISD::UMIN, MVT::v4i64, Legal);
1639 // We want to custom lower some of our intrinsics.
1640 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1641 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1642 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1643 if (!Subtarget->is64Bit())
1644 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1646 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1647 // handle type legalization for these operations here.
1649 // FIXME: We really should do custom legalization for addition and
1650 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1651 // than generic legalization for 64-bit multiplication-with-overflow, though.
1652 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1653 // Add/Sub/Mul with overflow operations are custom lowered.
1655 setOperationAction(ISD::SADDO, VT, Custom);
1656 setOperationAction(ISD::UADDO, VT, Custom);
1657 setOperationAction(ISD::SSUBO, VT, Custom);
1658 setOperationAction(ISD::USUBO, VT, Custom);
1659 setOperationAction(ISD::SMULO, VT, Custom);
1660 setOperationAction(ISD::UMULO, VT, Custom);
1664 if (!Subtarget->is64Bit()) {
1665 // These libcalls are not available in 32-bit.
1666 setLibcallName(RTLIB::SHL_I128, nullptr);
1667 setLibcallName(RTLIB::SRL_I128, nullptr);
1668 setLibcallName(RTLIB::SRA_I128, nullptr);
1671 // Combine sin / cos into one node or libcall if possible.
1672 if (Subtarget->hasSinCos()) {
1673 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1674 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1675 if (Subtarget->isTargetDarwin()) {
1676 // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1677 // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1678 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1679 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1683 if (Subtarget->isTargetWin64()) {
1684 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1685 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1686 setOperationAction(ISD::SREM, MVT::i128, Custom);
1687 setOperationAction(ISD::UREM, MVT::i128, Custom);
1688 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1689 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1692 // We have target-specific dag combine patterns for the following nodes:
1693 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1694 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1695 setTargetDAGCombine(ISD::BITCAST);
1696 setTargetDAGCombine(ISD::VSELECT);
1697 setTargetDAGCombine(ISD::SELECT);
1698 setTargetDAGCombine(ISD::SHL);
1699 setTargetDAGCombine(ISD::SRA);
1700 setTargetDAGCombine(ISD::SRL);
1701 setTargetDAGCombine(ISD::OR);
1702 setTargetDAGCombine(ISD::AND);
1703 setTargetDAGCombine(ISD::ADD);
1704 setTargetDAGCombine(ISD::FADD);
1705 setTargetDAGCombine(ISD::FSUB);
1706 setTargetDAGCombine(ISD::FMA);
1707 setTargetDAGCombine(ISD::SUB);
1708 setTargetDAGCombine(ISD::LOAD);
1709 setTargetDAGCombine(ISD::MLOAD);
1710 setTargetDAGCombine(ISD::STORE);
1711 setTargetDAGCombine(ISD::MSTORE);
1712 setTargetDAGCombine(ISD::ZERO_EXTEND);
1713 setTargetDAGCombine(ISD::ANY_EXTEND);
1714 setTargetDAGCombine(ISD::SIGN_EXTEND);
1715 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1716 setTargetDAGCombine(ISD::SINT_TO_FP);
1717 setTargetDAGCombine(ISD::UINT_TO_FP);
1718 setTargetDAGCombine(ISD::SETCC);
1719 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1720 setTargetDAGCombine(ISD::BUILD_VECTOR);
1721 setTargetDAGCombine(ISD::MUL);
1722 setTargetDAGCombine(ISD::XOR);
1724 computeRegisterProperties(Subtarget->getRegisterInfo());
1726 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1727 MaxStoresPerMemsetOptSize = 8;
1728 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1729 MaxStoresPerMemcpyOptSize = 4;
1730 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1731 MaxStoresPerMemmoveOptSize = 4;
1732 setPrefLoopAlignment(4); // 2^4 bytes.
1734 // Predictable cmov don't hurt on atom because it's in-order.
1735 PredictableSelectIsExpensive = !Subtarget->isAtom();
1736 EnableExtLdPromotion = true;
1737 setPrefFunctionAlignment(4); // 2^4 bytes.
1739 verifyIntrinsicTables();
1742 // This has so far only been implemented for 64-bit MachO.
1743 bool X86TargetLowering::useLoadStackGuardNode() const {
1744 return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1747 TargetLoweringBase::LegalizeTypeAction
1748 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1749 if (ExperimentalVectorWideningLegalization &&
1750 VT.getVectorNumElements() != 1 &&
1751 VT.getVectorElementType().getSimpleVT() != MVT::i1)
1752 return TypeWidenVector;
1754 return TargetLoweringBase::getPreferredVectorAction(VT);
1757 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1760 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1762 const unsigned NumElts = VT.getVectorNumElements();
1763 const EVT EltVT = VT.getVectorElementType();
1764 if (VT.is512BitVector()) {
1765 if (Subtarget->hasAVX512())
1766 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1767 EltVT == MVT::f32 || EltVT == MVT::f64)
1769 case 8: return MVT::v8i1;
1770 case 16: return MVT::v16i1;
1772 if (Subtarget->hasBWI())
1773 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1775 case 32: return MVT::v32i1;
1776 case 64: return MVT::v64i1;
1780 if (VT.is256BitVector() || VT.is128BitVector()) {
1781 if (Subtarget->hasVLX())
1782 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1783 EltVT == MVT::f32 || EltVT == MVT::f64)
1785 case 2: return MVT::v2i1;
1786 case 4: return MVT::v4i1;
1787 case 8: return MVT::v8i1;
1789 if (Subtarget->hasBWI() && Subtarget->hasVLX())
1790 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1792 case 8: return MVT::v8i1;
1793 case 16: return MVT::v16i1;
1794 case 32: return MVT::v32i1;
1798 return VT.changeVectorElementTypeToInteger();
1801 /// Helper for getByValTypeAlignment to determine
1802 /// the desired ByVal argument alignment.
1803 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1806 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1807 if (VTy->getBitWidth() == 128)
1809 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1810 unsigned EltAlign = 0;
1811 getMaxByValAlign(ATy->getElementType(), EltAlign);
1812 if (EltAlign > MaxAlign)
1813 MaxAlign = EltAlign;
1814 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1815 for (auto *EltTy : STy->elements()) {
1816 unsigned EltAlign = 0;
1817 getMaxByValAlign(EltTy, EltAlign);
1818 if (EltAlign > MaxAlign)
1819 MaxAlign = EltAlign;
1826 /// Return the desired alignment for ByVal aggregate
1827 /// function arguments in the caller parameter area. For X86, aggregates
1828 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1829 /// are at 4-byte boundaries.
1830 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1831 const DataLayout &DL) const {
1832 if (Subtarget->is64Bit()) {
1833 // Max of 8 and alignment of type.
1834 unsigned TyAlign = DL.getABITypeAlignment(Ty);
1841 if (Subtarget->hasSSE1())
1842 getMaxByValAlign(Ty, Align);
1846 /// Returns the target specific optimal type for load
1847 /// and store operations as a result of memset, memcpy, and memmove
1848 /// lowering. If DstAlign is zero that means it's safe to destination
1849 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1850 /// means there isn't a need to check it against alignment requirement,
1851 /// probably because the source does not need to be loaded. If 'IsMemset' is
1852 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1853 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1854 /// source is constant so it does not need to be loaded.
1855 /// It returns EVT::Other if the type should be determined using generic
1856 /// target-independent logic.
1858 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1859 unsigned DstAlign, unsigned SrcAlign,
1860 bool IsMemset, bool ZeroMemset,
1862 MachineFunction &MF) const {
1863 const Function *F = MF.getFunction();
1864 if ((!IsMemset || ZeroMemset) &&
1865 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1867 (Subtarget->isUnalignedMemAccessFast() ||
1868 ((DstAlign == 0 || DstAlign >= 16) &&
1869 (SrcAlign == 0 || SrcAlign >= 16)))) {
1871 if (Subtarget->hasInt256())
1873 if (Subtarget->hasFp256())
1876 if (Subtarget->hasSSE2())
1878 if (Subtarget->hasSSE1())
1880 } else if (!MemcpyStrSrc && Size >= 8 &&
1881 !Subtarget->is64Bit() &&
1882 Subtarget->hasSSE2()) {
1883 // Do not use f64 to lower memcpy if source is string constant. It's
1884 // better to use i32 to avoid the loads.
1888 if (Subtarget->is64Bit() && Size >= 8)
1893 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1895 return X86ScalarSSEf32;
1896 else if (VT == MVT::f64)
1897 return X86ScalarSSEf64;
1902 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1907 *Fast = Subtarget->isUnalignedMemAccessFast();
1911 /// Return the entry encoding for a jump table in the
1912 /// current function. The returned value is a member of the
1913 /// MachineJumpTableInfo::JTEntryKind enum.
1914 unsigned X86TargetLowering::getJumpTableEncoding() const {
1915 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1917 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1918 Subtarget->isPICStyleGOT())
1919 return MachineJumpTableInfo::EK_Custom32;
1921 // Otherwise, use the normal jump table encoding heuristics.
1922 return TargetLowering::getJumpTableEncoding();
1925 bool X86TargetLowering::useSoftFloat() const {
1926 return Subtarget->useSoftFloat();
1930 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1931 const MachineBasicBlock *MBB,
1932 unsigned uid,MCContext &Ctx) const{
1933 assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1934 Subtarget->isPICStyleGOT());
1935 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1937 return MCSymbolRefExpr::create(MBB->getSymbol(),
1938 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1941 /// Returns relocation base for the given PIC jumptable.
1942 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1943 SelectionDAG &DAG) const {
1944 if (!Subtarget->is64Bit())
1945 // This doesn't have SDLoc associated with it, but is not really the
1946 // same as a Register.
1947 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
1948 getPointerTy(DAG.getDataLayout()));
1952 /// This returns the relocation base for the given PIC jumptable,
1953 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1954 const MCExpr *X86TargetLowering::
1955 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1956 MCContext &Ctx) const {
1957 // X86-64 uses RIP relative addressing based on the jump table label.
1958 if (Subtarget->isPICStyleRIPRel())
1959 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1961 // Otherwise, the reference is relative to the PIC base.
1962 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
1965 std::pair<const TargetRegisterClass *, uint8_t>
1966 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1968 const TargetRegisterClass *RRC = nullptr;
1970 switch (VT.SimpleTy) {
1972 return TargetLowering::findRepresentativeClass(TRI, VT);
1973 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1974 RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1977 RRC = &X86::VR64RegClass;
1979 case MVT::f32: case MVT::f64:
1980 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1981 case MVT::v4f32: case MVT::v2f64:
1982 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1984 RRC = &X86::VR128RegClass;
1987 return std::make_pair(RRC, Cost);
1990 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1991 unsigned &Offset) const {
1992 if (!Subtarget->isTargetLinux())
1995 if (Subtarget->is64Bit()) {
1996 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1998 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2010 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2011 unsigned DestAS) const {
2012 assert(SrcAS != DestAS && "Expected different address spaces!");
2014 return SrcAS < 256 && DestAS < 256;
2017 //===----------------------------------------------------------------------===//
2018 // Return Value Calling Convention Implementation
2019 //===----------------------------------------------------------------------===//
2021 #include "X86GenCallingConv.inc"
2024 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2025 MachineFunction &MF, bool isVarArg,
2026 const SmallVectorImpl<ISD::OutputArg> &Outs,
2027 LLVMContext &Context) const {
2028 SmallVector<CCValAssign, 16> RVLocs;
2029 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2030 return CCInfo.CheckReturn(Outs, RetCC_X86);
2033 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2034 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2039 X86TargetLowering::LowerReturn(SDValue Chain,
2040 CallingConv::ID CallConv, bool isVarArg,
2041 const SmallVectorImpl<ISD::OutputArg> &Outs,
2042 const SmallVectorImpl<SDValue> &OutVals,
2043 SDLoc dl, SelectionDAG &DAG) const {
2044 MachineFunction &MF = DAG.getMachineFunction();
2045 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2047 SmallVector<CCValAssign, 16> RVLocs;
2048 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2049 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2052 SmallVector<SDValue, 6> RetOps;
2053 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2054 // Operand #1 = Bytes To Pop
2055 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2058 // Copy the result values into the output registers.
2059 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2060 CCValAssign &VA = RVLocs[i];
2061 assert(VA.isRegLoc() && "Can only return in registers!");
2062 SDValue ValToCopy = OutVals[i];
2063 EVT ValVT = ValToCopy.getValueType();
2065 // Promote values to the appropriate types.
2066 if (VA.getLocInfo() == CCValAssign::SExt)
2067 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2068 else if (VA.getLocInfo() == CCValAssign::ZExt)
2069 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2070 else if (VA.getLocInfo() == CCValAssign::AExt) {
2071 if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
2072 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2074 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2076 else if (VA.getLocInfo() == CCValAssign::BCvt)
2077 ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2079 assert(VA.getLocInfo() != CCValAssign::FPExt &&
2080 "Unexpected FP-extend for return value.");
2082 // If this is x86-64, and we disabled SSE, we can't return FP values,
2083 // or SSE or MMX vectors.
2084 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2085 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2086 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2087 report_fatal_error("SSE register return with SSE disabled");
2089 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
2090 // llvm-gcc has never done it right and no one has noticed, so this
2091 // should be OK for now.
2092 if (ValVT == MVT::f64 &&
2093 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2094 report_fatal_error("SSE2 register return with SSE2 disabled");
2096 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2097 // the RET instruction and handled by the FP Stackifier.
2098 if (VA.getLocReg() == X86::FP0 ||
2099 VA.getLocReg() == X86::FP1) {
2100 // If this is a copy from an xmm register to ST(0), use an FPExtend to
2101 // change the value to the FP stack register class.
2102 if (isScalarFPTypeInSSEReg(VA.getValVT()))
2103 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2104 RetOps.push_back(ValToCopy);
2105 // Don't emit a copytoreg.
2109 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2110 // which is returned in RAX / RDX.
2111 if (Subtarget->is64Bit()) {
2112 if (ValVT == MVT::x86mmx) {
2113 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2114 ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2115 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2117 // If we don't have SSE2 available, convert to v4f32 so the generated
2118 // register is legal.
2119 if (!Subtarget->hasSSE2())
2120 ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2125 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2126 Flag = Chain.getValue(1);
2127 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2130 // All x86 ABIs require that for returning structs by value we copy
2131 // the sret argument into %rax/%eax (depending on ABI) for the return.
2132 // We saved the argument into a virtual register in the entry block,
2133 // so now we copy the value out and into %rax/%eax.
2135 // Checking Function.hasStructRetAttr() here is insufficient because the IR
2136 // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2137 // false, then an sret argument may be implicitly inserted in the SelDAG. In
2138 // either case FuncInfo->setSRetReturnReg() will have been called.
2139 if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2140 SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2141 getPointerTy(MF.getDataLayout()));
2144 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2145 X86::RAX : X86::EAX;
2146 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2147 Flag = Chain.getValue(1);
2149 // RAX/EAX now acts like a return value.
2151 DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2154 RetOps[0] = Chain; // Update chain.
2156 // Add the flag if we have it.
2158 RetOps.push_back(Flag);
2160 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2163 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2164 if (N->getNumValues() != 1)
2166 if (!N->hasNUsesOfValue(1, 0))
2169 SDValue TCChain = Chain;
2170 SDNode *Copy = *N->use_begin();
2171 if (Copy->getOpcode() == ISD::CopyToReg) {
2172 // If the copy has a glue operand, we conservatively assume it isn't safe to
2173 // perform a tail call.
2174 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2176 TCChain = Copy->getOperand(0);
2177 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2180 bool HasRet = false;
2181 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2183 if (UI->getOpcode() != X86ISD::RET_FLAG)
2185 // If we are returning more than one value, we can definitely
2186 // not make a tail call see PR19530
2187 if (UI->getNumOperands() > 4)
2189 if (UI->getNumOperands() == 4 &&
2190 UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2203 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2204 ISD::NodeType ExtendKind) const {
2206 // TODO: Is this also valid on 32-bit?
2207 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2208 ReturnMVT = MVT::i8;
2210 ReturnMVT = MVT::i32;
2212 EVT MinVT = getRegisterType(Context, ReturnMVT);
2213 return VT.bitsLT(MinVT) ? MinVT : VT;
2216 /// Lower the result values of a call into the
2217 /// appropriate copies out of appropriate physical registers.
2220 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2221 CallingConv::ID CallConv, bool isVarArg,
2222 const SmallVectorImpl<ISD::InputArg> &Ins,
2223 SDLoc dl, SelectionDAG &DAG,
2224 SmallVectorImpl<SDValue> &InVals) const {
2226 // Assign locations to each value returned by this call.
2227 SmallVector<CCValAssign, 16> RVLocs;
2228 bool Is64Bit = Subtarget->is64Bit();
2229 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2231 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2233 // Copy all of the result registers out of their specified physreg.
2234 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2235 CCValAssign &VA = RVLocs[i];
2236 EVT CopyVT = VA.getLocVT();
2238 // If this is x86-64, and we disabled SSE, we can't return FP values
2239 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2240 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2241 report_fatal_error("SSE register return with SSE disabled");
2244 // If we prefer to use the value in xmm registers, copy it out as f80 and
2245 // use a truncate to move it from fp stack reg to xmm reg.
2246 bool RoundAfterCopy = false;
2247 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2248 isScalarFPTypeInSSEReg(VA.getValVT())) {
2250 RoundAfterCopy = (CopyVT != VA.getLocVT());
2253 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2254 CopyVT, InFlag).getValue(1);
2255 SDValue Val = Chain.getValue(0);
2258 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2259 // This truncation won't change the value.
2260 DAG.getIntPtrConstant(1, dl));
2262 if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2263 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2265 InFlag = Chain.getValue(2);
2266 InVals.push_back(Val);
2272 //===----------------------------------------------------------------------===//
2273 // C & StdCall & Fast Calling Convention implementation
2274 //===----------------------------------------------------------------------===//
2275 // StdCall calling convention seems to be standard for many Windows' API
2276 // routines and around. It differs from C calling convention just a little:
2277 // callee should clean up the stack, not caller. Symbols should be also
2278 // decorated in some fancy way :) It doesn't support any vector arguments.
2279 // For info on fast calling convention see Fast Calling Convention (tail call)
2280 // implementation LowerX86_32FastCCCallTo.
2282 /// CallIsStructReturn - Determines whether a call uses struct return
2284 enum StructReturnType {
2289 static StructReturnType
2290 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2292 return NotStructReturn;
2294 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2295 if (!Flags.isSRet())
2296 return NotStructReturn;
2297 if (Flags.isInReg())
2298 return RegStructReturn;
2299 return StackStructReturn;
2302 /// Determines whether a function uses struct return semantics.
2303 static StructReturnType
2304 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2306 return NotStructReturn;
2308 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2309 if (!Flags.isSRet())
2310 return NotStructReturn;
2311 if (Flags.isInReg())
2312 return RegStructReturn;
2313 return StackStructReturn;
2316 /// Make a copy of an aggregate at address specified by "Src" to address
2317 /// "Dst" with size and alignment information specified by the specific
2318 /// parameter attribute. The copy will be passed as a byval function parameter.
2320 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2321 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2323 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2325 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2326 /*isVolatile*/false, /*AlwaysInline=*/true,
2327 /*isTailCall*/false,
2328 MachinePointerInfo(), MachinePointerInfo());
2331 /// Return true if the calling convention is one that
2332 /// supports tail call optimization.
2333 static bool IsTailCallConvention(CallingConv::ID CC) {
2334 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2335 CC == CallingConv::HiPE);
2338 /// \brief Return true if the calling convention is a C calling convention.
2339 static bool IsCCallConvention(CallingConv::ID CC) {
2340 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2341 CC == CallingConv::X86_64_SysV);
2344 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2346 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2347 if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2351 CallingConv::ID CalleeCC = CS.getCallingConv();
2352 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2358 /// Return true if the function is being made into
2359 /// a tailcall target by changing its ABI.
2360 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2361 bool GuaranteedTailCallOpt) {
2362 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2366 X86TargetLowering::LowerMemArgument(SDValue Chain,
2367 CallingConv::ID CallConv,
2368 const SmallVectorImpl<ISD::InputArg> &Ins,
2369 SDLoc dl, SelectionDAG &DAG,
2370 const CCValAssign &VA,
2371 MachineFrameInfo *MFI,
2373 // Create the nodes corresponding to a load from this parameter slot.
2374 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2375 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2376 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2377 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2380 // If value is passed by pointer we have address passed instead of the value
2382 bool ExtendedInMem = VA.isExtInLoc() &&
2383 VA.getValVT().getScalarType() == MVT::i1;
2385 if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2386 ValVT = VA.getLocVT();
2388 ValVT = VA.getValVT();
2390 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2391 // changed with more analysis.
2392 // In case of tail call optimization mark all arguments mutable. Since they
2393 // could be overwritten by lowering of arguments in case of a tail call.
2394 if (Flags.isByVal()) {
2395 unsigned Bytes = Flags.getByValSize();
2396 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2397 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2398 return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2400 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2401 VA.getLocMemOffset(), isImmutable);
2402 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2403 SDValue Val = DAG.getLoad(ValVT, dl, Chain, FIN,
2404 MachinePointerInfo::getFixedStack(FI),
2405 false, false, false, 0);
2406 return ExtendedInMem ?
2407 DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2411 // FIXME: Get this from tablegen.
2412 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2413 const X86Subtarget *Subtarget) {
2414 assert(Subtarget->is64Bit());
2416 if (Subtarget->isCallingConvWin64(CallConv)) {
2417 static const MCPhysReg GPR64ArgRegsWin64[] = {
2418 X86::RCX, X86::RDX, X86::R8, X86::R9
2420 return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2423 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2424 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2426 return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2429 // FIXME: Get this from tablegen.
2430 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2431 CallingConv::ID CallConv,
2432 const X86Subtarget *Subtarget) {
2433 assert(Subtarget->is64Bit());
2434 if (Subtarget->isCallingConvWin64(CallConv)) {
2435 // The XMM registers which might contain var arg parameters are shadowed
2436 // in their paired GPR. So we only need to save the GPR to their home
2438 // TODO: __vectorcall will change this.
2442 const Function *Fn = MF.getFunction();
2443 bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2444 bool isSoftFloat = Subtarget->useSoftFloat();
2445 assert(!(isSoftFloat && NoImplicitFloatOps) &&
2446 "SSE register cannot be used when SSE is disabled!");
2447 if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2448 // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2452 static const MCPhysReg XMMArgRegs64Bit[] = {
2453 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2454 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2456 return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2460 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2461 CallingConv::ID CallConv,
2463 const SmallVectorImpl<ISD::InputArg> &Ins,
2466 SmallVectorImpl<SDValue> &InVals)
2468 MachineFunction &MF = DAG.getMachineFunction();
2469 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2470 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2472 const Function* Fn = MF.getFunction();
2473 if (Fn->hasExternalLinkage() &&
2474 Subtarget->isTargetCygMing() &&
2475 Fn->getName() == "main")
2476 FuncInfo->setForceFramePointer(true);
2478 MachineFrameInfo *MFI = MF.getFrameInfo();
2479 bool Is64Bit = Subtarget->is64Bit();
2480 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2482 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2483 "Var args not supported with calling convention fastcc, ghc or hipe");
2485 // Assign locations to all of the incoming arguments.
2486 SmallVector<CCValAssign, 16> ArgLocs;
2487 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2489 // Allocate shadow area for Win64
2491 CCInfo.AllocateStack(32, 8);
2493 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2495 unsigned LastVal = ~0U;
2497 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2498 CCValAssign &VA = ArgLocs[i];
2499 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2501 assert(VA.getValNo() != LastVal &&
2502 "Don't support value assigned to multiple locs yet");
2504 LastVal = VA.getValNo();
2506 if (VA.isRegLoc()) {
2507 EVT RegVT = VA.getLocVT();
2508 const TargetRegisterClass *RC;
2509 if (RegVT == MVT::i32)
2510 RC = &X86::GR32RegClass;
2511 else if (Is64Bit && RegVT == MVT::i64)
2512 RC = &X86::GR64RegClass;
2513 else if (RegVT == MVT::f32)
2514 RC = &X86::FR32RegClass;
2515 else if (RegVT == MVT::f64)
2516 RC = &X86::FR64RegClass;
2517 else if (RegVT.is512BitVector())
2518 RC = &X86::VR512RegClass;
2519 else if (RegVT.is256BitVector())
2520 RC = &X86::VR256RegClass;
2521 else if (RegVT.is128BitVector())
2522 RC = &X86::VR128RegClass;
2523 else if (RegVT == MVT::x86mmx)
2524 RC = &X86::VR64RegClass;
2525 else if (RegVT == MVT::i1)
2526 RC = &X86::VK1RegClass;
2527 else if (RegVT == MVT::v8i1)
2528 RC = &X86::VK8RegClass;
2529 else if (RegVT == MVT::v16i1)
2530 RC = &X86::VK16RegClass;
2531 else if (RegVT == MVT::v32i1)
2532 RC = &X86::VK32RegClass;
2533 else if (RegVT == MVT::v64i1)
2534 RC = &X86::VK64RegClass;
2536 llvm_unreachable("Unknown argument type!");
2538 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2539 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2541 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2542 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2544 if (VA.getLocInfo() == CCValAssign::SExt)
2545 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2546 DAG.getValueType(VA.getValVT()));
2547 else if (VA.getLocInfo() == CCValAssign::ZExt)
2548 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2549 DAG.getValueType(VA.getValVT()));
2550 else if (VA.getLocInfo() == CCValAssign::BCvt)
2551 ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2553 if (VA.isExtInLoc()) {
2554 // Handle MMX values passed in XMM regs.
2555 if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2556 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2558 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2561 assert(VA.isMemLoc());
2562 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2565 // If value is passed via pointer - do a load.
2566 if (VA.getLocInfo() == CCValAssign::Indirect)
2567 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2568 MachinePointerInfo(), false, false, false, 0);
2570 InVals.push_back(ArgValue);
2573 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2574 // All x86 ABIs require that for returning structs by value we copy the
2575 // sret argument into %rax/%eax (depending on ABI) for the return. Save
2576 // the argument into a virtual register so that we can access it from the
2578 if (Ins[i].Flags.isSRet()) {
2579 unsigned Reg = FuncInfo->getSRetReturnReg();
2581 MVT PtrTy = getPointerTy(DAG.getDataLayout());
2582 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2583 FuncInfo->setSRetReturnReg(Reg);
2585 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2586 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2591 unsigned StackSize = CCInfo.getNextStackOffset();
2592 // Align stack specially for tail calls.
2593 if (FuncIsMadeTailCallSafe(CallConv,
2594 MF.getTarget().Options.GuaranteedTailCallOpt))
2595 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2597 // If the function takes variable number of arguments, make a frame index for
2598 // the start of the first vararg value... for expansion of llvm.va_start. We
2599 // can skip this if there are no va_start calls.
2600 if (MFI->hasVAStart() &&
2601 (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2602 CallConv != CallingConv::X86_ThisCall))) {
2603 FuncInfo->setVarArgsFrameIndex(
2604 MFI->CreateFixedObject(1, StackSize, true));
2607 MachineModuleInfo &MMI = MF.getMMI();
2608 const Function *WinEHParent = nullptr;
2609 if (MMI.hasWinEHFuncInfo(Fn))
2610 WinEHParent = MMI.getWinEHParent(Fn);
2611 bool IsWinEHOutlined = WinEHParent && WinEHParent != Fn;
2612 bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2614 // Figure out if XMM registers are in use.
2615 assert(!(Subtarget->useSoftFloat() &&
2616 Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2617 "SSE register cannot be used when SSE is disabled!");
2619 // 64-bit calling conventions support varargs and register parameters, so we
2620 // have to do extra work to spill them in the prologue.
2621 if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2622 // Find the first unallocated argument registers.
2623 ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2624 ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2625 unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2626 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2627 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2628 "SSE register cannot be used when SSE is disabled!");
2630 // Gather all the live in physical registers.
2631 SmallVector<SDValue, 6> LiveGPRs;
2632 SmallVector<SDValue, 8> LiveXMMRegs;
2634 for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2635 unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2637 DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2639 if (!ArgXMMs.empty()) {
2640 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2641 ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2642 for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2643 unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2644 LiveXMMRegs.push_back(
2645 DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2650 // Get to the caller-allocated home save location. Add 8 to account
2651 // for the return address.
2652 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2653 FuncInfo->setRegSaveFrameIndex(
2654 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2655 // Fixup to set vararg frame on shadow area (4 x i64).
2657 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2659 // For X86-64, if there are vararg parameters that are passed via
2660 // registers, then we must store them to their spots on the stack so
2661 // they may be loaded by deferencing the result of va_next.
2662 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2663 FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2664 FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2665 ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2668 // Store the integer parameter registers.
2669 SmallVector<SDValue, 8> MemOps;
2670 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2671 getPointerTy(DAG.getDataLayout()));
2672 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2673 for (SDValue Val : LiveGPRs) {
2674 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2675 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2677 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2678 MachinePointerInfo::getFixedStack(
2679 FuncInfo->getRegSaveFrameIndex(), Offset),
2681 MemOps.push_back(Store);
2685 if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2686 // Now store the XMM (fp + vector) parameter registers.
2687 SmallVector<SDValue, 12> SaveXMMOps;
2688 SaveXMMOps.push_back(Chain);
2689 SaveXMMOps.push_back(ALVal);
2690 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2691 FuncInfo->getRegSaveFrameIndex(), dl));
2692 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2693 FuncInfo->getVarArgsFPOffset(), dl));
2694 SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2696 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2697 MVT::Other, SaveXMMOps));
2700 if (!MemOps.empty())
2701 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2702 } else if (IsWin64 && IsWinEHOutlined) {
2703 // Get to the caller-allocated home save location. Add 8 to account
2704 // for the return address.
2705 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2706 FuncInfo->setRegSaveFrameIndex(MFI->CreateFixedObject(
2707 /*Size=*/1, /*SPOffset=*/HomeOffset + 8, /*Immutable=*/false));
2709 MMI.getWinEHFuncInfo(Fn)
2710 .CatchHandlerParentFrameObjIdx[const_cast<Function *>(Fn)] =
2711 FuncInfo->getRegSaveFrameIndex();
2713 // Store the second integer parameter (rdx) into rsp+16 relative to the
2714 // stack pointer at the entry of the function.
2715 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2716 getPointerTy(DAG.getDataLayout()));
2717 unsigned GPR = MF.addLiveIn(X86::RDX, &X86::GR64RegClass);
2718 SDValue Val = DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64);
2719 Chain = DAG.getStore(
2720 Val.getValue(1), dl, Val, RSFIN,
2721 MachinePointerInfo::getFixedStack(FuncInfo->getRegSaveFrameIndex()),
2722 /*isVolatile=*/true, /*isNonTemporal=*/false, /*Alignment=*/0);
2725 if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2726 // Find the largest legal vector type.
2727 MVT VecVT = MVT::Other;
2728 // FIXME: Only some x86_32 calling conventions support AVX512.
2729 if (Subtarget->hasAVX512() &&
2730 (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2731 CallConv == CallingConv::Intel_OCL_BI)))
2732 VecVT = MVT::v16f32;
2733 else if (Subtarget->hasAVX())
2735 else if (Subtarget->hasSSE2())
2738 // We forward some GPRs and some vector types.
2739 SmallVector<MVT, 2> RegParmTypes;
2740 MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2741 RegParmTypes.push_back(IntVT);
2742 if (VecVT != MVT::Other)
2743 RegParmTypes.push_back(VecVT);
2745 // Compute the set of forwarded registers. The rest are scratch.
2746 SmallVectorImpl<ForwardedRegister> &Forwards =
2747 FuncInfo->getForwardedMustTailRegParms();
2748 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2750 // Conservatively forward AL on x86_64, since it might be used for varargs.
2751 if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2752 unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2753 Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2756 // Copy all forwards from physical to virtual registers.
2757 for (ForwardedRegister &F : Forwards) {
2758 // FIXME: Can we use a less constrained schedule?
2759 SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2760 F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2761 Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2765 // Some CCs need callee pop.
2766 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2767 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2768 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2770 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2771 // If this is an sret function, the return should pop the hidden pointer.
2772 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2773 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2774 argsAreStructReturn(Ins) == StackStructReturn)
2775 FuncInfo->setBytesToPopOnReturn(4);
2779 // RegSaveFrameIndex is X86-64 only.
2780 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2781 if (CallConv == CallingConv::X86_FastCall ||
2782 CallConv == CallingConv::X86_ThisCall)
2783 // fastcc functions can't have varargs.
2784 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2787 FuncInfo->setArgumentStackSize(StackSize);
2789 if (IsWinEHParent) {
2791 int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2792 SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2793 MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2794 SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2795 Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2796 MachinePointerInfo::getFixedStack(UnwindHelpFI),
2797 /*isVolatile=*/true,
2798 /*isNonTemporal=*/false, /*Alignment=*/0);
2800 // Functions using Win32 EH are considered to have opaque SP adjustments
2801 // to force local variables to be addressed from the frame or base
2803 MFI->setHasOpaqueSPAdjustment(true);
2811 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2812 SDValue StackPtr, SDValue Arg,
2813 SDLoc dl, SelectionDAG &DAG,
2814 const CCValAssign &VA,
2815 ISD::ArgFlagsTy Flags) const {
2816 unsigned LocMemOffset = VA.getLocMemOffset();
2817 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2818 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2820 if (Flags.isByVal())
2821 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2823 return DAG.getStore(Chain, dl, Arg, PtrOff,
2824 MachinePointerInfo::getStack(LocMemOffset),
2828 /// Emit a load of return address if tail call
2829 /// optimization is performed and it is required.
2831 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2832 SDValue &OutRetAddr, SDValue Chain,
2833 bool IsTailCall, bool Is64Bit,
2834 int FPDiff, SDLoc dl) const {
2835 // Adjust the Return address stack slot.
2836 EVT VT = getPointerTy(DAG.getDataLayout());
2837 OutRetAddr = getReturnAddressFrameIndex(DAG);
2839 // Load the "old" Return address.
2840 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2841 false, false, false, 0);
2842 return SDValue(OutRetAddr.getNode(), 1);
2845 /// Emit a store of the return address if tail call
2846 /// optimization is performed and it is required (FPDiff!=0).
2847 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2848 SDValue Chain, SDValue RetAddrFrIdx,
2849 EVT PtrVT, unsigned SlotSize,
2850 int FPDiff, SDLoc dl) {
2851 // Store the return address to the appropriate stack slot.
2852 if (!FPDiff) return Chain;
2853 // Calculate the new stack slot for the return address.
2854 int NewReturnAddrFI =
2855 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2857 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2858 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2859 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2864 /// Returns a vector_shuffle mask for an movs{s|d}, movd
2865 /// operation of specified width.
2866 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
2868 unsigned NumElems = VT.getVectorNumElements();
2869 SmallVector<int, 8> Mask;
2870 Mask.push_back(NumElems);
2871 for (unsigned i = 1; i != NumElems; ++i)
2873 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2877 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2878 SmallVectorImpl<SDValue> &InVals) const {
2879 SelectionDAG &DAG = CLI.DAG;
2881 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2882 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2883 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2884 SDValue Chain = CLI.Chain;
2885 SDValue Callee = CLI.Callee;
2886 CallingConv::ID CallConv = CLI.CallConv;
2887 bool &isTailCall = CLI.IsTailCall;
2888 bool isVarArg = CLI.IsVarArg;
2890 MachineFunction &MF = DAG.getMachineFunction();
2891 bool Is64Bit = Subtarget->is64Bit();
2892 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2893 StructReturnType SR = callIsStructReturn(Outs);
2894 bool IsSibcall = false;
2895 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2896 auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
2898 if (Attr.getValueAsString() == "true")
2901 if (Subtarget->isPICStyleGOT() &&
2902 !MF.getTarget().Options.GuaranteedTailCallOpt) {
2903 // If we are using a GOT, disable tail calls to external symbols with
2904 // default visibility. Tail calling such a symbol requires using a GOT
2905 // relocation, which forces early binding of the symbol. This breaks code
2906 // that require lazy function symbol resolution. Using musttail or
2907 // GuaranteedTailCallOpt will override this.
2908 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2909 if (!G || (!G->getGlobal()->hasLocalLinkage() &&
2910 G->getGlobal()->hasDefaultVisibility()))
2914 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2916 // Force this to be a tail call. The verifier rules are enough to ensure
2917 // that we can lower this successfully without moving the return address
2920 } else if (isTailCall) {
2921 // Check if it's really possible to do a tail call.
2922 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2923 isVarArg, SR != NotStructReturn,
2924 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2925 Outs, OutVals, Ins, DAG);
2927 // Sibcalls are automatically detected tailcalls which do not require
2929 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2936 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2937 "Var args not supported with calling convention fastcc, ghc or hipe");
2939 // Analyze operands of the call, assigning locations to each operand.
2940 SmallVector<CCValAssign, 16> ArgLocs;
2941 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2943 // Allocate shadow area for Win64
2945 CCInfo.AllocateStack(32, 8);
2947 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2949 // Get a count of how many bytes are to be pushed on the stack.
2950 unsigned NumBytes = CCInfo.getNextStackOffset();
2952 // This is a sibcall. The memory operands are available in caller's
2953 // own caller's stack.
2955 else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2956 IsTailCallConvention(CallConv))
2957 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2960 if (isTailCall && !IsSibcall && !IsMustTail) {
2961 // Lower arguments at fp - stackoffset + fpdiff.
2962 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2964 FPDiff = NumBytesCallerPushed - NumBytes;
2966 // Set the delta of movement of the returnaddr stackslot.
2967 // But only set if delta is greater than previous delta.
2968 if (FPDiff < X86Info->getTCReturnAddrDelta())
2969 X86Info->setTCReturnAddrDelta(FPDiff);
2972 unsigned NumBytesToPush = NumBytes;
2973 unsigned NumBytesToPop = NumBytes;
2975 // If we have an inalloca argument, all stack space has already been allocated
2976 // for us and be right at the top of the stack. We don't support multiple
2977 // arguments passed in memory when using inalloca.
2978 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2980 if (!ArgLocs.back().isMemLoc())
2981 report_fatal_error("cannot use inalloca attribute on a register "
2983 if (ArgLocs.back().getLocMemOffset() != 0)
2984 report_fatal_error("any parameter with the inalloca attribute must be "
2985 "the only memory argument");
2989 Chain = DAG.getCALLSEQ_START(
2990 Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
2992 SDValue RetAddrFrIdx;
2993 // Load return address for tail calls.
2994 if (isTailCall && FPDiff)
2995 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2996 Is64Bit, FPDiff, dl);
2998 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2999 SmallVector<SDValue, 8> MemOpChains;
3002 // Walk the register/memloc assignments, inserting copies/loads. In the case
3003 // of tail call optimization arguments are handle later.
3004 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3005 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3006 // Skip inalloca arguments, they have already been written.
3007 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3008 if (Flags.isInAlloca())
3011 CCValAssign &VA = ArgLocs[i];
3012 EVT RegVT = VA.getLocVT();
3013 SDValue Arg = OutVals[i];
3014 bool isByVal = Flags.isByVal();
3016 // Promote the value if needed.
3017 switch (VA.getLocInfo()) {
3018 default: llvm_unreachable("Unknown loc info!");
3019 case CCValAssign::Full: break;
3020 case CCValAssign::SExt:
3021 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3023 case CCValAssign::ZExt:
3024 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3026 case CCValAssign::AExt:
3027 if (Arg.getValueType().isVector() &&
3028 Arg.getValueType().getScalarType() == MVT::i1)
3029 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3030 else if (RegVT.is128BitVector()) {
3031 // Special case: passing MMX values in XMM registers.
3032 Arg = DAG.getBitcast(MVT::i64, Arg);
3033 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3034 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3036 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3038 case CCValAssign::BCvt:
3039 Arg = DAG.getBitcast(RegVT, Arg);
3041 case CCValAssign::Indirect: {
3042 // Store the argument.
3043 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3044 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3045 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
3046 MachinePointerInfo::getFixedStack(FI),
3053 if (VA.isRegLoc()) {
3054 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3055 if (isVarArg && IsWin64) {
3056 // Win64 ABI requires argument XMM reg to be copied to the corresponding
3057 // shadow reg if callee is a varargs function.
3058 unsigned ShadowReg = 0;
3059 switch (VA.getLocReg()) {
3060 case X86::XMM0: ShadowReg = X86::RCX; break;
3061 case X86::XMM1: ShadowReg = X86::RDX; break;
3062 case X86::XMM2: ShadowReg = X86::R8; break;
3063 case X86::XMM3: ShadowReg = X86::R9; break;
3066 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3068 } else if (!IsSibcall && (!isTailCall || isByVal)) {
3069 assert(VA.isMemLoc());
3070 if (!StackPtr.getNode())
3071 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3072 getPointerTy(DAG.getDataLayout()));
3073 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3074 dl, DAG, VA, Flags));
3078 if (!MemOpChains.empty())
3079 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3081 if (Subtarget->isPICStyleGOT()) {
3082 // ELF / PIC requires GOT in the EBX register before function calls via PLT
3085 RegsToPass.push_back(std::make_pair(
3086 unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3087 getPointerTy(DAG.getDataLayout()))));
3089 // If we are tail calling and generating PIC/GOT style code load the
3090 // address of the callee into ECX. The value in ecx is used as target of
3091 // the tail jump. This is done to circumvent the ebx/callee-saved problem
3092 // for tail calls on PIC/GOT architectures. Normally we would just put the
3093 // address of GOT into ebx and then call target@PLT. But for tail calls
3094 // ebx would be restored (since ebx is callee saved) before jumping to the
3097 // Note: The actual moving to ECX is done further down.
3098 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3099 if (G && !G->getGlobal()->hasLocalLinkage() &&
3100 G->getGlobal()->hasDefaultVisibility())
3101 Callee = LowerGlobalAddress(Callee, DAG);
3102 else if (isa<ExternalSymbolSDNode>(Callee))
3103 Callee = LowerExternalSymbol(Callee, DAG);
3107 if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3108 // From AMD64 ABI document:
3109 // For calls that may call functions that use varargs or stdargs
3110 // (prototype-less calls or calls to functions containing ellipsis (...) in
3111 // the declaration) %al is used as hidden argument to specify the number
3112 // of SSE registers used. The contents of %al do not need to match exactly
3113 // the number of registers, but must be an ubound on the number of SSE
3114 // registers used and is in the range 0 - 8 inclusive.
3116 // Count the number of XMM registers allocated.
3117 static const MCPhysReg XMMArgRegs[] = {
3118 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3119 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3121 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3122 assert((Subtarget->hasSSE1() || !NumXMMRegs)
3123 && "SSE registers cannot be used when SSE is disabled");
3125 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3126 DAG.getConstant(NumXMMRegs, dl,
3130 if (isVarArg && IsMustTail) {
3131 const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3132 for (const auto &F : Forwards) {
3133 SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3134 RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3138 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
3139 // don't need this because the eligibility check rejects calls that require
3140 // shuffling arguments passed in memory.
3141 if (!IsSibcall && isTailCall) {
3142 // Force all the incoming stack arguments to be loaded from the stack
3143 // before any new outgoing arguments are stored to the stack, because the
3144 // outgoing stack slots may alias the incoming argument stack slots, and
3145 // the alias isn't otherwise explicit. This is slightly more conservative
3146 // than necessary, because it means that each store effectively depends
3147 // on every argument instead of just those arguments it would clobber.
3148 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3150 SmallVector<SDValue, 8> MemOpChains2;
3153 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3154 CCValAssign &VA = ArgLocs[i];
3157 assert(VA.isMemLoc());
3158 SDValue Arg = OutVals[i];
3159 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3160 // Skip inalloca arguments. They don't require any work.
3161 if (Flags.isInAlloca())
3163 // Create frame index.
3164 int32_t Offset = VA.getLocMemOffset()+FPDiff;
3165 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3166 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3167 FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3169 if (Flags.isByVal()) {
3170 // Copy relative to framepointer.
3171 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3172 if (!StackPtr.getNode())
3173 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3174 getPointerTy(DAG.getDataLayout()));
3175 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3178 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3182 // Store relative to framepointer.
3183 MemOpChains2.push_back(
3184 DAG.getStore(ArgChain, dl, Arg, FIN,
3185 MachinePointerInfo::getFixedStack(FI),
3190 if (!MemOpChains2.empty())
3191 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3193 // Store the return address to the appropriate stack slot.
3194 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3195 getPointerTy(DAG.getDataLayout()),
3196 RegInfo->getSlotSize(), FPDiff, dl);
3199 // Build a sequence of copy-to-reg nodes chained together with token chain
3200 // and flag operands which copy the outgoing args into registers.
3202 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3203 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3204 RegsToPass[i].second, InFlag);
3205 InFlag = Chain.getValue(1);
3208 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3209 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3210 // In the 64-bit large code model, we have to make all calls
3211 // through a register, since the call instruction's 32-bit
3212 // pc-relative offset may not be large enough to hold the whole
3214 } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3215 // If the callee is a GlobalAddress node (quite common, every direct call
3216 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3218 GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3220 // We should use extra load for direct calls to dllimported functions in
3222 const GlobalValue *GV = G->getGlobal();
3223 if (!GV->hasDLLImportStorageClass()) {
3224 unsigned char OpFlags = 0;
3225 bool ExtraLoad = false;
3226 unsigned WrapperKind = ISD::DELETED_NODE;
3228 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3229 // external symbols most go through the PLT in PIC mode. If the symbol
3230 // has hidden or protected visibility, or if it is static or local, then
3231 // we don't need to use the PLT - we can directly call it.
3232 if (Subtarget->isTargetELF() &&
3233 DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3234 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3235 OpFlags = X86II::MO_PLT;
3236 } else if (Subtarget->isPICStyleStubAny() &&
3237 !GV->isStrongDefinitionForLinker() &&
3238 (!Subtarget->getTargetTriple().isMacOSX() ||
3239 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3240 // PC-relative references to external symbols should go through $stub,
3241 // unless we're building with the leopard linker or later, which
3242 // automatically synthesizes these stubs.
3243 OpFlags = X86II::MO_DARWIN_STUB;
3244 } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3245 cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3246 // If the function is marked as non-lazy, generate an indirect call
3247 // which loads from the GOT directly. This avoids runtime overhead
3248 // at the cost of eager binding (and one extra byte of encoding).
3249 OpFlags = X86II::MO_GOTPCREL;
3250 WrapperKind = X86ISD::WrapperRIP;
3254 Callee = DAG.getTargetGlobalAddress(
3255 GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3257 // Add a wrapper if needed.
3258 if (WrapperKind != ISD::DELETED_NODE)
3259 Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3260 getPointerTy(DAG.getDataLayout()), Callee);
3261 // Add extra indirection if needed.
3263 Callee = DAG.getLoad(
3264 getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3265 MachinePointerInfo::getGOT(), false, false, false, 0);
3267 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3268 unsigned char OpFlags = 0;
3270 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3271 // external symbols should go through the PLT.
3272 if (Subtarget->isTargetELF() &&
3273 DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3274 OpFlags = X86II::MO_PLT;
3275 } else if (Subtarget->isPICStyleStubAny() &&
3276 (!Subtarget->getTargetTriple().isMacOSX() ||
3277 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3278 // PC-relative references to external symbols should go through $stub,
3279 // unless we're building with the leopard linker or later, which
3280 // automatically synthesizes these stubs.
3281 OpFlags = X86II::MO_DARWIN_STUB;
3284 Callee = DAG.getTargetExternalSymbol(
3285 S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3286 } else if (Subtarget->isTarget64BitILP32() &&
3287 Callee->getValueType(0) == MVT::i32) {
3288 // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3289 Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3292 // Returns a chain & a flag for retval copy to use.
3293 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3294 SmallVector<SDValue, 8> Ops;
3296 if (!IsSibcall && isTailCall) {
3297 Chain = DAG.getCALLSEQ_END(Chain,
3298 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3299 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3300 InFlag = Chain.getValue(1);
3303 Ops.push_back(Chain);
3304 Ops.push_back(Callee);
3307 Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3309 // Add argument registers to the end of the list so that they are known live
3311 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3312 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3313 RegsToPass[i].second.getValueType()));
3315 // Add a register mask operand representing the call-preserved registers.
3316 const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3317 assert(Mask && "Missing call preserved mask for calling convention");
3319 // If this is an invoke in a 32-bit function using an MSVC personality, assume
3320 // the function clobbers all registers. If an exception is thrown, the runtime
3321 // will not restore CSRs.
3322 // FIXME: Model this more precisely so that we can register allocate across
3323 // the normal edge and spill and fill across the exceptional edge.
3324 if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3325 const Function *CallerFn = MF.getFunction();
3326 EHPersonality Pers =
3327 CallerFn->hasPersonalityFn()
3328 ? classifyEHPersonality(CallerFn->getPersonalityFn())
3329 : EHPersonality::Unknown;
3330 if (isMSVCEHPersonality(Pers))
3331 Mask = RegInfo->getNoPreservedMask();
3334 Ops.push_back(DAG.getRegisterMask(Mask));
3336 if (InFlag.getNode())
3337 Ops.push_back(InFlag);
3341 //// If this is the first return lowered for this function, add the regs
3342 //// to the liveout set for the function.
3343 // This isn't right, although it's probably harmless on x86; liveouts
3344 // should be computed from returns not tail calls. Consider a void
3345 // function making a tail call to a function returning int.
3346 MF.getFrameInfo()->setHasTailCall();
3347 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3350 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3351 InFlag = Chain.getValue(1);
3353 // Create the CALLSEQ_END node.
3354 unsigned NumBytesForCalleeToPop;
3355 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3356 DAG.getTarget().Options.GuaranteedTailCallOpt))
3357 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
3358 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3359 !Subtarget->getTargetTriple().isOSMSVCRT() &&
3360 SR == StackStructReturn)
3361 // If this is a call to a struct-return function, the callee
3362 // pops the hidden struct pointer, so we have to push it back.
3363 // This is common for Darwin/X86, Linux & Mingw32 targets.
3364 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3365 NumBytesForCalleeToPop = 4;
3367 NumBytesForCalleeToPop = 0; // Callee pops nothing.
3369 // Returns a flag for retval copy to use.
3371 Chain = DAG.getCALLSEQ_END(Chain,
3372 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3373 DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3376 InFlag = Chain.getValue(1);
3379 // Handle result values, copying them out of physregs into vregs that we
3381 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3382 Ins, dl, DAG, InVals);
3385 //===----------------------------------------------------------------------===//
3386 // Fast Calling Convention (tail call) implementation
3387 //===----------------------------------------------------------------------===//
3389 // Like std call, callee cleans arguments, convention except that ECX is
3390 // reserved for storing the tail called function address. Only 2 registers are
3391 // free for argument passing (inreg). Tail call optimization is performed
3393 // * tailcallopt is enabled
3394 // * caller/callee are fastcc
3395 // On X86_64 architecture with GOT-style position independent code only local
3396 // (within module) calls are supported at the moment.
3397 // To keep the stack aligned according to platform abi the function
3398 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3399 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3400 // If a tail called function callee has more arguments than the caller the
3401 // caller needs to make sure that there is room to move the RETADDR to. This is
3402 // achieved by reserving an area the size of the argument delta right after the
3403 // original RETADDR, but before the saved framepointer or the spilled registers
3404 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3416 /// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
3419 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3420 SelectionDAG& DAG) const {
3421 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3422 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3423 unsigned StackAlignment = TFI.getStackAlignment();
3424 uint64_t AlignMask = StackAlignment - 1;
3425 int64_t Offset = StackSize;
3426 unsigned SlotSize = RegInfo->getSlotSize();
3427 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3428 // Number smaller than 12 so just add the difference.
3429 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3431 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3432 Offset = ((~AlignMask) & Offset) + StackAlignment +
3433 (StackAlignment-SlotSize);
3438 /// Return true if the given stack call argument is already available in the
3439 /// same position (relatively) of the caller's incoming argument stack.
3441 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3442 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3443 const X86InstrInfo *TII) {
3444 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3446 if (Arg.getOpcode() == ISD::CopyFromReg) {
3447 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3448 if (!TargetRegisterInfo::isVirtualRegister(VR))
3450 MachineInstr *Def = MRI->getVRegDef(VR);
3453 if (!Flags.isByVal()) {
3454 if (!TII->isLoadFromStackSlot(Def, FI))
3457 unsigned Opcode = Def->getOpcode();
3458 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3459 Opcode == X86::LEA64_32r) &&
3460 Def->getOperand(1).isFI()) {
3461 FI = Def->getOperand(1).getIndex();
3462 Bytes = Flags.getByValSize();
3466 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3467 if (Flags.isByVal())
3468 // ByVal argument is passed in as a pointer but it's now being
3469 // dereferenced. e.g.
3470 // define @foo(%struct.X* %A) {
3471 // tail call @bar(%struct.X* byval %A)
3474 SDValue Ptr = Ld->getBasePtr();
3475 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3478 FI = FINode->getIndex();
3479 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3480 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3481 FI = FINode->getIndex();
3482 Bytes = Flags.getByValSize();
3486 assert(FI != INT_MAX);
3487 if (!MFI->isFixedObjectIndex(FI))
3489 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3492 /// Check whether the call is eligible for tail call optimization. Targets
3493 /// that want to do tail call optimization should implement this function.
3495 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3496 CallingConv::ID CalleeCC,
3498 bool isCalleeStructRet,
3499 bool isCallerStructRet,
3501 const SmallVectorImpl<ISD::OutputArg> &Outs,
3502 const SmallVectorImpl<SDValue> &OutVals,
3503 const SmallVectorImpl<ISD::InputArg> &Ins,
3504 SelectionDAG &DAG) const {
3505 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3508 // If -tailcallopt is specified, make fastcc functions tail-callable.
3509 const MachineFunction &MF = DAG.getMachineFunction();
3510 const Function *CallerF = MF.getFunction();
3512 // If the function return type is x86_fp80 and the callee return type is not,
3513 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3514 // perform a tailcall optimization here.
3515 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3518 CallingConv::ID CallerCC = CallerF->getCallingConv();
3519 bool CCMatch = CallerCC == CalleeCC;
3520 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3521 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3523 // Win64 functions have extra shadow space for argument homing. Don't do the
3524 // sibcall if the caller and callee have mismatched expectations for this
3526 if (IsCalleeWin64 != IsCallerWin64)
3529 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3530 if (IsTailCallConvention(CalleeCC) && CCMatch)
3535 // Look for obvious safe cases to perform tail call optimization that do not
3536 // require ABI changes. This is what gcc calls sibcall.
3538 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3539 // emit a special epilogue.
3540 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3541 if (RegInfo->needsStackRealignment(MF))
3544 // Also avoid sibcall optimization if either caller or callee uses struct
3545 // return semantics.
3546 if (isCalleeStructRet || isCallerStructRet)
3549 // An stdcall/thiscall caller is expected to clean up its arguments; the
3550 // callee isn't going to do that.
3551 // FIXME: this is more restrictive than needed. We could produce a tailcall
3552 // when the stack adjustment matches. For example, with a thiscall that takes
3553 // only one argument.
3554 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3555 CallerCC == CallingConv::X86_ThisCall))
3558 // Do not sibcall optimize vararg calls unless all arguments are passed via
3560 if (isVarArg && !Outs.empty()) {
3562 // Optimizing for varargs on Win64 is unlikely to be safe without
3563 // additional testing.
3564 if (IsCalleeWin64 || IsCallerWin64)
3567 SmallVector<CCValAssign, 16> ArgLocs;
3568 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3571 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3572 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3573 if (!ArgLocs[i].isRegLoc())
3577 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3578 // stack. Therefore, if it's not used by the call it is not safe to optimize
3579 // this into a sibcall.
3580 bool Unused = false;
3581 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3588 SmallVector<CCValAssign, 16> RVLocs;
3589 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3591 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3592 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3593 CCValAssign &VA = RVLocs[i];
3594 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3599 // If the calling conventions do not match, then we'd better make sure the
3600 // results are returned in the same way as what the caller expects.
3602 SmallVector<CCValAssign, 16> RVLocs1;
3603 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3605 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3607 SmallVector<CCValAssign, 16> RVLocs2;
3608 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3610 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3612 if (RVLocs1.size() != RVLocs2.size())
3614 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3615 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3617 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3619 if (RVLocs1[i].isRegLoc()) {
3620 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3623 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3629 // If the callee takes no arguments then go on to check the results of the
3631 if (!Outs.empty()) {
3632 // Check if stack adjustment is needed. For now, do not do this if any
3633 // argument is passed on the stack.
3634 SmallVector<CCValAssign, 16> ArgLocs;
3635 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3638 // Allocate shadow area for Win64
3640 CCInfo.AllocateStack(32, 8);
3642 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3643 if (CCInfo.getNextStackOffset()) {
3644 MachineFunction &MF = DAG.getMachineFunction();
3645 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3648 // Check if the arguments are already laid out in the right way as
3649 // the caller's fixed stack objects.
3650 MachineFrameInfo *MFI = MF.getFrameInfo();
3651 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3652 const X86InstrInfo *TII = Subtarget->getInstrInfo();
3653 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3654 CCValAssign &VA = ArgLocs[i];
3655 SDValue Arg = OutVals[i];
3656 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3657 if (VA.getLocInfo() == CCValAssign::Indirect)
3659 if (!VA.isRegLoc()) {
3660 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3667 // If the tailcall address may be in a register, then make sure it's
3668 // possible to register allocate for it. In 32-bit, the call address can
3669 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3670 // callee-saved registers are restored. These happen to be the same
3671 // registers used to pass 'inreg' arguments so watch out for those.
3672 if (!Subtarget->is64Bit() &&
3673 ((!isa<GlobalAddressSDNode>(Callee) &&
3674 !isa<ExternalSymbolSDNode>(Callee)) ||
3675 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3676 unsigned NumInRegs = 0;
3677 // In PIC we need an extra register to formulate the address computation
3679 unsigned MaxInRegs =
3680 (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3682 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3683 CCValAssign &VA = ArgLocs[i];
3686 unsigned Reg = VA.getLocReg();
3689 case X86::EAX: case X86::EDX: case X86::ECX:
3690 if (++NumInRegs == MaxInRegs)
3702 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3703 const TargetLibraryInfo *libInfo) const {
3704 return X86::createFastISel(funcInfo, libInfo);
3707 //===----------------------------------------------------------------------===//
3708 // Other Lowering Hooks
3709 //===----------------------------------------------------------------------===//
3711 static bool MayFoldLoad(SDValue Op) {
3712 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3715 static bool MayFoldIntoStore(SDValue Op) {
3716 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3719 static bool isTargetShuffle(unsigned Opcode) {
3721 default: return false;
3722 case X86ISD::BLENDI:
3723 case X86ISD::PSHUFB:
3724 case X86ISD::PSHUFD:
3725 case X86ISD::PSHUFHW:
3726 case X86ISD::PSHUFLW:
3728 case X86ISD::PALIGNR:
3729 case X86ISD::MOVLHPS:
3730 case X86ISD::MOVLHPD:
3731 case X86ISD::MOVHLPS:
3732 case X86ISD::MOVLPS:
3733 case X86ISD::MOVLPD:
3734 case X86ISD::MOVSHDUP:
3735 case X86ISD::MOVSLDUP:
3736 case X86ISD::MOVDDUP:
3739 case X86ISD::UNPCKL:
3740 case X86ISD::UNPCKH:
3741 case X86ISD::VPERMILPI:
3742 case X86ISD::VPERM2X128:
3743 case X86ISD::VPERMI:
3748 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3749 SDValue V1, unsigned TargetMask,
3750 SelectionDAG &DAG) {
3752 default: llvm_unreachable("Unknown x86 shuffle node");
3753 case X86ISD::PSHUFD:
3754 case X86ISD::PSHUFHW:
3755 case X86ISD::PSHUFLW:
3756 case X86ISD::VPERMILPI:
3757 case X86ISD::VPERMI:
3758 return DAG.getNode(Opc, dl, VT, V1,
3759 DAG.getConstant(TargetMask, dl, MVT::i8));
3763 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3764 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3766 default: llvm_unreachable("Unknown x86 shuffle node");
3767 case X86ISD::MOVLHPS:
3768 case X86ISD::MOVLHPD:
3769 case X86ISD::MOVHLPS:
3770 case X86ISD::MOVLPS:
3771 case X86ISD::MOVLPD:
3774 case X86ISD::UNPCKL:
3775 case X86ISD::UNPCKH:
3776 return DAG.getNode(Opc, dl, VT, V1, V2);
3780 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3781 MachineFunction &MF = DAG.getMachineFunction();
3782 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3783 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3784 int ReturnAddrIndex = FuncInfo->getRAIndex();
3786 if (ReturnAddrIndex == 0) {
3787 // Set up a frame object for the return address.
3788 unsigned SlotSize = RegInfo->getSlotSize();
3789 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3792 FuncInfo->setRAIndex(ReturnAddrIndex);
3795 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3798 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3799 bool hasSymbolicDisplacement) {
3800 // Offset should fit into 32 bit immediate field.
3801 if (!isInt<32>(Offset))
3804 // If we don't have a symbolic displacement - we don't have any extra
3806 if (!hasSymbolicDisplacement)
3809 // FIXME: Some tweaks might be needed for medium code model.
3810 if (M != CodeModel::Small && M != CodeModel::Kernel)
3813 // For small code model we assume that latest object is 16MB before end of 31
3814 // bits boundary. We may also accept pretty large negative constants knowing
3815 // that all objects are in the positive half of address space.
3816 if (M == CodeModel::Small && Offset < 16*1024*1024)
3819 // For kernel code model we know that all object resist in the negative half
3820 // of 32bits address space. We may not accept negative offsets, since they may
3821 // be just off and we may accept pretty large positive ones.
3822 if (M == CodeModel::Kernel && Offset >= 0)
3828 /// Determines whether the callee is required to pop its own arguments.
3829 /// Callee pop is necessary to support tail calls.
3830 bool X86::isCalleePop(CallingConv::ID CallingConv,
3831 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3832 switch (CallingConv) {
3835 case CallingConv::X86_StdCall:
3836 case CallingConv::X86_FastCall:
3837 case CallingConv::X86_ThisCall:
3839 case CallingConv::Fast:
3840 case CallingConv::GHC:
3841 case CallingConv::HiPE:
3848 /// \brief Return true if the condition is an unsigned comparison operation.
3849 static bool isX86CCUnsigned(unsigned X86CC) {
3851 default: llvm_unreachable("Invalid integer condition!");
3852 case X86::COND_E: return true;
3853 case X86::COND_G: return false;
3854 case X86::COND_GE: return false;
3855 case X86::COND_L: return false;
3856 case X86::COND_LE: return false;
3857 case X86::COND_NE: return true;
3858 case X86::COND_B: return true;
3859 case X86::COND_A: return true;
3860 case X86::COND_BE: return true;
3861 case X86::COND_AE: return true;
3863 llvm_unreachable("covered switch fell through?!");
3866 /// Do a one-to-one translation of a ISD::CondCode to the X86-specific
3867 /// condition code, returning the condition code and the LHS/RHS of the
3868 /// comparison to make.
3869 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3870 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3872 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3873 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3874 // X > -1 -> X == 0, jump !sign.
3875 RHS = DAG.getConstant(0, DL, RHS.getValueType());
3876 return X86::COND_NS;
3878 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3879 // X < 0 -> X == 0, jump on sign.
3882 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3884 RHS = DAG.getConstant(0, DL, RHS.getValueType());
3885 return X86::COND_LE;
3889 switch (SetCCOpcode) {
3890 default: llvm_unreachable("Invalid integer condition!");
3891 case ISD::SETEQ: return X86::COND_E;
3892 case ISD::SETGT: return X86::COND_G;
3893 case ISD::SETGE: return X86::COND_GE;
3894 case ISD::SETLT: return X86::COND_L;
3895 case ISD::SETLE: return X86::COND_LE;
3896 case ISD::SETNE: return X86::COND_NE;
3897 case ISD::SETULT: return X86::COND_B;
3898 case ISD::SETUGT: return X86::COND_A;
3899 case ISD::SETULE: return X86::COND_BE;
3900 case ISD::SETUGE: return X86::COND_AE;
3904 // First determine if it is required or is profitable to flip the operands.
3906 // If LHS is a foldable load, but RHS is not, flip the condition.
3907 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3908 !ISD::isNON_EXTLoad(RHS.getNode())) {
3909 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3910 std::swap(LHS, RHS);
3913 switch (SetCCOpcode) {
3919 std::swap(LHS, RHS);
3923 // On a floating point condition, the flags are set as follows:
3925 // 0 | 0 | 0 | X > Y
3926 // 0 | 0 | 1 | X < Y
3927 // 1 | 0 | 0 | X == Y
3928 // 1 | 1 | 1 | unordered
3929 switch (SetCCOpcode) {
3930 default: llvm_unreachable("Condcode should be pre-legalized away");
3932 case ISD::SETEQ: return X86::COND_E;
3933 case ISD::SETOLT: // flipped
3935 case ISD::SETGT: return X86::COND_A;
3936 case ISD::SETOLE: // flipped
3938 case ISD::SETGE: return X86::COND_AE;
3939 case ISD::SETUGT: // flipped
3941 case ISD::SETLT: return X86::COND_B;
3942 case ISD::SETUGE: // flipped
3944 case ISD::SETLE: return X86::COND_BE;
3946 case ISD::SETNE: return X86::COND_NE;
3947 case ISD::SETUO: return X86::COND_P;
3948 case ISD::SETO: return X86::COND_NP;
3950 case ISD::SETUNE: return X86::COND_INVALID;
3954 /// Is there a floating point cmov for the specific X86 condition code?
3955 /// Current x86 isa includes the following FP cmov instructions:
3956 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3957 static bool hasFPCMov(unsigned X86CC) {
3973 /// Returns true if the target can instruction select the
3974 /// specified FP immediate natively. If false, the legalizer will
3975 /// materialize the FP immediate as a load from a constant pool.
3976 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3977 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3978 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3984 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3985 ISD::LoadExtType ExtTy,
3987 // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3988 // relocation target a movq or addq instruction: don't let the load shrink.
3989 SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3990 if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3991 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3992 return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3996 /// \brief Returns true if it is beneficial to convert a load of a constant
3997 /// to just the constant itself.
3998 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
4000 assert(Ty->isIntegerTy());
4002 unsigned BitSize = Ty->getPrimitiveSizeInBits();
4003 if (BitSize == 0 || BitSize > 64)
4008 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
4009 unsigned Index) const {
4010 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4013 return (Index == 0 || Index == ResVT.getVectorNumElements());
4016 bool X86TargetLowering::isCheapToSpeculateCttz() const {
4017 // Speculate cttz only if we can directly use TZCNT.
4018 return Subtarget->hasBMI();
4021 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4022 // Speculate ctlz only if we can directly use LZCNT.
4023 return Subtarget->hasLZCNT();
4026 /// Return true if every element in Mask, beginning
4027 /// from position Pos and ending in Pos+Size is undef.
4028 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4029 for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4035 /// Return true if Val is undef or if its value falls within the
4036 /// specified range (L, H].
4037 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4038 return (Val < 0) || (Val >= Low && Val < Hi);
4041 /// Val is either less than zero (undef) or equal to the specified value.
4042 static bool isUndefOrEqual(int Val, int CmpVal) {
4043 return (Val < 0 || Val == CmpVal);
4046 /// Return true if every element in Mask, beginning
4047 /// from position Pos and ending in Pos+Size, falls within the specified
4048 /// sequential range (Low, Low+Size]. or is undef.
4049 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4050 unsigned Pos, unsigned Size, int Low) {
4051 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4052 if (!isUndefOrEqual(Mask[i], Low))
4057 /// Return true if the specified EXTRACT_SUBVECTOR operand specifies a vector
4058 /// extract that is suitable for instruction that extract 128 or 256 bit vectors
4059 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4060 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4061 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4064 // The index should be aligned on a vecWidth-bit boundary.
4066 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4068 MVT VT = N->getSimpleValueType(0);
4069 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4070 bool Result = (Index * ElSize) % vecWidth == 0;
4075 /// Return true if the specified INSERT_SUBVECTOR
4076 /// operand specifies a subvector insert that is suitable for input to
4077 /// insertion of 128 or 256-bit subvectors
4078 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4079 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4080 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4082 // The index should be aligned on a vecWidth-bit boundary.
4084 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4086 MVT VT = N->getSimpleValueType(0);
4087 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4088 bool Result = (Index * ElSize) % vecWidth == 0;
4093 bool X86::isVINSERT128Index(SDNode *N) {
4094 return isVINSERTIndex(N, 128);
4097 bool X86::isVINSERT256Index(SDNode *N) {
4098 return isVINSERTIndex(N, 256);
4101 bool X86::isVEXTRACT128Index(SDNode *N) {
4102 return isVEXTRACTIndex(N, 128);
4105 bool X86::isVEXTRACT256Index(SDNode *N) {
4106 return isVEXTRACTIndex(N, 256);
4109 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4110 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4111 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4112 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4115 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4117 MVT VecVT = N->getOperand(0).getSimpleValueType();
4118 MVT ElVT = VecVT.getVectorElementType();
4120 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4121 return Index / NumElemsPerChunk;
4124 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4125 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4126 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4127 llvm_unreachable("Illegal insert subvector for VINSERT");
4130 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4132 MVT VecVT = N->getSimpleValueType(0);
4133 MVT ElVT = VecVT.getVectorElementType();
4135 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4136 return Index / NumElemsPerChunk;
4139 /// Return the appropriate immediate to extract the specified
4140 /// EXTRACT_SUBVECTOR index with VEXTRACTF128 and VINSERTI128 instructions.
4141 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4142 return getExtractVEXTRACTImmediate(N, 128);
4145 /// Return the appropriate immediate to extract the specified
4146 /// EXTRACT_SUBVECTOR index with VEXTRACTF64x4 and VINSERTI64x4 instructions.
4147 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4148 return getExtractVEXTRACTImmediate(N, 256);
4151 /// Return the appropriate immediate to insert at the specified
4152 /// INSERT_SUBVECTOR index with VINSERTF128 and VINSERTI128 instructions.
4153 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4154 return getInsertVINSERTImmediate(N, 128);
4157 /// Return the appropriate immediate to insert at the specified
4158 /// INSERT_SUBVECTOR index with VINSERTF46x4 and VINSERTI64x4 instructions.
4159 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4160 return getInsertVINSERTImmediate(N, 256);
4163 /// Returns true if Elt is a constant integer zero
4164 static bool isZero(SDValue V) {
4165 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4166 return C && C->isNullValue();
4169 /// Returns true if Elt is a constant zero or a floating point constant +0.0.
4170 bool X86::isZeroNode(SDValue Elt) {
4173 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4174 return CFP->getValueAPF().isPosZero();
4178 /// Returns a vector of specified type with all zero elements.
4179 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4180 SelectionDAG &DAG, SDLoc dl) {
4181 assert(VT.isVector() && "Expected a vector type");
4183 // Always build SSE zero vectors as <4 x i32> bitcasted
4184 // to their dest type. This ensures they get CSE'd.
4186 if (VT.is128BitVector()) { // SSE
4187 if (Subtarget->hasSSE2()) { // SSE2
4188 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4189 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4191 SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4192 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4194 } else if (VT.is256BitVector()) { // AVX
4195 if (Subtarget->hasInt256()) { // AVX2
4196 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4197 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4198 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4200 // 256-bit logic and arithmetic instructions in AVX are all
4201 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4202 SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4203 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4204 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4206 } else if (VT.is512BitVector()) { // AVX-512
4207 SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4208 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4209 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4210 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4211 } else if (VT.getScalarType() == MVT::i1) {
4213 assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4214 && "Unexpected vector type");
4215 assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4216 && "Unexpected vector type");
4217 SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4218 SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4219 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4221 llvm_unreachable("Unexpected vector type");
4223 return DAG.getBitcast(VT, Vec);
4226 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4227 SelectionDAG &DAG, SDLoc dl,
4228 unsigned vectorWidth) {
4229 assert((vectorWidth == 128 || vectorWidth == 256) &&
4230 "Unsupported vector width");
4231 EVT VT = Vec.getValueType();
4232 EVT ElVT = VT.getVectorElementType();
4233 unsigned Factor = VT.getSizeInBits()/vectorWidth;
4234 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4235 VT.getVectorNumElements()/Factor);
4237 // Extract from UNDEF is UNDEF.
4238 if (Vec.getOpcode() == ISD::UNDEF)
4239 return DAG.getUNDEF(ResultVT);
4241 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
4242 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4244 // This is the index of the first element of the vectorWidth-bit chunk
4246 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4249 // If the input is a buildvector just emit a smaller one.
4250 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4251 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4252 makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4255 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4256 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4259 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
4260 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4261 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4262 /// instructions or a simple subregister reference. Idx is an index in the
4263 /// 128 bits we want. It need not be aligned to a 128-bit boundary. That makes
4264 /// lowering EXTRACT_VECTOR_ELT operations easier.
4265 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4266 SelectionDAG &DAG, SDLoc dl) {
4267 assert((Vec.getValueType().is256BitVector() ||
4268 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4269 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4272 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4273 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4274 SelectionDAG &DAG, SDLoc dl) {
4275 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4276 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4279 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4280 unsigned IdxVal, SelectionDAG &DAG,
4281 SDLoc dl, unsigned vectorWidth) {
4282 assert((vectorWidth == 128 || vectorWidth == 256) &&
4283 "Unsupported vector width");
4284 // Inserting UNDEF is Result
4285 if (Vec.getOpcode() == ISD::UNDEF)
4287 EVT VT = Vec.getValueType();
4288 EVT ElVT = VT.getVectorElementType();
4289 EVT ResultVT = Result.getValueType();
4291 // Insert the relevant vectorWidth bits.
4292 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4294 // This is the index of the first element of the vectorWidth-bit chunk
4296 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4299 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4300 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4303 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
4304 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4305 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4306 /// simple superregister reference. Idx is an index in the 128 bits
4307 /// we want. It need not be aligned to a 128-bit boundary. That makes
4308 /// lowering INSERT_VECTOR_ELT operations easier.
4309 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4310 SelectionDAG &DAG, SDLoc dl) {
4311 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4313 // For insertion into the zero index (low half) of a 256-bit vector, it is
4314 // more efficient to generate a blend with immediate instead of an insert*128.
4315 // We are still creating an INSERT_SUBVECTOR below with an undef node to
4316 // extend the subvector to the size of the result vector. Make sure that
4317 // we are not recursing on that node by checking for undef here.
4318 if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4319 Result.getOpcode() != ISD::UNDEF) {
4320 EVT ResultVT = Result.getValueType();
4321 SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4322 SDValue Undef = DAG.getUNDEF(ResultVT);
4323 SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4326 // The blend instruction, and therefore its mask, depend on the data type.
4327 MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4328 if (ScalarType.isFloatingPoint()) {
4329 // Choose either vblendps (float) or vblendpd (double).
4330 unsigned ScalarSize = ScalarType.getSizeInBits();
4331 assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4332 unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4333 SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4334 return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4337 const X86Subtarget &Subtarget =
4338 static_cast<const X86Subtarget &>(DAG.getSubtarget());
4340 // AVX2 is needed for 256-bit integer blend support.
4341 // Integers must be cast to 32-bit because there is only vpblendd;
4342 // vpblendw can't be used for this because it has a handicapped mask.
4344 // If we don't have AVX2, then cast to float. Using a wrong domain blend
4345 // is still more efficient than using the wrong domain vinsertf128 that
4346 // will be created by InsertSubVector().
4347 MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4349 SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4350 Vec256 = DAG.getBitcast(CastVT, Vec256);
4351 Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4352 return DAG.getBitcast(ResultVT, Vec256);
4355 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4358 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4359 SelectionDAG &DAG, SDLoc dl) {
4360 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4361 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4364 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4365 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4366 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4367 /// large BUILD_VECTORS.
4368 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4369 unsigned NumElems, SelectionDAG &DAG,
4371 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4372 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4375 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4376 unsigned NumElems, SelectionDAG &DAG,
4378 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4379 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4382 /// Returns a vector of specified type with all bits set.
4383 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4384 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4385 /// Then bitcast to their original type, ensuring they get CSE'd.
4386 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4388 assert(VT.isVector() && "Expected a vector type");
4390 SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4392 if (VT.is256BitVector()) {
4393 if (HasInt256) { // AVX2
4394 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4395 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4397 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4398 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4400 } else if (VT.is128BitVector()) {
4401 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4403 llvm_unreachable("Unexpected vector type");
4405 return DAG.getBitcast(VT, Vec);
4408 /// Returns a vector_shuffle node for an unpackl operation.
4409 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4411 unsigned NumElems = VT.getVectorNumElements();
4412 SmallVector<int, 8> Mask;
4413 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4415 Mask.push_back(i + NumElems);
4417 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4420 /// Returns a vector_shuffle node for an unpackh operation.
4421 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4423 unsigned NumElems = VT.getVectorNumElements();
4424 SmallVector<int, 8> Mask;
4425 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4426 Mask.push_back(i + Half);
4427 Mask.push_back(i + NumElems + Half);
4429 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4432 /// Return a vector_shuffle of the specified vector of zero or undef vector.
4433 /// This produces a shuffle where the low element of V2 is swizzled into the
4434 /// zero/undef vector, landing at element Idx.
4435 /// This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4436 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4438 const X86Subtarget *Subtarget,
4439 SelectionDAG &DAG) {
4440 MVT VT = V2.getSimpleValueType();
4442 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4443 unsigned NumElems = VT.getVectorNumElements();
4444 SmallVector<int, 16> MaskVec;
4445 for (unsigned i = 0; i != NumElems; ++i)
4446 // If this is the insertion idx, put the low elt of V2 here.
4447 MaskVec.push_back(i == Idx ? NumElems : i);
4448 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4451 /// Calculates the shuffle mask corresponding to the target-specific opcode.
4452 /// Returns true if the Mask could be calculated. Sets IsUnary to true if only
4453 /// uses one source. Note that this will set IsUnary for shuffles which use a
4454 /// single input multiple times, and in those cases it will
4455 /// adjust the mask to only have indices within that single input.
4456 /// FIXME: Add support for Decode*Mask functions that return SM_SentinelZero.
4457 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4458 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4459 unsigned NumElems = VT.getVectorNumElements();
4463 bool IsFakeUnary = false;
4464 switch(N->getOpcode()) {
4465 case X86ISD::BLENDI:
4466 ImmN = N->getOperand(N->getNumOperands()-1);
4467 DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4470 ImmN = N->getOperand(N->getNumOperands()-1);
4471 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4472 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4474 case X86ISD::UNPCKH:
4475 DecodeUNPCKHMask(VT, Mask);
4476 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4478 case X86ISD::UNPCKL:
4479 DecodeUNPCKLMask(VT, Mask);
4480 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4482 case X86ISD::MOVHLPS:
4483 DecodeMOVHLPSMask(NumElems, Mask);
4484 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4486 case X86ISD::MOVLHPS:
4487 DecodeMOVLHPSMask(NumElems, Mask);
4488 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4490 case X86ISD::PALIGNR:
4491 ImmN = N->getOperand(N->getNumOperands()-1);
4492 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4494 case X86ISD::PSHUFD:
4495 case X86ISD::VPERMILPI:
4496 ImmN = N->getOperand(N->getNumOperands()-1);
4497 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4500 case X86ISD::PSHUFHW:
4501 ImmN = N->getOperand(N->getNumOperands()-1);
4502 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4505 case X86ISD::PSHUFLW:
4506 ImmN = N->getOperand(N->getNumOperands()-1);
4507 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4510 case X86ISD::PSHUFB: {
4512 SDValue MaskNode = N->getOperand(1);
4513 while (MaskNode->getOpcode() == ISD::BITCAST)
4514 MaskNode = MaskNode->getOperand(0);
4516 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4517 // If we have a build-vector, then things are easy.
4518 EVT VT = MaskNode.getValueType();
4519 assert(VT.isVector() &&
4520 "Can't produce a non-vector with a build_vector!");
4521 if (!VT.isInteger())
4524 int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4526 SmallVector<uint64_t, 32> RawMask;
4527 for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4528 SDValue Op = MaskNode->getOperand(i);
4529 if (Op->getOpcode() == ISD::UNDEF) {
4530 RawMask.push_back((uint64_t)SM_SentinelUndef);
4533 auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4536 APInt MaskElement = CN->getAPIntValue();
4538 // We now have to decode the element which could be any integer size and
4539 // extract each byte of it.
4540 for (int j = 0; j < NumBytesPerElement; ++j) {
4541 // Note that this is x86 and so always little endian: the low byte is
4542 // the first byte of the mask.
4543 RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4544 MaskElement = MaskElement.lshr(8);
4547 DecodePSHUFBMask(RawMask, Mask);
4551 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4555 SDValue Ptr = MaskLoad->getBasePtr();
4556 if (Ptr->getOpcode() == X86ISD::Wrapper ||
4557 Ptr->getOpcode() == X86ISD::WrapperRIP)
4558 Ptr = Ptr->getOperand(0);
4560 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4561 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4564 if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4565 DecodePSHUFBMask(C, Mask);
4573 case X86ISD::VPERMI:
4574 ImmN = N->getOperand(N->getNumOperands()-1);
4575 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4580 DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4582 case X86ISD::VPERM2X128:
4583 ImmN = N->getOperand(N->getNumOperands()-1);
4584 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4585 if (Mask.empty()) return false;
4586 // Mask only contains negative index if an element is zero.
4587 if (std::any_of(Mask.begin(), Mask.end(),
4588 [](int M){ return M == SM_SentinelZero; }))
4591 case X86ISD::MOVSLDUP:
4592 DecodeMOVSLDUPMask(VT, Mask);
4595 case X86ISD::MOVSHDUP:
4596 DecodeMOVSHDUPMask(VT, Mask);
4599 case X86ISD::MOVDDUP:
4600 DecodeMOVDDUPMask(VT, Mask);
4603 case X86ISD::MOVLHPD:
4604 case X86ISD::MOVLPD:
4605 case X86ISD::MOVLPS:
4606 // Not yet implemented
4608 default: llvm_unreachable("unknown target shuffle node");
4611 // If we have a fake unary shuffle, the shuffle mask is spread across two
4612 // inputs that are actually the same node. Re-map the mask to always point
4613 // into the first input.
4616 if (M >= (int)Mask.size())
4622 /// Returns the scalar element that will make up the ith
4623 /// element of the result of the vector shuffle.
4624 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4627 return SDValue(); // Limit search depth.
4629 SDValue V = SDValue(N, 0);
4630 EVT VT = V.getValueType();
4631 unsigned Opcode = V.getOpcode();
4633 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4634 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4635 int Elt = SV->getMaskElt(Index);
4638 return DAG.getUNDEF(VT.getVectorElementType());
4640 unsigned NumElems = VT.getVectorNumElements();
4641 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4642 : SV->getOperand(1);
4643 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4646 // Recurse into target specific vector shuffles to find scalars.
4647 if (isTargetShuffle(Opcode)) {
4648 MVT ShufVT = V.getSimpleValueType();
4649 unsigned NumElems = ShufVT.getVectorNumElements();
4650 SmallVector<int, 16> ShuffleMask;
4653 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4656 int Elt = ShuffleMask[Index];
4658 return DAG.getUNDEF(ShufVT.getVectorElementType());
4660 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4662 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4666 // Actual nodes that may contain scalar elements
4667 if (Opcode == ISD::BITCAST) {
4668 V = V.getOperand(0);
4669 EVT SrcVT = V.getValueType();
4670 unsigned NumElems = VT.getVectorNumElements();
4672 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4676 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4677 return (Index == 0) ? V.getOperand(0)
4678 : DAG.getUNDEF(VT.getVectorElementType());
4680 if (V.getOpcode() == ISD::BUILD_VECTOR)
4681 return V.getOperand(Index);
4686 /// Custom lower build_vector of v16i8.
4687 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4688 unsigned NumNonZero, unsigned NumZero,
4690 const X86Subtarget* Subtarget,
4691 const TargetLowering &TLI) {
4699 // SSE4.1 - use PINSRB to insert each byte directly.
4700 if (Subtarget->hasSSE41()) {
4701 for (unsigned i = 0; i < 16; ++i) {
4702 bool isNonZero = (NonZeros & (1 << i)) != 0;
4706 V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4708 V = DAG.getUNDEF(MVT::v16i8);
4711 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4712 MVT::v16i8, V, Op.getOperand(i),
4713 DAG.getIntPtrConstant(i, dl));
4720 // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4721 for (unsigned i = 0; i < 16; ++i) {
4722 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4723 if (ThisIsNonZero && First) {
4725 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4727 V = DAG.getUNDEF(MVT::v8i16);
4732 SDValue ThisElt, LastElt;
4733 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4734 if (LastIsNonZero) {
4735 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4736 MVT::i16, Op.getOperand(i-1));
4738 if (ThisIsNonZero) {
4739 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4740 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4741 ThisElt, DAG.getConstant(8, dl, MVT::i8));
4743 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4747 if (ThisElt.getNode())
4748 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4749 DAG.getIntPtrConstant(i/2, dl));
4753 return DAG.getBitcast(MVT::v16i8, V);
4756 /// Custom lower build_vector of v8i16.
4757 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4758 unsigned NumNonZero, unsigned NumZero,
4760 const X86Subtarget* Subtarget,
4761 const TargetLowering &TLI) {
4768 for (unsigned i = 0; i < 8; ++i) {
4769 bool isNonZero = (NonZeros & (1 << i)) != 0;
4773 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4775 V = DAG.getUNDEF(MVT::v8i16);
4778 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4779 MVT::v8i16, V, Op.getOperand(i),
4780 DAG.getIntPtrConstant(i, dl));
4787 /// Custom lower build_vector of v4i32 or v4f32.
4788 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4789 const X86Subtarget *Subtarget,
4790 const TargetLowering &TLI) {
4791 // Find all zeroable elements.
4792 std::bitset<4> Zeroable;
4793 for (int i=0; i < 4; ++i) {
4794 SDValue Elt = Op->getOperand(i);
4795 Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4797 assert(Zeroable.size() - Zeroable.count() > 1 &&
4798 "We expect at least two non-zero elements!");
4800 // We only know how to deal with build_vector nodes where elements are either
4801 // zeroable or extract_vector_elt with constant index.
4802 SDValue FirstNonZero;
4803 unsigned FirstNonZeroIdx;
4804 for (unsigned i=0; i < 4; ++i) {
4807 SDValue Elt = Op->getOperand(i);
4808 if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4809 !isa<ConstantSDNode>(Elt.getOperand(1)))
4811 // Make sure that this node is extracting from a 128-bit vector.
4812 MVT VT = Elt.getOperand(0).getSimpleValueType();
4813 if (!VT.is128BitVector())
4815 if (!FirstNonZero.getNode()) {
4817 FirstNonZeroIdx = i;
4821 assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4822 SDValue V1 = FirstNonZero.getOperand(0);
4823 MVT VT = V1.getSimpleValueType();
4825 // See if this build_vector can be lowered as a blend with zero.
4827 unsigned EltMaskIdx, EltIdx;
4829 for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4830 if (Zeroable[EltIdx]) {
4831 // The zero vector will be on the right hand side.
4832 Mask[EltIdx] = EltIdx+4;
4836 Elt = Op->getOperand(EltIdx);
4837 // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4838 EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4839 if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4841 Mask[EltIdx] = EltIdx;
4845 // Let the shuffle legalizer deal with blend operations.
4846 SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4847 if (V1.getSimpleValueType() != VT)
4848 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4849 return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4852 // See if we can lower this build_vector to a INSERTPS.
4853 if (!Subtarget->hasSSE41())
4856 SDValue V2 = Elt.getOperand(0);
4857 if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4860 bool CanFold = true;
4861 for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4865 SDValue Current = Op->getOperand(i);
4866 SDValue SrcVector = Current->getOperand(0);
4869 CanFold = SrcVector == V1 &&
4870 cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4876 assert(V1.getNode() && "Expected at least two non-zero elements!");
4877 if (V1.getSimpleValueType() != MVT::v4f32)
4878 V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4879 if (V2.getSimpleValueType() != MVT::v4f32)
4880 V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4882 // Ok, we can emit an INSERTPS instruction.
4883 unsigned ZMask = Zeroable.to_ulong();
4885 unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4886 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4888 SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
4889 DAG.getIntPtrConstant(InsertPSMask, DL));
4890 return DAG.getBitcast(VT, Result);
4893 /// Return a vector logical shift node.
4894 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4895 unsigned NumBits, SelectionDAG &DAG,
4896 const TargetLowering &TLI, SDLoc dl) {
4897 assert(VT.is128BitVector() && "Unknown type for VShift");
4898 MVT ShVT = MVT::v2i64;
4899 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4900 SrcOp = DAG.getBitcast(ShVT, SrcOp);
4901 MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
4902 assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4903 SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
4904 return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4908 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4910 // Check if the scalar load can be widened into a vector load. And if
4911 // the address is "base + cst" see if the cst can be "absorbed" into
4912 // the shuffle mask.
4913 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4914 SDValue Ptr = LD->getBasePtr();
4915 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4917 EVT PVT = LD->getValueType(0);
4918 if (PVT != MVT::i32 && PVT != MVT::f32)
4923 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4924 FI = FINode->getIndex();
4926 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4927 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4928 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4929 Offset = Ptr.getConstantOperandVal(1);
4930 Ptr = Ptr.getOperand(0);
4935 // FIXME: 256-bit vector instructions don't require a strict alignment,
4936 // improve this code to support it better.
4937 unsigned RequiredAlign = VT.getSizeInBits()/8;
4938 SDValue Chain = LD->getChain();
4939 // Make sure the stack object alignment is at least 16 or 32.
4940 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4941 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4942 if (MFI->isFixedObjectIndex(FI)) {
4943 // Can't change the alignment. FIXME: It's possible to compute
4944 // the exact stack offset and reference FI + adjust offset instead.
4945 // If someone *really* cares about this. That's the way to implement it.
4948 MFI->setObjectAlignment(FI, RequiredAlign);
4952 // (Offset % 16 or 32) must be multiple of 4. Then address is then
4953 // Ptr + (Offset & ~15).
4956 if ((Offset % RequiredAlign) & 3)
4958 int64_t StartOffset = Offset & ~(RequiredAlign-1);
4961 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4962 DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
4965 int EltNo = (Offset - StartOffset) >> 2;
4966 unsigned NumElems = VT.getVectorNumElements();
4968 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4969 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4970 LD->getPointerInfo().getWithOffset(StartOffset),
4971 false, false, false, 0);
4973 SmallVector<int, 8> Mask(NumElems, EltNo);
4975 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4981 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
4982 /// elements can be replaced by a single large load which has the same value as
4983 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
4985 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4987 /// FIXME: we'd also like to handle the case where the last elements are zero
4988 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4989 /// There's even a handy isZeroNode for that purpose.
4990 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
4991 SDLoc &DL, SelectionDAG &DAG,
4992 bool isAfterLegalize) {
4993 unsigned NumElems = Elts.size();
4995 LoadSDNode *LDBase = nullptr;
4996 unsigned LastLoadedElt = -1U;
4998 // For each element in the initializer, see if we've found a load or an undef.
4999 // If we don't find an initial load element, or later load elements are
5000 // non-consecutive, bail out.
5001 for (unsigned i = 0; i < NumElems; ++i) {
5002 SDValue Elt = Elts[i];
5003 // Look through a bitcast.
5004 if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
5005 Elt = Elt.getOperand(0);
5006 if (!Elt.getNode() ||
5007 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5010 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5012 LDBase = cast<LoadSDNode>(Elt.getNode());
5016 if (Elt.getOpcode() == ISD::UNDEF)
5019 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5020 EVT LdVT = Elt.getValueType();
5021 // Each loaded element must be the correct fractional portion of the
5022 // requested vector load.
5023 if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
5025 if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
5030 // If we have found an entire vector of loads and undefs, then return a large
5031 // load of the entire vector width starting at the base pointer. If we found
5032 // consecutive loads for the low half, generate a vzext_load node.
5033 if (LastLoadedElt == NumElems - 1) {
5034 assert(LDBase && "Did not find base load for merging consecutive loads");
5035 EVT EltVT = LDBase->getValueType(0);
5036 // Ensure that the input vector size for the merged loads matches the
5037 // cumulative size of the input elements.
5038 if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5041 if (isAfterLegalize &&
5042 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5045 SDValue NewLd = SDValue();
5047 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5048 LDBase->getPointerInfo(), LDBase->isVolatile(),
5049 LDBase->isNonTemporal(), LDBase->isInvariant(),
5050 LDBase->getAlignment());
5052 if (LDBase->hasAnyUseOfValue(1)) {
5053 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5055 SDValue(NewLd.getNode(), 1));
5056 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5057 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5058 SDValue(NewLd.getNode(), 1));
5064 //TODO: The code below fires only for for loading the low v2i32 / v2f32
5065 //of a v4i32 / v4f32. It's probably worth generalizing.
5066 EVT EltVT = VT.getVectorElementType();
5067 if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5068 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5069 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5070 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5072 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5073 LDBase->getPointerInfo(),
5074 LDBase->getAlignment(),
5075 false/*isVolatile*/, true/*ReadMem*/,
5078 // Make sure the newly-created LOAD is in the same position as LDBase in
5079 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5080 // update uses of LDBase's output chain to use the TokenFactor.
5081 if (LDBase->hasAnyUseOfValue(1)) {
5082 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5083 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5084 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5085 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5086 SDValue(ResNode.getNode(), 1));
5089 return DAG.getBitcast(VT, ResNode);
5094 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5095 /// to generate a splat value for the following cases:
5096 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5097 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5098 /// a scalar load, or a constant.
5099 /// The VBROADCAST node is returned when a pattern is found,
5100 /// or SDValue() otherwise.
5101 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5102 SelectionDAG &DAG) {
5103 // VBROADCAST requires AVX.
5104 // TODO: Splats could be generated for non-AVX CPUs using SSE
5105 // instructions, but there's less potential gain for only 128-bit vectors.
5106 if (!Subtarget->hasAVX())
5109 MVT VT = Op.getSimpleValueType();
5112 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5113 "Unsupported vector type for broadcast.");
5118 switch (Op.getOpcode()) {
5120 // Unknown pattern found.
5123 case ISD::BUILD_VECTOR: {
5124 auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5125 BitVector UndefElements;
5126 SDValue Splat = BVOp->getSplatValue(&UndefElements);
5128 // We need a splat of a single value to use broadcast, and it doesn't
5129 // make any sense if the value is only in one element of the vector.
5130 if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5134 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5135 Ld.getOpcode() == ISD::ConstantFP);
5137 // Make sure that all of the users of a non-constant load are from the
5138 // BUILD_VECTOR node.
5139 if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5144 case ISD::VECTOR_SHUFFLE: {
5145 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5147 // Shuffles must have a splat mask where the first element is
5149 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5152 SDValue Sc = Op.getOperand(0);
5153 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5154 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5156 if (!Subtarget->hasInt256())
5159 // Use the register form of the broadcast instruction available on AVX2.
5160 if (VT.getSizeInBits() >= 256)
5161 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5162 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5165 Ld = Sc.getOperand(0);
5166 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5167 Ld.getOpcode() == ISD::ConstantFP);
5169 // The scalar_to_vector node and the suspected
5170 // load node must have exactly one user.
5171 // Constants may have multiple users.
5173 // AVX-512 has register version of the broadcast
5174 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5175 Ld.getValueType().getSizeInBits() >= 32;
5176 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5183 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5184 bool IsGE256 = (VT.getSizeInBits() >= 256);
5186 // When optimizing for size, generate up to 5 extra bytes for a broadcast
5187 // instruction to save 8 or more bytes of constant pool data.
5188 // TODO: If multiple splats are generated to load the same constant,
5189 // it may be detrimental to overall size. There needs to be a way to detect
5190 // that condition to know if this is truly a size win.
5191 const Function *F = DAG.getMachineFunction().getFunction();
5192 // FIXME: Use Function::optForSize().
5193 bool OptForSize = F->hasFnAttribute(Attribute::OptimizeForSize);
5195 // Handle broadcasting a single constant scalar from the constant pool
5197 // On Sandybridge (no AVX2), it is still better to load a constant vector
5198 // from the constant pool and not to broadcast it from a scalar.
5199 // But override that restriction when optimizing for size.
5200 // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5201 if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5202 EVT CVT = Ld.getValueType();
5203 assert(!CVT.isVector() && "Must not broadcast a vector type");
5205 // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5206 // For size optimization, also splat v2f64 and v2i64, and for size opt
5207 // with AVX2, also splat i8 and i16.
5208 // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5209 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5210 (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5211 const Constant *C = nullptr;
5212 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5213 C = CI->getConstantIntValue();
5214 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5215 C = CF->getConstantFPValue();
5217 assert(C && "Invalid constant type");
5219 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5221 DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5222 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5223 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5224 MachinePointerInfo::getConstantPool(),
5225 false, false, false, Alignment);
5227 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5231 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5233 // Handle AVX2 in-register broadcasts.
5234 if (!IsLoad && Subtarget->hasInt256() &&
5235 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5236 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5238 // The scalar source must be a normal load.
5242 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5243 (Subtarget->hasVLX() && ScalarSize == 64))
5244 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5246 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5247 // double since there is no vbroadcastsd xmm
5248 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5249 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5250 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5253 // Unsupported broadcast.
5257 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5258 /// underlying vector and index.
5260 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5262 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5264 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5265 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5268 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5270 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5272 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5273 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5276 // In this case the vector is the extract_subvector expression and the index
5277 // is 2, as specified by the shuffle.
5278 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5279 SDValue ShuffleVec = SVOp->getOperand(0);
5280 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5281 assert(ShuffleVecVT.getVectorElementType() ==
5282 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5284 int ShuffleIdx = SVOp->getMaskElt(Idx);
5285 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5286 ExtractedFromVec = ShuffleVec;
5292 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5293 MVT VT = Op.getSimpleValueType();
5295 // Skip if insert_vec_elt is not supported.
5296 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5297 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5301 unsigned NumElems = Op.getNumOperands();
5305 SmallVector<unsigned, 4> InsertIndices;
5306 SmallVector<int, 8> Mask(NumElems, -1);
5308 for (unsigned i = 0; i != NumElems; ++i) {
5309 unsigned Opc = Op.getOperand(i).getOpcode();
5311 if (Opc == ISD::UNDEF)
5314 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5315 // Quit if more than 1 elements need inserting.
5316 if (InsertIndices.size() > 1)
5319 InsertIndices.push_back(i);
5323 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5324 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5325 // Quit if non-constant index.
5326 if (!isa<ConstantSDNode>(ExtIdx))
5328 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5330 // Quit if extracted from vector of different type.
5331 if (ExtractedFromVec.getValueType() != VT)
5334 if (!VecIn1.getNode())
5335 VecIn1 = ExtractedFromVec;
5336 else if (VecIn1 != ExtractedFromVec) {
5337 if (!VecIn2.getNode())
5338 VecIn2 = ExtractedFromVec;
5339 else if (VecIn2 != ExtractedFromVec)
5340 // Quit if more than 2 vectors to shuffle
5344 if (ExtractedFromVec == VecIn1)
5346 else if (ExtractedFromVec == VecIn2)
5347 Mask[i] = Idx + NumElems;
5350 if (!VecIn1.getNode())
5353 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5354 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5355 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5356 unsigned Idx = InsertIndices[i];
5357 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5358 DAG.getIntPtrConstant(Idx, DL));
5364 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
5365 assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5366 Op.getScalarValueSizeInBits() == 1 &&
5367 "Can not convert non-constant vector");
5368 uint64_t Immediate = 0;
5369 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5370 SDValue In = Op.getOperand(idx);
5371 if (In.getOpcode() != ISD::UNDEF)
5372 Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5376 MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5377 return DAG.getConstant(Immediate, dl, VT);
5379 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5381 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5383 MVT VT = Op.getSimpleValueType();
5384 assert((VT.getVectorElementType() == MVT::i1) &&
5385 "Unexpected type in LowerBUILD_VECTORvXi1!");
5388 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5389 SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5390 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5391 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5394 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5395 SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5396 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5397 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5400 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5401 SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
5402 if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5403 return DAG.getBitcast(VT, Imm);
5404 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5405 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5406 DAG.getIntPtrConstant(0, dl));
5409 // Vector has one or more non-const elements
5410 uint64_t Immediate = 0;
5411 SmallVector<unsigned, 16> NonConstIdx;
5412 bool IsSplat = true;
5413 bool HasConstElts = false;
5415 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5416 SDValue In = Op.getOperand(idx);
5417 if (In.getOpcode() == ISD::UNDEF)
5419 if (!isa<ConstantSDNode>(In))
5420 NonConstIdx.push_back(idx);
5422 Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5423 HasConstElts = true;
5427 else if (In != Op.getOperand(SplatIdx))
5431 // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5433 return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5434 DAG.getConstant(1, dl, VT),
5435 DAG.getConstant(0, dl, VT));
5437 // insert elements one by one
5441 MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5442 Imm = DAG.getConstant(Immediate, dl, ImmVT);
5444 else if (HasConstElts)
5445 Imm = DAG.getConstant(0, dl, VT);
5447 Imm = DAG.getUNDEF(VT);
5448 if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5449 DstVec = DAG.getBitcast(VT, Imm);
5451 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5452 DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5453 DAG.getIntPtrConstant(0, dl));
5456 for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5457 unsigned InsertIdx = NonConstIdx[i];
5458 DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5459 Op.getOperand(InsertIdx),
5460 DAG.getIntPtrConstant(InsertIdx, dl));
5465 /// \brief Return true if \p N implements a horizontal binop and return the
5466 /// operands for the horizontal binop into V0 and V1.
5468 /// This is a helper function of LowerToHorizontalOp().
5469 /// This function checks that the build_vector \p N in input implements a
5470 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5471 /// operation to match.
5472 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5473 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5474 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5477 /// This function only analyzes elements of \p N whose indices are
5478 /// in range [BaseIdx, LastIdx).
5479 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5481 unsigned BaseIdx, unsigned LastIdx,
5482 SDValue &V0, SDValue &V1) {
5483 EVT VT = N->getValueType(0);
5485 assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5486 assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5487 "Invalid Vector in input!");
5489 bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5490 bool CanFold = true;
5491 unsigned ExpectedVExtractIdx = BaseIdx;
5492 unsigned NumElts = LastIdx - BaseIdx;
5493 V0 = DAG.getUNDEF(VT);
5494 V1 = DAG.getUNDEF(VT);
5496 // Check if N implements a horizontal binop.
5497 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5498 SDValue Op = N->getOperand(i + BaseIdx);
5501 if (Op->getOpcode() == ISD::UNDEF) {
5502 // Update the expected vector extract index.
5503 if (i * 2 == NumElts)
5504 ExpectedVExtractIdx = BaseIdx;
5505 ExpectedVExtractIdx += 2;
5509 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5514 SDValue Op0 = Op.getOperand(0);
5515 SDValue Op1 = Op.getOperand(1);
5517 // Try to match the following pattern:
5518 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5519 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5520 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5521 Op0.getOperand(0) == Op1.getOperand(0) &&
5522 isa<ConstantSDNode>(Op0.getOperand(1)) &&
5523 isa<ConstantSDNode>(Op1.getOperand(1)));
5527 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5528 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5530 if (i * 2 < NumElts) {
5531 if (V0.getOpcode() == ISD::UNDEF) {
5532 V0 = Op0.getOperand(0);
5533 if (V0.getValueType() != VT)
5537 if (V1.getOpcode() == ISD::UNDEF) {
5538 V1 = Op0.getOperand(0);
5539 if (V1.getValueType() != VT)
5542 if (i * 2 == NumElts)
5543 ExpectedVExtractIdx = BaseIdx;
5546 SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5547 if (I0 == ExpectedVExtractIdx)
5548 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5549 else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5550 // Try to match the following dag sequence:
5551 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5552 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5556 ExpectedVExtractIdx += 2;
5562 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5563 /// a concat_vector.
5565 /// This is a helper function of LowerToHorizontalOp().
5566 /// This function expects two 256-bit vectors called V0 and V1.
5567 /// At first, each vector is split into two separate 128-bit vectors.
5568 /// Then, the resulting 128-bit vectors are used to implement two
5569 /// horizontal binary operations.
5571 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5573 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5574 /// the two new horizontal binop.
5575 /// When Mode is set, the first horizontal binop dag node would take as input
5576 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5577 /// horizontal binop dag node would take as input the lower 128-bit of V1
5578 /// and the upper 128-bit of V1.
5580 /// HADD V0_LO, V0_HI
5581 /// HADD V1_LO, V1_HI
5583 /// Otherwise, the first horizontal binop dag node takes as input the lower
5584 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5585 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5587 /// HADD V0_LO, V1_LO
5588 /// HADD V0_HI, V1_HI
5590 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5591 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5592 /// the upper 128-bits of the result.
5593 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5594 SDLoc DL, SelectionDAG &DAG,
5595 unsigned X86Opcode, bool Mode,
5596 bool isUndefLO, bool isUndefHI) {
5597 EVT VT = V0.getValueType();
5598 assert(VT.is256BitVector() && VT == V1.getValueType() &&
5599 "Invalid nodes in input!");
5601 unsigned NumElts = VT.getVectorNumElements();
5602 SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5603 SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5604 SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5605 SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5606 EVT NewVT = V0_LO.getValueType();
5608 SDValue LO = DAG.getUNDEF(NewVT);
5609 SDValue HI = DAG.getUNDEF(NewVT);
5612 // Don't emit a horizontal binop if the result is expected to be UNDEF.
5613 if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5614 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5615 if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5616 HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5618 // Don't emit a horizontal binop if the result is expected to be UNDEF.
5619 if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5620 V1_LO->getOpcode() != ISD::UNDEF))
5621 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5623 if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5624 V1_HI->getOpcode() != ISD::UNDEF))
5625 HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5628 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5631 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5633 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5634 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5635 EVT VT = BV->getValueType(0);
5636 if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5637 (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5641 unsigned NumElts = VT.getVectorNumElements();
5642 SDValue InVec0 = DAG.getUNDEF(VT);
5643 SDValue InVec1 = DAG.getUNDEF(VT);
5645 assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5646 VT == MVT::v2f64) && "build_vector with an invalid type found!");
5648 // Odd-numbered elements in the input build vector are obtained from
5649 // adding two integer/float elements.
5650 // Even-numbered elements in the input build vector are obtained from
5651 // subtracting two integer/float elements.
5652 unsigned ExpectedOpcode = ISD::FSUB;
5653 unsigned NextExpectedOpcode = ISD::FADD;
5654 bool AddFound = false;
5655 bool SubFound = false;
5657 for (unsigned i = 0, e = NumElts; i != e; ++i) {
5658 SDValue Op = BV->getOperand(i);
5660 // Skip 'undef' values.
5661 unsigned Opcode = Op.getOpcode();
5662 if (Opcode == ISD::UNDEF) {
5663 std::swap(ExpectedOpcode, NextExpectedOpcode);
5667 // Early exit if we found an unexpected opcode.
5668 if (Opcode != ExpectedOpcode)
5671 SDValue Op0 = Op.getOperand(0);
5672 SDValue Op1 = Op.getOperand(1);
5674 // Try to match the following pattern:
5675 // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5676 // Early exit if we cannot match that sequence.
5677 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5678 Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5679 !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5680 !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5681 Op0.getOperand(1) != Op1.getOperand(1))
5684 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5688 // We found a valid add/sub node. Update the information accordingly.
5694 // Update InVec0 and InVec1.
5695 if (InVec0.getOpcode() == ISD::UNDEF) {
5696 InVec0 = Op0.getOperand(0);
5697 if (InVec0.getValueType() != VT)
5700 if (InVec1.getOpcode() == ISD::UNDEF) {
5701 InVec1 = Op1.getOperand(0);
5702 if (InVec1.getValueType() != VT)
5706 // Make sure that operands in input to each add/sub node always
5707 // come from a same pair of vectors.
5708 if (InVec0 != Op0.getOperand(0)) {
5709 if (ExpectedOpcode == ISD::FSUB)
5712 // FADD is commutable. Try to commute the operands
5713 // and then test again.
5714 std::swap(Op0, Op1);
5715 if (InVec0 != Op0.getOperand(0))
5719 if (InVec1 != Op1.getOperand(0))
5722 // Update the pair of expected opcodes.
5723 std::swap(ExpectedOpcode, NextExpectedOpcode);
5726 // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5727 if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5728 InVec1.getOpcode() != ISD::UNDEF)
5729 return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5734 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5735 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5736 const X86Subtarget *Subtarget,
5737 SelectionDAG &DAG) {
5738 EVT VT = BV->getValueType(0);
5739 unsigned NumElts = VT.getVectorNumElements();
5740 unsigned NumUndefsLO = 0;
5741 unsigned NumUndefsHI = 0;
5742 unsigned Half = NumElts/2;
5744 // Count the number of UNDEF operands in the build_vector in input.
5745 for (unsigned i = 0, e = Half; i != e; ++i)
5746 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5749 for (unsigned i = Half, e = NumElts; i != e; ++i)
5750 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5753 // Early exit if this is either a build_vector of all UNDEFs or all the
5754 // operands but one are UNDEF.
5755 if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5759 SDValue InVec0, InVec1;
5760 if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5761 // Try to match an SSE3 float HADD/HSUB.
5762 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5763 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5765 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5766 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5767 } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5768 // Try to match an SSSE3 integer HADD/HSUB.
5769 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5770 return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5772 if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5773 return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5776 if (!Subtarget->hasAVX())
5779 if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5780 // Try to match an AVX horizontal add/sub of packed single/double
5781 // precision floating point values from 256-bit vectors.
5782 SDValue InVec2, InVec3;
5783 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5784 isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5785 ((InVec0.getOpcode() == ISD::UNDEF ||
5786 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5787 ((InVec1.getOpcode() == ISD::UNDEF ||
5788 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5789 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5791 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5792 isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5793 ((InVec0.getOpcode() == ISD::UNDEF ||
5794 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5795 ((InVec1.getOpcode() == ISD::UNDEF ||
5796 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5797 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5798 } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5799 // Try to match an AVX2 horizontal add/sub of signed integers.
5800 SDValue InVec2, InVec3;
5802 bool CanFold = true;
5804 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5805 isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5806 ((InVec0.getOpcode() == ISD::UNDEF ||
5807 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5808 ((InVec1.getOpcode() == ISD::UNDEF ||
5809 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5810 X86Opcode = X86ISD::HADD;
5811 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5812 isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5813 ((InVec0.getOpcode() == ISD::UNDEF ||
5814 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5815 ((InVec1.getOpcode() == ISD::UNDEF ||
5816 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5817 X86Opcode = X86ISD::HSUB;
5822 // Fold this build_vector into a single horizontal add/sub.
5823 // Do this only if the target has AVX2.
5824 if (Subtarget->hasAVX2())
5825 return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5827 // Do not try to expand this build_vector into a pair of horizontal
5828 // add/sub if we can emit a pair of scalar add/sub.
5829 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5832 // Convert this build_vector into a pair of horizontal binop followed by
5834 bool isUndefLO = NumUndefsLO == Half;
5835 bool isUndefHI = NumUndefsHI == Half;
5836 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5837 isUndefLO, isUndefHI);
5841 if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5842 VT == MVT::v16i16) && Subtarget->hasAVX()) {
5844 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5845 X86Opcode = X86ISD::HADD;
5846 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5847 X86Opcode = X86ISD::HSUB;
5848 else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5849 X86Opcode = X86ISD::FHADD;
5850 else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5851 X86Opcode = X86ISD::FHSUB;
5855 // Don't try to expand this build_vector into a pair of horizontal add/sub
5856 // if we can simply emit a pair of scalar add/sub.
5857 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5860 // Convert this build_vector into two horizontal add/sub followed by
5862 bool isUndefLO = NumUndefsLO == Half;
5863 bool isUndefHI = NumUndefsHI == Half;
5864 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5865 isUndefLO, isUndefHI);
5872 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5875 MVT VT = Op.getSimpleValueType();
5876 MVT ExtVT = VT.getVectorElementType();
5877 unsigned NumElems = Op.getNumOperands();
5879 // Generate vectors for predicate vectors.
5880 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5881 return LowerBUILD_VECTORvXi1(Op, DAG);
5883 // Vectors containing all zeros can be matched by pxor and xorps later
5884 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5885 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5886 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5887 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5890 return getZeroVector(VT, Subtarget, DAG, dl);
5893 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5894 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5895 // vpcmpeqd on 256-bit vectors.
5896 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5897 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5900 if (!VT.is512BitVector())
5901 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5904 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
5905 if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
5907 if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
5908 return HorizontalOp;
5909 if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
5912 unsigned EVTBits = ExtVT.getSizeInBits();
5914 unsigned NumZero = 0;
5915 unsigned NumNonZero = 0;
5916 unsigned NonZeros = 0;
5917 bool IsAllConstants = true;
5918 SmallSet<SDValue, 8> Values;
5919 for (unsigned i = 0; i < NumElems; ++i) {
5920 SDValue Elt = Op.getOperand(i);
5921 if (Elt.getOpcode() == ISD::UNDEF)
5924 if (Elt.getOpcode() != ISD::Constant &&
5925 Elt.getOpcode() != ISD::ConstantFP)
5926 IsAllConstants = false;
5927 if (X86::isZeroNode(Elt))
5930 NonZeros |= (1 << i);
5935 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5936 if (NumNonZero == 0)
5937 return DAG.getUNDEF(VT);
5939 // Special case for single non-zero, non-undef, element.
5940 if (NumNonZero == 1) {
5941 unsigned Idx = countTrailingZeros(NonZeros);
5942 SDValue Item = Op.getOperand(Idx);
5944 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5945 // the value are obviously zero, truncate the value to i32 and do the
5946 // insertion that way. Only do this if the value is non-constant or if the
5947 // value is a constant being inserted into element 0. It is cheaper to do
5948 // a constant pool load than it is to do a movd + shuffle.
5949 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5950 (!IsAllConstants || Idx == 0)) {
5951 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5953 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5954 EVT VecVT = MVT::v4i32;
5956 // Truncate the value (which may itself be a constant) to i32, and
5957 // convert it to a vector with movd (S2V+shuffle to zero extend).
5958 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5959 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5960 return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
5961 Item, Idx * 2, true, Subtarget, DAG));
5965 // If we have a constant or non-constant insertion into the low element of
5966 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5967 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5968 // depending on what the source datatype is.
5971 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5973 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5974 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5975 if (VT.is512BitVector()) {
5976 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5977 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5978 Item, DAG.getIntPtrConstant(0, dl));
5980 assert((VT.is128BitVector() || VT.is256BitVector()) &&
5981 "Expected an SSE value type!");
5982 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5983 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5984 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5987 // We can't directly insert an i8 or i16 into a vector, so zero extend
5989 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5990 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5991 if (VT.is256BitVector()) {
5992 if (Subtarget->hasAVX()) {
5993 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
5994 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5996 // Without AVX, we need to extend to a 128-bit vector and then
5997 // insert into the 256-bit vector.
5998 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5999 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6000 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6003 assert(VT.is128BitVector() && "Expected an SSE value type!");
6004 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6005 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6007 return DAG.getBitcast(VT, Item);
6011 // Is it a vector logical left shift?
6012 if (NumElems == 2 && Idx == 1 &&
6013 X86::isZeroNode(Op.getOperand(0)) &&
6014 !X86::isZeroNode(Op.getOperand(1))) {
6015 unsigned NumBits = VT.getSizeInBits();
6016 return getVShift(true, VT,
6017 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6018 VT, Op.getOperand(1)),
6019 NumBits/2, DAG, *this, dl);
6022 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6025 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6026 // is a non-constant being inserted into an element other than the low one,
6027 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6028 // movd/movss) to move this into the low element, then shuffle it into
6030 if (EVTBits == 32) {
6031 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6032 return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6036 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6037 if (Values.size() == 1) {
6038 if (EVTBits == 32) {
6039 // Instead of a shuffle like this:
6040 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6041 // Check if it's possible to issue this instead.
6042 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6043 unsigned Idx = countTrailingZeros(NonZeros);
6044 SDValue Item = Op.getOperand(Idx);
6045 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6046 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6051 // A vector full of immediates; various special cases are already
6052 // handled, so this is best done with a single constant-pool load.
6056 // For AVX-length vectors, see if we can use a vector load to get all of the
6057 // elements, otherwise build the individual 128-bit pieces and use
6058 // shuffles to put them in place.
6059 if (VT.is256BitVector() || VT.is512BitVector()) {
6060 SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6062 // Check for a build vector of consecutive loads.
6063 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6066 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6068 // Build both the lower and upper subvector.
6069 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6070 makeArrayRef(&V[0], NumElems/2));
6071 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6072 makeArrayRef(&V[NumElems / 2], NumElems/2));
6074 // Recreate the wider vector with the lower and upper part.
6075 if (VT.is256BitVector())
6076 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6077 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6080 // Let legalizer expand 2-wide build_vectors.
6081 if (EVTBits == 64) {
6082 if (NumNonZero == 1) {
6083 // One half is zero or undef.
6084 unsigned Idx = countTrailingZeros(NonZeros);
6085 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6086 Op.getOperand(Idx));
6087 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6092 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6093 if (EVTBits == 8 && NumElems == 16)
6094 if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6098 if (EVTBits == 16 && NumElems == 8)
6099 if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6103 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6104 if (EVTBits == 32 && NumElems == 4)
6105 if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6108 // If element VT is == 32 bits, turn it into a number of shuffles.
6109 SmallVector<SDValue, 8> V(NumElems);
6110 if (NumElems == 4 && NumZero > 0) {
6111 for (unsigned i = 0; i < 4; ++i) {
6112 bool isZero = !(NonZeros & (1 << i));
6114 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6116 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6119 for (unsigned i = 0; i < 2; ++i) {
6120 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6123 V[i] = V[i*2]; // Must be a zero vector.
6126 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6129 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6132 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6137 bool Reverse1 = (NonZeros & 0x3) == 2;
6138 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6142 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6143 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6145 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6148 if (Values.size() > 1 && VT.is128BitVector()) {
6149 // Check for a build vector of consecutive loads.
6150 for (unsigned i = 0; i < NumElems; ++i)
6151 V[i] = Op.getOperand(i);
6153 // Check for elements which are consecutive loads.
6154 if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6157 // Check for a build vector from mostly shuffle plus few inserting.
6158 if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6161 // For SSE 4.1, use insertps to put the high elements into the low element.
6162 if (Subtarget->hasSSE41()) {
6164 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6165 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6167 Result = DAG.getUNDEF(VT);
6169 for (unsigned i = 1; i < NumElems; ++i) {
6170 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6171 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6172 Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6177 // Otherwise, expand into a number of unpckl*, start by extending each of
6178 // our (non-undef) elements to the full vector width with the element in the
6179 // bottom slot of the vector (which generates no code for SSE).
6180 for (unsigned i = 0; i < NumElems; ++i) {
6181 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6182 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6184 V[i] = DAG.getUNDEF(VT);
6187 // Next, we iteratively mix elements, e.g. for v4f32:
6188 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6189 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6190 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6191 unsigned EltStride = NumElems >> 1;
6192 while (EltStride != 0) {
6193 for (unsigned i = 0; i < EltStride; ++i) {
6194 // If V[i+EltStride] is undef and this is the first round of mixing,
6195 // then it is safe to just drop this shuffle: V[i] is already in the
6196 // right place, the one element (since it's the first round) being
6197 // inserted as undef can be dropped. This isn't safe for successive
6198 // rounds because they will permute elements within both vectors.
6199 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6200 EltStride == NumElems/2)
6203 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6212 // 256-bit AVX can use the vinsertf128 instruction
6213 // to create 256-bit vectors from two other 128-bit ones.
6214 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6216 MVT ResVT = Op.getSimpleValueType();
6218 assert((ResVT.is256BitVector() ||
6219 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6221 SDValue V1 = Op.getOperand(0);
6222 SDValue V2 = Op.getOperand(1);
6223 unsigned NumElems = ResVT.getVectorNumElements();
6224 if (ResVT.is256BitVector())
6225 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6227 if (Op.getNumOperands() == 4) {
6228 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6229 ResVT.getVectorNumElements()/2);
6230 SDValue V3 = Op.getOperand(2);
6231 SDValue V4 = Op.getOperand(3);
6232 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6233 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6235 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6238 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6239 const X86Subtarget *Subtarget,
6240 SelectionDAG & DAG) {
6242 MVT ResVT = Op.getSimpleValueType();
6243 unsigned NumOfOperands = Op.getNumOperands();
6245 assert(isPowerOf2_32(NumOfOperands) &&
6246 "Unexpected number of operands in CONCAT_VECTORS");
6248 if (NumOfOperands > 2) {
6249 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6250 ResVT.getVectorNumElements()/2);
6251 SmallVector<SDValue, 2> Ops;
6252 for (unsigned i = 0; i < NumOfOperands/2; i++)
6253 Ops.push_back(Op.getOperand(i));
6254 SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6256 for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6257 Ops.push_back(Op.getOperand(i));
6258 SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6259 return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6262 SDValue V1 = Op.getOperand(0);
6263 SDValue V2 = Op.getOperand(1);
6264 bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6265 bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6267 if (IsZeroV1 && IsZeroV2)
6268 return getZeroVector(ResVT, Subtarget, DAG, dl);
6270 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6271 SDValue Undef = DAG.getUNDEF(ResVT);
6272 unsigned NumElems = ResVT.getVectorNumElements();
6273 SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6275 V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6276 V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6280 V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6281 // Zero the upper bits of V1
6282 V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6283 V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6286 return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6289 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6290 const X86Subtarget *Subtarget,
6291 SelectionDAG &DAG) {
6292 MVT VT = Op.getSimpleValueType();
6293 if (VT.getVectorElementType() == MVT::i1)
6294 return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6296 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6297 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6298 Op.getNumOperands() == 4)));
6300 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6301 // from two other 128-bit ones.
6303 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6304 return LowerAVXCONCAT_VECTORS(Op, DAG);
6308 //===----------------------------------------------------------------------===//
6309 // Vector shuffle lowering
6311 // This is an experimental code path for lowering vector shuffles on x86. It is
6312 // designed to handle arbitrary vector shuffles and blends, gracefully
6313 // degrading performance as necessary. It works hard to recognize idiomatic
6314 // shuffles and lower them to optimal instruction patterns without leaving
6315 // a framework that allows reasonably efficient handling of all vector shuffle
6317 //===----------------------------------------------------------------------===//
6319 /// \brief Tiny helper function to identify a no-op mask.
6321 /// This is a somewhat boring predicate function. It checks whether the mask
6322 /// array input, which is assumed to be a single-input shuffle mask of the kind
6323 /// used by the X86 shuffle instructions (not a fully general
6324 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6325 /// in-place shuffle are 'no-op's.
6326 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6327 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6328 if (Mask[i] != -1 && Mask[i] != i)
6333 /// \brief Helper function to classify a mask as a single-input mask.
6335 /// This isn't a generic single-input test because in the vector shuffle
6336 /// lowering we canonicalize single inputs to be the first input operand. This
6337 /// means we can more quickly test for a single input by only checking whether
6338 /// an input from the second operand exists. We also assume that the size of
6339 /// mask corresponds to the size of the input vectors which isn't true in the
6340 /// fully general case.
6341 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6343 if (M >= (int)Mask.size())
6348 /// \brief Test whether there are elements crossing 128-bit lanes in this
6351 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6352 /// and we routinely test for these.
6353 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6354 int LaneSize = 128 / VT.getScalarSizeInBits();
6355 int Size = Mask.size();
6356 for (int i = 0; i < Size; ++i)
6357 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6362 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6364 /// This checks a shuffle mask to see if it is performing the same
6365 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6366 /// that it is also not lane-crossing. It may however involve a blend from the
6367 /// same lane of a second vector.
6369 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6370 /// non-trivial to compute in the face of undef lanes. The representation is
6371 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6372 /// entries from both V1 and V2 inputs to the wider mask.
6374 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6375 SmallVectorImpl<int> &RepeatedMask) {
6376 int LaneSize = 128 / VT.getScalarSizeInBits();
6377 RepeatedMask.resize(LaneSize, -1);
6378 int Size = Mask.size();
6379 for (int i = 0; i < Size; ++i) {
6382 if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6383 // This entry crosses lanes, so there is no way to model this shuffle.
6386 // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6387 if (RepeatedMask[i % LaneSize] == -1)
6388 // This is the first non-undef entry in this slot of a 128-bit lane.
6389 RepeatedMask[i % LaneSize] =
6390 Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6391 else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6392 // Found a mismatch with the repeated mask.
6398 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6401 /// This is a fast way to test a shuffle mask against a fixed pattern:
6403 /// if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6405 /// It returns true if the mask is exactly as wide as the argument list, and
6406 /// each element of the mask is either -1 (signifying undef) or the value given
6407 /// in the argument.
6408 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6409 ArrayRef<int> ExpectedMask) {
6410 if (Mask.size() != ExpectedMask.size())
6413 int Size = Mask.size();
6415 // If the values are build vectors, we can look through them to find
6416 // equivalent inputs that make the shuffles equivalent.
6417 auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6418 auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6420 for (int i = 0; i < Size; ++i)
6421 if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6422 auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6423 auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6424 if (!MaskBV || !ExpectedBV ||
6425 MaskBV->getOperand(Mask[i] % Size) !=
6426 ExpectedBV->getOperand(ExpectedMask[i] % Size))
6433 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6435 /// This helper function produces an 8-bit shuffle immediate corresponding to
6436 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6437 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6440 /// NB: We rely heavily on "undef" masks preserving the input lane.
6441 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6442 SelectionDAG &DAG) {
6443 assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6444 assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6445 assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6446 assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6447 assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6450 Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6451 Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6452 Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6453 Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6454 return DAG.getConstant(Imm, DL, MVT::i8);
6457 /// \brief Compute whether each element of a shuffle is zeroable.
6459 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6460 /// Either it is an undef element in the shuffle mask, the element of the input
6461 /// referenced is undef, or the element of the input referenced is known to be
6462 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6463 /// as many lanes with this technique as possible to simplify the remaining
6465 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6466 SDValue V1, SDValue V2) {
6467 SmallBitVector Zeroable(Mask.size(), false);
6469 while (V1.getOpcode() == ISD::BITCAST)
6470 V1 = V1->getOperand(0);
6471 while (V2.getOpcode() == ISD::BITCAST)
6472 V2 = V2->getOperand(0);
6474 bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6475 bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6477 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6479 // Handle the easy cases.
6480 if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6485 // If this is an index into a build_vector node (which has the same number
6486 // of elements), dig out the input value and use it.
6487 SDValue V = M < Size ? V1 : V2;
6488 if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6491 SDValue Input = V.getOperand(M % Size);
6492 // The UNDEF opcode check really should be dead code here, but not quite
6493 // worth asserting on (it isn't invalid, just unexpected).
6494 if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6501 /// \brief Try to emit a bitmask instruction for a shuffle.
6503 /// This handles cases where we can model a blend exactly as a bitmask due to
6504 /// one of the inputs being zeroable.
6505 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6506 SDValue V2, ArrayRef<int> Mask,
6507 SelectionDAG &DAG) {
6508 MVT EltVT = VT.getScalarType();
6509 int NumEltBits = EltVT.getSizeInBits();
6510 MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6511 SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6512 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6514 if (EltVT.isFloatingPoint()) {
6515 Zero = DAG.getBitcast(EltVT, Zero);
6516 AllOnes = DAG.getBitcast(EltVT, AllOnes);
6518 SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6519 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6521 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6524 if (Mask[i] % Size != i)
6525 return SDValue(); // Not a blend.
6527 V = Mask[i] < Size ? V1 : V2;
6528 else if (V != (Mask[i] < Size ? V1 : V2))
6529 return SDValue(); // Can only let one input through the mask.
6531 VMaskOps[i] = AllOnes;
6534 return SDValue(); // No non-zeroable elements!
6536 SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6537 V = DAG.getNode(VT.isFloatingPoint()
6538 ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6543 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6545 /// This is used as a fallback approach when first class blend instructions are
6546 /// unavailable. Currently it is only suitable for integer vectors, but could
6547 /// be generalized for floating point vectors if desirable.
6548 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6549 SDValue V2, ArrayRef<int> Mask,
6550 SelectionDAG &DAG) {
6551 assert(VT.isInteger() && "Only supports integer vector types!");
6552 MVT EltVT = VT.getScalarType();
6553 int NumEltBits = EltVT.getSizeInBits();
6554 SDValue Zero = DAG.getConstant(0, DL, EltVT);
6555 SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6557 SmallVector<SDValue, 16> MaskOps;
6558 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6559 if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6560 return SDValue(); // Shuffled input!
6561 MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6564 SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6565 V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6566 // We have to cast V2 around.
6567 MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6568 V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6569 DAG.getBitcast(MaskVT, V1Mask),
6570 DAG.getBitcast(MaskVT, V2)));
6571 return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6574 /// \brief Try to emit a blend instruction for a shuffle.
6576 /// This doesn't do any checks for the availability of instructions for blending
6577 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6578 /// be matched in the backend with the type given. What it does check for is
6579 /// that the shuffle mask is in fact a blend.
6580 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6581 SDValue V2, ArrayRef<int> Mask,
6582 const X86Subtarget *Subtarget,
6583 SelectionDAG &DAG) {
6584 unsigned BlendMask = 0;
6585 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6586 if (Mask[i] >= Size) {
6587 if (Mask[i] != i + Size)
6588 return SDValue(); // Shuffled V2 input!
6589 BlendMask |= 1u << i;
6592 if (Mask[i] >= 0 && Mask[i] != i)
6593 return SDValue(); // Shuffled V1 input!
6595 switch (VT.SimpleTy) {
6600 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6601 DAG.getConstant(BlendMask, DL, MVT::i8));
6605 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6609 // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6610 // that instruction.
6611 if (Subtarget->hasAVX2()) {
6612 // Scale the blend by the number of 32-bit dwords per element.
6613 int Scale = VT.getScalarSizeInBits() / 32;
6615 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6616 if (Mask[i] >= Size)
6617 for (int j = 0; j < Scale; ++j)
6618 BlendMask |= 1u << (i * Scale + j);
6620 MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6621 V1 = DAG.getBitcast(BlendVT, V1);
6622 V2 = DAG.getBitcast(BlendVT, V2);
6623 return DAG.getBitcast(
6624 VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6625 DAG.getConstant(BlendMask, DL, MVT::i8)));
6629 // For integer shuffles we need to expand the mask and cast the inputs to
6630 // v8i16s prior to blending.
6631 int Scale = 8 / VT.getVectorNumElements();
6633 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6634 if (Mask[i] >= Size)
6635 for (int j = 0; j < Scale; ++j)
6636 BlendMask |= 1u << (i * Scale + j);
6638 V1 = DAG.getBitcast(MVT::v8i16, V1);
6639 V2 = DAG.getBitcast(MVT::v8i16, V2);
6640 return DAG.getBitcast(VT,
6641 DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6642 DAG.getConstant(BlendMask, DL, MVT::i8)));
6646 assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6647 SmallVector<int, 8> RepeatedMask;
6648 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6649 // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6650 assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6652 for (int i = 0; i < 8; ++i)
6653 if (RepeatedMask[i] >= 16)
6654 BlendMask |= 1u << i;
6655 return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6656 DAG.getConstant(BlendMask, DL, MVT::i8));
6662 assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6663 "256-bit byte-blends require AVX2 support!");
6665 // Attempt to lower to a bitmask if we can. VPAND is faster than VPBLENDVB.
6666 if (SDValue Masked = lowerVectorShuffleAsBitMask(DL, VT, V1, V2, Mask, DAG))
6669 // Scale the blend by the number of bytes per element.
6670 int Scale = VT.getScalarSizeInBits() / 8;
6672 // This form of blend is always done on bytes. Compute the byte vector
6674 MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6676 // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6677 // mix of LLVM's code generator and the x86 backend. We tell the code
6678 // generator that boolean values in the elements of an x86 vector register
6679 // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6680 // mapping a select to operand #1, and 'false' mapping to operand #2. The
6681 // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6682 // of the element (the remaining are ignored) and 0 in that high bit would
6683 // mean operand #1 while 1 in the high bit would mean operand #2. So while
6684 // the LLVM model for boolean values in vector elements gets the relevant
6685 // bit set, it is set backwards and over constrained relative to x86's
6687 SmallVector<SDValue, 32> VSELECTMask;
6688 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6689 for (int j = 0; j < Scale; ++j)
6690 VSELECTMask.push_back(
6691 Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6692 : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6695 V1 = DAG.getBitcast(BlendVT, V1);
6696 V2 = DAG.getBitcast(BlendVT, V2);
6697 return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
6698 DAG.getNode(ISD::BUILD_VECTOR, DL,
6699 BlendVT, VSELECTMask),
6704 llvm_unreachable("Not a supported integer vector type!");
6708 /// \brief Try to lower as a blend of elements from two inputs followed by
6709 /// a single-input permutation.
6711 /// This matches the pattern where we can blend elements from two inputs and
6712 /// then reduce the shuffle to a single-input permutation.
6713 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6716 SelectionDAG &DAG) {
6717 // We build up the blend mask while checking whether a blend is a viable way
6718 // to reduce the shuffle.
6719 SmallVector<int, 32> BlendMask(Mask.size(), -1);
6720 SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6722 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6726 assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6728 if (BlendMask[Mask[i] % Size] == -1)
6729 BlendMask[Mask[i] % Size] = Mask[i];
6730 else if (BlendMask[Mask[i] % Size] != Mask[i])
6731 return SDValue(); // Can't blend in the needed input!
6733 PermuteMask[i] = Mask[i] % Size;
6736 SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6737 return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6740 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6741 /// blends and permutes.
6743 /// This matches the extremely common pattern for handling combined
6744 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6745 /// operations. It will try to pick the best arrangement of shuffles and
6747 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6751 SelectionDAG &DAG) {
6752 // Shuffle the input elements into the desired positions in V1 and V2 and
6753 // blend them together.
6754 SmallVector<int, 32> V1Mask(Mask.size(), -1);
6755 SmallVector<int, 32> V2Mask(Mask.size(), -1);
6756 SmallVector<int, 32> BlendMask(Mask.size(), -1);
6757 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6758 if (Mask[i] >= 0 && Mask[i] < Size) {
6759 V1Mask[i] = Mask[i];
6761 } else if (Mask[i] >= Size) {
6762 V2Mask[i] = Mask[i] - Size;
6763 BlendMask[i] = i + Size;
6766 // Try to lower with the simpler initial blend strategy unless one of the
6767 // input shuffles would be a no-op. We prefer to shuffle inputs as the
6768 // shuffle may be able to fold with a load or other benefit. However, when
6769 // we'll have to do 2x as many shuffles in order to achieve this, blending
6770 // first is a better strategy.
6771 if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6772 if (SDValue BlendPerm =
6773 lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6776 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6777 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6778 return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6781 /// \brief Try to lower a vector shuffle as a byte rotation.
6783 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6784 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6785 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6786 /// try to generically lower a vector shuffle through such an pattern. It
6787 /// does not check for the profitability of lowering either as PALIGNR or
6788 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6789 /// This matches shuffle vectors that look like:
6791 /// v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6793 /// Essentially it concatenates V1 and V2, shifts right by some number of
6794 /// elements, and takes the low elements as the result. Note that while this is
6795 /// specified as a *right shift* because x86 is little-endian, it is a *left
6796 /// rotate* of the vector lanes.
6797 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6800 const X86Subtarget *Subtarget,
6801 SelectionDAG &DAG) {
6802 assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6804 int NumElts = Mask.size();
6805 int NumLanes = VT.getSizeInBits() / 128;
6806 int NumLaneElts = NumElts / NumLanes;
6808 // We need to detect various ways of spelling a rotation:
6809 // [11, 12, 13, 14, 15, 0, 1, 2]
6810 // [-1, 12, 13, 14, -1, -1, 1, -1]
6811 // [-1, -1, -1, -1, -1, -1, 1, 2]
6812 // [ 3, 4, 5, 6, 7, 8, 9, 10]
6813 // [-1, 4, 5, 6, -1, -1, 9, -1]
6814 // [-1, 4, 5, 6, -1, -1, -1, -1]
6817 for (int l = 0; l < NumElts; l += NumLaneElts) {
6818 for (int i = 0; i < NumLaneElts; ++i) {
6819 if (Mask[l + i] == -1)
6821 assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6823 // Get the mod-Size index and lane correct it.
6824 int LaneIdx = (Mask[l + i] % NumElts) - l;
6825 // Make sure it was in this lane.
6826 if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6829 // Determine where a rotated vector would have started.
6830 int StartIdx = i - LaneIdx;
6832 // The identity rotation isn't interesting, stop.
6835 // If we found the tail of a vector the rotation must be the missing
6836 // front. If we found the head of a vector, it must be how much of the
6838 int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6841 Rotation = CandidateRotation;
6842 else if (Rotation != CandidateRotation)
6843 // The rotations don't match, so we can't match this mask.
6846 // Compute which value this mask is pointing at.
6847 SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6849 // Compute which of the two target values this index should be assigned
6850 // to. This reflects whether the high elements are remaining or the low
6851 // elements are remaining.
6852 SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6854 // Either set up this value if we've not encountered it before, or check
6855 // that it remains consistent.
6858 else if (TargetV != MaskV)
6859 // This may be a rotation, but it pulls from the inputs in some
6860 // unsupported interleaving.
6865 // Check that we successfully analyzed the mask, and normalize the results.
6866 assert(Rotation != 0 && "Failed to locate a viable rotation!");
6867 assert((Lo || Hi) && "Failed to find a rotated input vector!");
6873 // The actual rotate instruction rotates bytes, so we need to scale the
6874 // rotation based on how many bytes are in the vector lane.
6875 int Scale = 16 / NumLaneElts;
6877 // SSSE3 targets can use the palignr instruction.
6878 if (Subtarget->hasSSSE3()) {
6879 // Cast the inputs to i8 vector of correct length to match PALIGNR.
6880 MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6881 Lo = DAG.getBitcast(AlignVT, Lo);
6882 Hi = DAG.getBitcast(AlignVT, Hi);
6884 return DAG.getBitcast(
6885 VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6886 DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
6889 assert(VT.getSizeInBits() == 128 &&
6890 "Rotate-based lowering only supports 128-bit lowering!");
6891 assert(Mask.size() <= 16 &&
6892 "Can shuffle at most 16 bytes in a 128-bit vector!");
6894 // Default SSE2 implementation
6895 int LoByteShift = 16 - Rotation * Scale;
6896 int HiByteShift = Rotation * Scale;
6898 // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6899 Lo = DAG.getBitcast(MVT::v2i64, Lo);
6900 Hi = DAG.getBitcast(MVT::v2i64, Hi);
6902 SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6903 DAG.getConstant(LoByteShift, DL, MVT::i8));
6904 SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6905 DAG.getConstant(HiByteShift, DL, MVT::i8));
6906 return DAG.getBitcast(VT,
6907 DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6910 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6912 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6913 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6914 /// matches elements from one of the input vectors shuffled to the left or
6915 /// right with zeroable elements 'shifted in'. It handles both the strictly
6916 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6919 /// PSHL : (little-endian) left bit shift.
6920 /// [ zz, 0, zz, 2 ]
6921 /// [ -1, 4, zz, -1 ]
6922 /// PSRL : (little-endian) right bit shift.
6924 /// [ -1, -1, 7, zz]
6925 /// PSLLDQ : (little-endian) left byte shift
6926 /// [ zz, 0, 1, 2, 3, 4, 5, 6]
6927 /// [ zz, zz, -1, -1, 2, 3, 4, -1]
6928 /// [ zz, zz, zz, zz, zz, zz, -1, 1]
6929 /// PSRLDQ : (little-endian) right byte shift
6930 /// [ 5, 6, 7, zz, zz, zz, zz, zz]
6931 /// [ -1, 5, 6, 7, zz, zz, zz, zz]
6932 /// [ 1, 2, -1, -1, -1, -1, zz, zz]
6933 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6934 SDValue V2, ArrayRef<int> Mask,
6935 SelectionDAG &DAG) {
6936 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6938 int Size = Mask.size();
6939 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6941 auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6942 for (int i = 0; i < Size; i += Scale)
6943 for (int j = 0; j < Shift; ++j)
6944 if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6950 auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6951 for (int i = 0; i != Size; i += Scale) {
6952 unsigned Pos = Left ? i + Shift : i;
6953 unsigned Low = Left ? i : i + Shift;
6954 unsigned Len = Scale - Shift;
6955 if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6956 Low + (V == V1 ? 0 : Size)))
6960 int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6961 bool ByteShift = ShiftEltBits > 64;
6962 unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6963 : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6964 int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6966 // Normalize the scale for byte shifts to still produce an i64 element
6968 Scale = ByteShift ? Scale / 2 : Scale;
6970 // We need to round trip through the appropriate type for the shift.
6971 MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6972 MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6973 assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6974 "Illegal integer vector type");
6975 V = DAG.getBitcast(ShiftVT, V);
6977 V = DAG.getNode(OpCode, DL, ShiftVT, V,
6978 DAG.getConstant(ShiftAmt, DL, MVT::i8));
6979 return DAG.getBitcast(VT, V);
6982 // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
6983 // keep doubling the size of the integer elements up to that. We can
6984 // then shift the elements of the integer vector by whole multiples of
6985 // their width within the elements of the larger integer vector. Test each
6986 // multiple to see if we can find a match with the moved element indices
6987 // and that the shifted in elements are all zeroable.
6988 for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
6989 for (int Shift = 1; Shift != Scale; ++Shift)
6990 for (bool Left : {true, false})
6991 if (CheckZeros(Shift, Scale, Left))
6992 for (SDValue V : {V1, V2})
6993 if (SDValue Match = MatchShift(Shift, Scale, Left, V))
7000 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
7001 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
7002 SDValue V2, ArrayRef<int> Mask,
7003 SelectionDAG &DAG) {
7004 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7005 assert(!Zeroable.all() && "Fully zeroable shuffle mask");
7007 int Size = Mask.size();
7008 int HalfSize = Size / 2;
7009 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7011 // Upper half must be undefined.
7012 if (!isUndefInRange(Mask, HalfSize, HalfSize))
7015 // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7016 // Remainder of lower half result is zero and upper half is all undef.
7017 auto LowerAsEXTRQ = [&]() {
7018 // Determine the extraction length from the part of the
7019 // lower half that isn't zeroable.
7021 for (; Len >= 0; --Len)
7022 if (!Zeroable[Len - 1])
7024 assert(Len > 0 && "Zeroable shuffle mask");
7026 // Attempt to match first Len sequential elements from the lower half.
7029 for (int i = 0; i != Len; ++i) {
7033 SDValue &V = (M < Size ? V1 : V2);
7036 // All mask elements must be in the lower half.
7040 if (Idx < 0 || (Src == V && Idx == (M - i))) {
7051 assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7052 int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7053 int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7054 return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7055 DAG.getConstant(BitLen, DL, MVT::i8),
7056 DAG.getConstant(BitIdx, DL, MVT::i8));
7059 if (SDValue ExtrQ = LowerAsEXTRQ())
7062 // INSERTQ: Extract lowest Len elements from lower half of second source and
7063 // insert over first source, starting at Idx.
7064 // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7065 auto LowerAsInsertQ = [&]() {
7066 for (int Idx = 0; Idx != HalfSize; ++Idx) {
7069 // Attempt to match first source from mask before insertion point.
7070 if (isUndefInRange(Mask, 0, Idx)) {
7072 } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7074 } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7080 // Extend the extraction length looking to match both the insertion of
7081 // the second source and the remaining elements of the first.
7082 for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7087 if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7089 } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7095 // Match the remaining elements of the lower half.
7096 if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7098 } else if ((!Base || (Base == V1)) &&
7099 isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7101 } else if ((!Base || (Base == V2)) &&
7102 isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7109 // We may not have a base (first source) - this can safely be undefined.
7111 Base = DAG.getUNDEF(VT);
7113 int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7114 int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7115 return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7116 DAG.getConstant(BitLen, DL, MVT::i8),
7117 DAG.getConstant(BitIdx, DL, MVT::i8));
7124 if (SDValue InsertQ = LowerAsInsertQ())
7130 /// \brief Lower a vector shuffle as a zero or any extension.
7132 /// Given a specific number of elements, element bit width, and extension
7133 /// stride, produce either a zero or any extension based on the available
7134 /// features of the subtarget.
7135 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7136 SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
7137 ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7138 assert(Scale > 1 && "Need a scale to extend.");
7139 int NumElements = VT.getVectorNumElements();
7140 int EltBits = VT.getScalarSizeInBits();
7141 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7142 "Only 8, 16, and 32 bit elements can be extended.");
7143 assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7145 // Found a valid zext mask! Try various lowering strategies based on the
7146 // input type and available ISA extensions.
7147 if (Subtarget->hasSSE41()) {
7148 MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7149 NumElements / Scale);
7150 return DAG.getBitcast(VT, DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
7153 // For any extends we can cheat for larger element sizes and use shuffle
7154 // instructions that can fold with a load and/or copy.
7155 if (AnyExt && EltBits == 32) {
7156 int PSHUFDMask[4] = {0, -1, 1, -1};
7157 return DAG.getBitcast(
7158 VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7159 DAG.getBitcast(MVT::v4i32, InputV),
7160 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7162 if (AnyExt && EltBits == 16 && Scale > 2) {
7163 int PSHUFDMask[4] = {0, -1, 0, -1};
7164 InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7165 DAG.getBitcast(MVT::v4i32, InputV),
7166 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7167 int PSHUFHWMask[4] = {1, -1, -1, -1};
7168 return DAG.getBitcast(
7169 VT, DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
7170 DAG.getBitcast(MVT::v8i16, InputV),
7171 getV4X86ShuffleImm8ForMask(PSHUFHWMask, DL, DAG)));
7174 // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7176 if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7177 assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7178 assert(VT.getSizeInBits() == 128 && "Unexpected vector width!");
7180 SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7181 DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7182 DAG.getConstant(EltBits, DL, MVT::i8),
7183 DAG.getConstant(0, DL, MVT::i8)));
7184 if (isUndefInRange(Mask, NumElements/2, NumElements/2))
7185 return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7188 DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7189 DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7190 DAG.getConstant(EltBits, DL, MVT::i8),
7191 DAG.getConstant(EltBits, DL, MVT::i8)));
7192 return DAG.getNode(ISD::BITCAST, DL, VT,
7193 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7196 // If this would require more than 2 unpack instructions to expand, use
7197 // pshufb when available. We can only use more than 2 unpack instructions
7198 // when zero extending i8 elements which also makes it easier to use pshufb.
7199 if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7200 assert(NumElements == 16 && "Unexpected byte vector width!");
7201 SDValue PSHUFBMask[16];
7202 for (int i = 0; i < 16; ++i)
7204 DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, DL, MVT::i8);
7205 InputV = DAG.getBitcast(MVT::v16i8, InputV);
7206 return DAG.getBitcast(VT,
7207 DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7208 DAG.getNode(ISD::BUILD_VECTOR, DL,
7209 MVT::v16i8, PSHUFBMask)));
7212 // Otherwise emit a sequence of unpacks.
7214 MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7215 SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7216 : getZeroVector(InputVT, Subtarget, DAG, DL);
7217 InputV = DAG.getBitcast(InputVT, InputV);
7218 InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
7222 } while (Scale > 1);
7223 return DAG.getBitcast(VT, InputV);
7226 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7228 /// This routine will try to do everything in its power to cleverly lower
7229 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7230 /// check for the profitability of this lowering, it tries to aggressively
7231 /// match this pattern. It will use all of the micro-architectural details it
7232 /// can to emit an efficient lowering. It handles both blends with all-zero
7233 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7234 /// masking out later).
7236 /// The reason we have dedicated lowering for zext-style shuffles is that they
7237 /// are both incredibly common and often quite performance sensitive.
7238 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7239 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7240 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7241 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7243 int Bits = VT.getSizeInBits();
7244 int NumElements = VT.getVectorNumElements();
7245 assert(VT.getScalarSizeInBits() <= 32 &&
7246 "Exceeds 32-bit integer zero extension limit");
7247 assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7249 // Define a helper function to check a particular ext-scale and lower to it if
7251 auto Lower = [&](int Scale) -> SDValue {
7254 for (int i = 0; i < NumElements; ++i) {
7256 continue; // Valid anywhere but doesn't tell us anything.
7257 if (i % Scale != 0) {
7258 // Each of the extended elements need to be zeroable.
7262 // We no longer are in the anyext case.
7267 // Each of the base elements needs to be consecutive indices into the
7268 // same input vector.
7269 SDValue V = Mask[i] < NumElements ? V1 : V2;
7272 else if (InputV != V)
7273 return SDValue(); // Flip-flopping inputs.
7275 if (Mask[i] % NumElements != i / Scale)
7276 return SDValue(); // Non-consecutive strided elements.
7279 // If we fail to find an input, we have a zero-shuffle which should always
7280 // have already been handled.
7281 // FIXME: Maybe handle this here in case during blending we end up with one?
7285 return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7286 DL, VT, Scale, AnyExt, InputV, Mask, Subtarget, DAG);
7289 // The widest scale possible for extending is to a 64-bit integer.
7290 assert(Bits % 64 == 0 &&
7291 "The number of bits in a vector must be divisible by 64 on x86!");
7292 int NumExtElements = Bits / 64;
7294 // Each iteration, try extending the elements half as much, but into twice as
7296 for (; NumExtElements < NumElements; NumExtElements *= 2) {
7297 assert(NumElements % NumExtElements == 0 &&
7298 "The input vector size must be divisible by the extended size.");
7299 if (SDValue V = Lower(NumElements / NumExtElements))
7303 // General extends failed, but 128-bit vectors may be able to use MOVQ.
7307 // Returns one of the source operands if the shuffle can be reduced to a
7308 // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7309 auto CanZExtLowHalf = [&]() {
7310 for (int i = NumElements / 2; i != NumElements; ++i)
7313 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7315 if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7320 if (SDValue V = CanZExtLowHalf()) {
7321 V = DAG.getBitcast(MVT::v2i64, V);
7322 V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7323 return DAG.getBitcast(VT, V);
7326 // No viable ext lowering found.
7330 /// \brief Try to get a scalar value for a specific element of a vector.
7332 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7333 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7334 SelectionDAG &DAG) {
7335 MVT VT = V.getSimpleValueType();
7336 MVT EltVT = VT.getVectorElementType();
7337 while (V.getOpcode() == ISD::BITCAST)
7338 V = V.getOperand(0);
7339 // If the bitcasts shift the element size, we can't extract an equivalent
7341 MVT NewVT = V.getSimpleValueType();
7342 if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7345 if (V.getOpcode() == ISD::BUILD_VECTOR ||
7346 (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7347 // Ensure the scalar operand is the same size as the destination.
7348 // FIXME: Add support for scalar truncation where possible.
7349 SDValue S = V.getOperand(Idx);
7350 if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7351 return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7357 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7359 /// This is particularly important because the set of instructions varies
7360 /// significantly based on whether the operand is a load or not.
7361 static bool isShuffleFoldableLoad(SDValue V) {
7362 while (V.getOpcode() == ISD::BITCAST)
7363 V = V.getOperand(0);
7365 return ISD::isNON_EXTLoad(V.getNode());
7368 /// \brief Try to lower insertion of a single element into a zero vector.
7370 /// This is a common pattern that we have especially efficient patterns to lower
7371 /// across all subtarget feature sets.
7372 static SDValue lowerVectorShuffleAsElementInsertion(
7373 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7374 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7375 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7377 MVT EltVT = VT.getVectorElementType();
7379 int V2Index = std::find_if(Mask.begin(), Mask.end(),
7380 [&Mask](int M) { return M >= (int)Mask.size(); }) -
7382 bool IsV1Zeroable = true;
7383 for (int i = 0, Size = Mask.size(); i < Size; ++i)
7384 if (i != V2Index && !Zeroable[i]) {
7385 IsV1Zeroable = false;
7389 // Check for a single input from a SCALAR_TO_VECTOR node.
7390 // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7391 // all the smarts here sunk into that routine. However, the current
7392 // lowering of BUILD_VECTOR makes that nearly impossible until the old
7393 // vector shuffle lowering is dead.
7394 SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
7396 if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
7397 // We need to zext the scalar if it is smaller than an i32.
7398 V2S = DAG.getBitcast(EltVT, V2S);
7399 if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7400 // Using zext to expand a narrow element won't work for non-zero
7405 // Zero-extend directly to i32.
7407 V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7409 V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7410 } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7411 EltVT == MVT::i16) {
7412 // Either not inserting from the low element of the input or the input
7413 // element size is too small to use VZEXT_MOVL to clear the high bits.
7417 if (!IsV1Zeroable) {
7418 // If V1 can't be treated as a zero vector we have fewer options to lower
7419 // this. We can't support integer vectors or non-zero targets cheaply, and
7420 // the V1 elements can't be permuted in any way.
7421 assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7422 if (!VT.isFloatingPoint() || V2Index != 0)
7424 SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7425 V1Mask[V2Index] = -1;
7426 if (!isNoopShuffleMask(V1Mask))
7428 // This is essentially a special case blend operation, but if we have
7429 // general purpose blend operations, they are always faster. Bail and let
7430 // the rest of the lowering handle these as blends.
7431 if (Subtarget->hasSSE41())
7434 // Otherwise, use MOVSD or MOVSS.
7435 assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7436 "Only two types of floating point element types to handle!");
7437 return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7441 // This lowering only works for the low element with floating point vectors.
7442 if (VT.isFloatingPoint() && V2Index != 0)
7445 V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7447 V2 = DAG.getBitcast(VT, V2);
7450 // If we have 4 or fewer lanes we can cheaply shuffle the element into
7451 // the desired position. Otherwise it is more efficient to do a vector
7452 // shift left. We know that we can do a vector shift left because all
7453 // the inputs are zero.
7454 if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7455 SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7456 V2Shuffle[V2Index] = 0;
7457 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7459 V2 = DAG.getBitcast(MVT::v2i64, V2);
7461 X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7462 DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
7463 DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
7464 DAG.getDataLayout(), VT)));
7465 V2 = DAG.getBitcast(VT, V2);
7471 /// \brief Try to lower broadcast of a single element.
7473 /// For convenience, this code also bundles all of the subtarget feature set
7474 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7475 /// a convenient way to factor it out.
7476 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7478 const X86Subtarget *Subtarget,
7479 SelectionDAG &DAG) {
7480 if (!Subtarget->hasAVX())
7482 if (VT.isInteger() && !Subtarget->hasAVX2())
7485 // Check that the mask is a broadcast.
7486 int BroadcastIdx = -1;
7488 if (M >= 0 && BroadcastIdx == -1)
7490 else if (M >= 0 && M != BroadcastIdx)
7493 assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7494 "a sorted mask where the broadcast "
7497 // Go up the chain of (vector) values to find a scalar load that we can
7498 // combine with the broadcast.
7500 switch (V.getOpcode()) {
7501 case ISD::CONCAT_VECTORS: {
7502 int OperandSize = Mask.size() / V.getNumOperands();
7503 V = V.getOperand(BroadcastIdx / OperandSize);
7504 BroadcastIdx %= OperandSize;
7508 case ISD::INSERT_SUBVECTOR: {
7509 SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7510 auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7514 int BeginIdx = (int)ConstantIdx->getZExtValue();
7516 BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7517 if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7518 BroadcastIdx -= BeginIdx;
7529 // Check if this is a broadcast of a scalar. We special case lowering
7530 // for scalars so that we can more effectively fold with loads.
7531 if (V.getOpcode() == ISD::BUILD_VECTOR ||
7532 (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7533 V = V.getOperand(BroadcastIdx);
7535 // If the scalar isn't a load, we can't broadcast from it in AVX1.
7536 // Only AVX2 has register broadcasts.
7537 if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7539 } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7540 // We can't broadcast from a vector register without AVX2, and we can only
7541 // broadcast from the zero-element of a vector register.
7545 return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7548 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7549 // INSERTPS when the V1 elements are already in the correct locations
7550 // because otherwise we can just always use two SHUFPS instructions which
7551 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7552 // perform INSERTPS if a single V1 element is out of place and all V2
7553 // elements are zeroable.
7554 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7556 SelectionDAG &DAG) {
7557 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7558 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7559 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7560 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7562 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7565 int V1DstIndex = -1;
7566 int V2DstIndex = -1;
7567 bool V1UsedInPlace = false;
7569 for (int i = 0; i < 4; ++i) {
7570 // Synthesize a zero mask from the zeroable elements (includes undefs).
7576 // Flag if we use any V1 inputs in place.
7578 V1UsedInPlace = true;
7582 // We can only insert a single non-zeroable element.
7583 if (V1DstIndex != -1 || V2DstIndex != -1)
7587 // V1 input out of place for insertion.
7590 // V2 input for insertion.
7595 // Don't bother if we have no (non-zeroable) element for insertion.
7596 if (V1DstIndex == -1 && V2DstIndex == -1)
7599 // Determine element insertion src/dst indices. The src index is from the
7600 // start of the inserted vector, not the start of the concatenated vector.
7601 unsigned V2SrcIndex = 0;
7602 if (V1DstIndex != -1) {
7603 // If we have a V1 input out of place, we use V1 as the V2 element insertion
7604 // and don't use the original V2 at all.
7605 V2SrcIndex = Mask[V1DstIndex];
7606 V2DstIndex = V1DstIndex;
7609 V2SrcIndex = Mask[V2DstIndex] - 4;
7612 // If no V1 inputs are used in place, then the result is created only from
7613 // the zero mask and the V2 insertion - so remove V1 dependency.
7615 V1 = DAG.getUNDEF(MVT::v4f32);
7617 unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7618 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7620 // Insert the V2 element into the desired position.
7622 return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7623 DAG.getConstant(InsertPSMask, DL, MVT::i8));
7626 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7627 /// UNPCK instruction.
7629 /// This specifically targets cases where we end up with alternating between
7630 /// the two inputs, and so can permute them into something that feeds a single
7631 /// UNPCK instruction. Note that this routine only targets integer vectors
7632 /// because for floating point vectors we have a generalized SHUFPS lowering
7633 /// strategy that handles everything that doesn't *exactly* match an unpack,
7634 /// making this clever lowering unnecessary.
7635 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7636 SDValue V2, ArrayRef<int> Mask,
7637 SelectionDAG &DAG) {
7638 assert(!VT.isFloatingPoint() &&
7639 "This routine only supports integer vectors.");
7640 assert(!isSingleInputShuffleMask(Mask) &&
7641 "This routine should only be used when blending two inputs.");
7642 assert(Mask.size() >= 2 && "Single element masks are invalid.");
7644 int Size = Mask.size();
7646 int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7647 return M >= 0 && M % Size < Size / 2;
7649 int NumHiInputs = std::count_if(
7650 Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7652 bool UnpackLo = NumLoInputs >= NumHiInputs;
7654 auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7655 SmallVector<int, 32> V1Mask(Mask.size(), -1);
7656 SmallVector<int, 32> V2Mask(Mask.size(), -1);
7658 for (int i = 0; i < Size; ++i) {
7662 // Each element of the unpack contains Scale elements from this mask.
7663 int UnpackIdx = i / Scale;
7665 // We only handle the case where V1 feeds the first slots of the unpack.
7666 // We rely on canonicalization to ensure this is the case.
7667 if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7670 // Setup the mask for this input. The indexing is tricky as we have to
7671 // handle the unpack stride.
7672 SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7673 VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7677 // If we will have to shuffle both inputs to use the unpack, check whether
7678 // we can just unpack first and shuffle the result. If so, skip this unpack.
7679 if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7680 !isNoopShuffleMask(V2Mask))
7683 // Shuffle the inputs into place.
7684 V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7685 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7687 // Cast the inputs to the type we will use to unpack them.
7688 V1 = DAG.getBitcast(UnpackVT, V1);
7689 V2 = DAG.getBitcast(UnpackVT, V2);
7691 // Unpack the inputs and cast the result back to the desired type.
7692 return DAG.getBitcast(
7693 VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7697 // We try each unpack from the largest to the smallest to try and find one
7698 // that fits this mask.
7699 int OrigNumElements = VT.getVectorNumElements();
7700 int OrigScalarSize = VT.getScalarSizeInBits();
7701 for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7702 int Scale = ScalarSize / OrigScalarSize;
7703 int NumElements = OrigNumElements / Scale;
7704 MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7705 if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7709 // If none of the unpack-rooted lowerings worked (or were profitable) try an
7711 if (NumLoInputs == 0 || NumHiInputs == 0) {
7712 assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7713 "We have to have *some* inputs!");
7714 int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7716 // FIXME: We could consider the total complexity of the permute of each
7717 // possible unpacking. Or at the least we should consider how many
7718 // half-crossings are created.
7719 // FIXME: We could consider commuting the unpacks.
7721 SmallVector<int, 32> PermMask;
7722 PermMask.assign(Size, -1);
7723 for (int i = 0; i < Size; ++i) {
7727 assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7730 2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7732 return DAG.getVectorShuffle(
7733 VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7735 DAG.getUNDEF(VT), PermMask);
7741 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7743 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7744 /// support for floating point shuffles but not integer shuffles. These
7745 /// instructions will incur a domain crossing penalty on some chips though so
7746 /// it is better to avoid lowering through this for integer vectors where
7748 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7749 const X86Subtarget *Subtarget,
7750 SelectionDAG &DAG) {
7752 assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7753 assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7754 assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7755 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7756 ArrayRef<int> Mask = SVOp->getMask();
7757 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7759 if (isSingleInputShuffleMask(Mask)) {
7760 // Use low duplicate instructions for masks that match their pattern.
7761 if (Subtarget->hasSSE3())
7762 if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7763 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7765 // Straight shuffle of a single input vector. Simulate this by using the
7766 // single input as both of the "inputs" to this instruction..
7767 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7769 if (Subtarget->hasAVX()) {
7770 // If we have AVX, we can use VPERMILPS which will allow folding a load
7771 // into the shuffle.
7772 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7773 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7776 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
7777 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7779 assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7780 assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7782 // If we have a single input, insert that into V1 if we can do so cheaply.
7783 if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7784 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7785 DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7787 // Try inverting the insertion since for v2 masks it is easy to do and we
7788 // can't reliably sort the mask one way or the other.
7789 int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7790 Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7791 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7792 DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7796 // Try to use one of the special instruction patterns to handle two common
7797 // blend patterns if a zero-blend above didn't work.
7798 if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7799 isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7800 if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7801 // We can either use a special instruction to load over the low double or
7802 // to move just the low double.
7804 isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7806 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7808 if (Subtarget->hasSSE41())
7809 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7813 // Use dedicated unpack instructions for masks that match their pattern.
7814 if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7815 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7816 if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7817 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7819 unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7820 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
7821 DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7824 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7826 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7827 /// the integer unit to minimize domain crossing penalties. However, for blends
7828 /// it falls back to the floating point shuffle operation with appropriate bit
7830 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7831 const X86Subtarget *Subtarget,
7832 SelectionDAG &DAG) {
7834 assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7835 assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7836 assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7837 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7838 ArrayRef<int> Mask = SVOp->getMask();
7839 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7841 if (isSingleInputShuffleMask(Mask)) {
7842 // Check for being able to broadcast a single element.
7843 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7844 Mask, Subtarget, DAG))
7847 // Straight shuffle of a single input vector. For everything from SSE2
7848 // onward this has a single fast instruction with no scary immediates.
7849 // We have to map the mask as it is actually a v4i32 shuffle instruction.
7850 V1 = DAG.getBitcast(MVT::v4i32, V1);
7851 int WidenedMask[4] = {
7852 std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7853 std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7854 return DAG.getBitcast(
7856 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7857 getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
7859 assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7860 assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7861 assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7862 assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7864 // If we have a blend of two PACKUS operations an the blend aligns with the
7865 // low and half halves, we can just merge the PACKUS operations. This is
7866 // particularly important as it lets us merge shuffles that this routine itself
7868 auto GetPackNode = [](SDValue V) {
7869 while (V.getOpcode() == ISD::BITCAST)
7870 V = V.getOperand(0);
7872 return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7874 if (SDValue V1Pack = GetPackNode(V1))
7875 if (SDValue V2Pack = GetPackNode(V2))
7876 return DAG.getBitcast(MVT::v2i64,
7877 DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7878 Mask[0] == 0 ? V1Pack.getOperand(0)
7879 : V1Pack.getOperand(1),
7880 Mask[1] == 2 ? V2Pack.getOperand(0)
7881 : V2Pack.getOperand(1)));
7883 // Try to use shift instructions.
7885 lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7888 // When loading a scalar and then shuffling it into a vector we can often do
7889 // the insertion cheaply.
7890 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7891 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7893 // Try inverting the insertion since for v2 masks it is easy to do and we
7894 // can't reliably sort the mask one way or the other.
7895 int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7896 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7897 DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7900 // We have different paths for blend lowering, but they all must use the
7901 // *exact* same predicate.
7902 bool IsBlendSupported = Subtarget->hasSSE41();
7903 if (IsBlendSupported)
7904 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7908 // Use dedicated unpack instructions for masks that match their pattern.
7909 if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7910 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7911 if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7912 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7914 // Try to use byte rotation instructions.
7915 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7916 if (Subtarget->hasSSSE3())
7917 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7918 DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7921 // If we have direct support for blends, we should lower by decomposing into
7922 // a permute. That will be faster than the domain cross.
7923 if (IsBlendSupported)
7924 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7927 // We implement this with SHUFPD which is pretty lame because it will likely
7928 // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7929 // However, all the alternatives are still more cycles and newer chips don't
7930 // have this problem. It would be really nice if x86 had better shuffles here.
7931 V1 = DAG.getBitcast(MVT::v2f64, V1);
7932 V2 = DAG.getBitcast(MVT::v2f64, V2);
7933 return DAG.getBitcast(MVT::v2i64,
7934 DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7937 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7939 /// This is used to disable more specialized lowerings when the shufps lowering
7940 /// will happen to be efficient.
7941 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7942 // This routine only handles 128-bit shufps.
7943 assert(Mask.size() == 4 && "Unsupported mask size!");
7945 // To lower with a single SHUFPS we need to have the low half and high half
7946 // each requiring a single input.
7947 if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7949 if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7955 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7957 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7958 /// It makes no assumptions about whether this is the *best* lowering, it simply
7960 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7961 ArrayRef<int> Mask, SDValue V1,
7962 SDValue V2, SelectionDAG &DAG) {
7963 SDValue LowV = V1, HighV = V2;
7964 int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7967 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7969 if (NumV2Elements == 1) {
7971 std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7974 // Compute the index adjacent to V2Index and in the same half by toggling
7976 int V2AdjIndex = V2Index ^ 1;
7978 if (Mask[V2AdjIndex] == -1) {
7979 // Handles all the cases where we have a single V2 element and an undef.
7980 // This will only ever happen in the high lanes because we commute the
7981 // vector otherwise.
7983 std::swap(LowV, HighV);
7984 NewMask[V2Index] -= 4;
7986 // Handle the case where the V2 element ends up adjacent to a V1 element.
7987 // To make this work, blend them together as the first step.
7988 int V1Index = V2AdjIndex;
7989 int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7990 V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
7991 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7993 // Now proceed to reconstruct the final blend as we have the necessary
7994 // high or low half formed.
8001 NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8002 NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8004 } else if (NumV2Elements == 2) {
8005 if (Mask[0] < 4 && Mask[1] < 4) {
8006 // Handle the easy case where we have V1 in the low lanes and V2 in the
8010 } else if (Mask[2] < 4 && Mask[3] < 4) {
8011 // We also handle the reversed case because this utility may get called
8012 // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8013 // arrange things in the right direction.
8019 // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8020 // trying to place elements directly, just blend them and set up the final
8021 // shuffle to place them.
8023 // The first two blend mask elements are for V1, the second two are for
8025 int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8026 Mask[2] < 4 ? Mask[2] : Mask[3],
8027 (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8028 (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8029 V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8030 getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8032 // Now we do a normal shuffle of V1 by giving V1 as both operands to
8035 NewMask[0] = Mask[0] < 4 ? 0 : 2;
8036 NewMask[1] = Mask[0] < 4 ? 2 : 0;
8037 NewMask[2] = Mask[2] < 4 ? 1 : 3;
8038 NewMask[3] = Mask[2] < 4 ? 3 : 1;
8041 return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8042 getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8045 /// \brief Lower 4-lane 32-bit floating point shuffles.
8047 /// Uses instructions exclusively from the floating point unit to minimize
8048 /// domain crossing penalties, as these are sufficient to implement all v4f32
8050 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8051 const X86Subtarget *Subtarget,
8052 SelectionDAG &DAG) {
8054 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8055 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8056 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8057 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8058 ArrayRef<int> Mask = SVOp->getMask();
8059 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8062 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8064 if (NumV2Elements == 0) {
8065 // Check for being able to broadcast a single element.
8066 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8067 Mask, Subtarget, DAG))
8070 // Use even/odd duplicate instructions for masks that match their pattern.
8071 if (Subtarget->hasSSE3()) {
8072 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8073 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8074 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8075 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8078 if (Subtarget->hasAVX()) {
8079 // If we have AVX, we can use VPERMILPS which will allow folding a load
8080 // into the shuffle.
8081 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8082 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8085 // Otherwise, use a straight shuffle of a single input vector. We pass the
8086 // input vector to both operands to simulate this with a SHUFPS.
8087 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8088 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8091 // There are special ways we can lower some single-element blends. However, we
8092 // have custom ways we can lower more complex single-element blends below that
8093 // we defer to if both this and BLENDPS fail to match, so restrict this to
8094 // when the V2 input is targeting element 0 of the mask -- that is the fast
8096 if (NumV2Elements == 1 && Mask[0] >= 4)
8097 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8098 Mask, Subtarget, DAG))
8101 if (Subtarget->hasSSE41()) {
8102 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8106 // Use INSERTPS if we can complete the shuffle efficiently.
8107 if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8110 if (!isSingleSHUFPSMask(Mask))
8111 if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8112 DL, MVT::v4f32, V1, V2, Mask, DAG))
8116 // Use dedicated unpack instructions for masks that match their pattern.
8117 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8118 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
8119 if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8120 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
8121 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8122 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
8123 if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8124 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
8126 // Otherwise fall back to a SHUFPS lowering strategy.
8127 return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8130 /// \brief Lower 4-lane i32 vector shuffles.
8132 /// We try to handle these with integer-domain shuffles where we can, but for
8133 /// blends we use the floating point domain blend instructions.
8134 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8135 const X86Subtarget *Subtarget,
8136 SelectionDAG &DAG) {
8138 assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8139 assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8140 assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8141 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8142 ArrayRef<int> Mask = SVOp->getMask();
8143 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8145 // Whenever we can lower this as a zext, that instruction is strictly faster
8146 // than any alternative. It also allows us to fold memory operands into the
8147 // shuffle in many cases.
8148 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8149 Mask, Subtarget, DAG))
8153 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8155 if (NumV2Elements == 0) {
8156 // Check for being able to broadcast a single element.
8157 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8158 Mask, Subtarget, DAG))
8161 // Straight shuffle of a single input vector. For everything from SSE2
8162 // onward this has a single fast instruction with no scary immediates.
8163 // We coerce the shuffle pattern to be compatible with UNPCK instructions
8164 // but we aren't actually going to use the UNPCK instruction because doing
8165 // so prevents folding a load into this instruction or making a copy.
8166 const int UnpackLoMask[] = {0, 0, 1, 1};
8167 const int UnpackHiMask[] = {2, 2, 3, 3};
8168 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8169 Mask = UnpackLoMask;
8170 else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8171 Mask = UnpackHiMask;
8173 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8174 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8177 // Try to use shift instructions.
8179 lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8182 // There are special ways we can lower some single-element blends.
8183 if (NumV2Elements == 1)
8184 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8185 Mask, Subtarget, DAG))
8188 // We have different paths for blend lowering, but they all must use the
8189 // *exact* same predicate.
8190 bool IsBlendSupported = Subtarget->hasSSE41();
8191 if (IsBlendSupported)
8192 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8196 if (SDValue Masked =
8197 lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8200 // Use dedicated unpack instructions for masks that match their pattern.
8201 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8202 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
8203 if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8204 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
8205 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8206 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
8207 if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8208 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
8210 // Try to use byte rotation instructions.
8211 // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8212 if (Subtarget->hasSSSE3())
8213 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8214 DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8217 // If we have direct support for blends, we should lower by decomposing into
8218 // a permute. That will be faster than the domain cross.
8219 if (IsBlendSupported)
8220 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8223 // Try to lower by permuting the inputs into an unpack instruction.
8224 if (SDValue Unpack =
8225 lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
8228 // We implement this with SHUFPS because it can blend from two vectors.
8229 // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8230 // up the inputs, bypassing domain shift penalties that we would encur if we
8231 // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8233 return DAG.getBitcast(
8235 DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8236 DAG.getBitcast(MVT::v4f32, V2), Mask));
8239 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8240 /// shuffle lowering, and the most complex part.
8242 /// The lowering strategy is to try to form pairs of input lanes which are
8243 /// targeted at the same half of the final vector, and then use a dword shuffle
8244 /// to place them onto the right half, and finally unpack the paired lanes into
8245 /// their final position.
8247 /// The exact breakdown of how to form these dword pairs and align them on the
8248 /// correct sides is really tricky. See the comments within the function for
8249 /// more of the details.
8251 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8252 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8253 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8254 /// vector, form the analogous 128-bit 8-element Mask.
8255 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8256 SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8257 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8258 assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
8259 MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8261 assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8262 MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8263 MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8265 SmallVector<int, 4> LoInputs;
8266 std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8267 [](int M) { return M >= 0; });
8268 std::sort(LoInputs.begin(), LoInputs.end());
8269 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8270 SmallVector<int, 4> HiInputs;
8271 std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8272 [](int M) { return M >= 0; });
8273 std::sort(HiInputs.begin(), HiInputs.end());
8274 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8276 std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8277 int NumHToL = LoInputs.size() - NumLToL;
8279 std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8280 int NumHToH = HiInputs.size() - NumLToH;
8281 MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8282 MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8283 MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8284 MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8286 // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8287 // such inputs we can swap two of the dwords across the half mark and end up
8288 // with <=2 inputs to each half in each half. Once there, we can fall through
8289 // to the generic code below. For example:
8291 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8292 // Mask: [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8294 // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8295 // and an existing 2-into-2 on the other half. In this case we may have to
8296 // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8297 // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8298 // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8299 // because any other situation (including a 3-into-1 or 1-into-3 in the other
8300 // half than the one we target for fixing) will be fixed when we re-enter this
8301 // path. We will also combine away any sequence of PSHUFD instructions that
8302 // result into a single instruction. Here is an example of the tricky case:
8304 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8305 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8307 // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8309 // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8310 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8312 // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8313 // Mask: [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8315 // The result is fine to be handled by the generic logic.
8316 auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8317 ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8318 int AOffset, int BOffset) {
8319 assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8320 "Must call this with A having 3 or 1 inputs from the A half.");
8321 assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8322 "Must call this with B having 1 or 3 inputs from the B half.");
8323 assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8324 "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8326 // Compute the index of dword with only one word among the three inputs in
8327 // a half by taking the sum of the half with three inputs and subtracting
8328 // the sum of the actual three inputs. The difference is the remaining
8331 int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
8332 int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
8333 int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
8334 ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
8335 int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
8336 int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8337 int TripleNonInputIdx =
8338 TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8339 TripleDWord = TripleNonInputIdx / 2;
8341 // We use xor with one to compute the adjacent DWord to whichever one the
8343 OneInputDWord = (OneInput / 2) ^ 1;
8345 // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8346 // and BToA inputs. If there is also such a problem with the BToB and AToB
8347 // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8348 // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8349 // is essential that we don't *create* a 3<-1 as then we might oscillate.
8350 if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8351 // Compute how many inputs will be flipped by swapping these DWords. We
8353 // to balance this to ensure we don't form a 3-1 shuffle in the other
8355 int NumFlippedAToBInputs =
8356 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8357 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8358 int NumFlippedBToBInputs =
8359 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8360 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8361 if ((NumFlippedAToBInputs == 1 &&
8362 (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8363 (NumFlippedBToBInputs == 1 &&
8364 (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8365 // We choose whether to fix the A half or B half based on whether that
8366 // half has zero flipped inputs. At zero, we may not be able to fix it
8367 // with that half. We also bias towards fixing the B half because that
8368 // will more commonly be the high half, and we have to bias one way.
8369 auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8370 ArrayRef<int> Inputs) {
8371 int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8372 bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8373 PinnedIdx ^ 1) != Inputs.end();
8374 // Determine whether the free index is in the flipped dword or the
8375 // unflipped dword based on where the pinned index is. We use this bit
8376 // in an xor to conditionally select the adjacent dword.
8377 int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8378 bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8379 FixFreeIdx) != Inputs.end();
8380 if (IsFixIdxInput == IsFixFreeIdxInput)
8382 IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8383 FixFreeIdx) != Inputs.end();
8384 assert(IsFixIdxInput != IsFixFreeIdxInput &&
8385 "We need to be changing the number of flipped inputs!");
8386 int PSHUFHalfMask[] = {0, 1, 2, 3};
8387 std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8388 V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8390 getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8393 if (M != -1 && M == FixIdx)
8395 else if (M != -1 && M == FixFreeIdx)
8398 if (NumFlippedBToBInputs != 0) {
8400 BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8401 FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8403 assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8405 AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8406 FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8411 int PSHUFDMask[] = {0, 1, 2, 3};
8412 PSHUFDMask[ADWord] = BDWord;
8413 PSHUFDMask[BDWord] = ADWord;
8416 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8417 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8419 // Adjust the mask to match the new locations of A and B.
8421 if (M != -1 && M/2 == ADWord)
8422 M = 2 * BDWord + M % 2;
8423 else if (M != -1 && M/2 == BDWord)
8424 M = 2 * ADWord + M % 2;
8426 // Recurse back into this routine to re-compute state now that this isn't
8427 // a 3 and 1 problem.
8428 return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8431 if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8432 return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8433 else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8434 return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8436 // At this point there are at most two inputs to the low and high halves from
8437 // each half. That means the inputs can always be grouped into dwords and
8438 // those dwords can then be moved to the correct half with a dword shuffle.
8439 // We use at most one low and one high word shuffle to collect these paired
8440 // inputs into dwords, and finally a dword shuffle to place them.
8441 int PSHUFLMask[4] = {-1, -1, -1, -1};
8442 int PSHUFHMask[4] = {-1, -1, -1, -1};
8443 int PSHUFDMask[4] = {-1, -1, -1, -1};
8445 // First fix the masks for all the inputs that are staying in their
8446 // original halves. This will then dictate the targets of the cross-half
8448 auto fixInPlaceInputs =
8449 [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8450 MutableArrayRef<int> SourceHalfMask,
8451 MutableArrayRef<int> HalfMask, int HalfOffset) {
8452 if (InPlaceInputs.empty())
8454 if (InPlaceInputs.size() == 1) {
8455 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8456 InPlaceInputs[0] - HalfOffset;
8457 PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8460 if (IncomingInputs.empty()) {
8461 // Just fix all of the in place inputs.
8462 for (int Input : InPlaceInputs) {
8463 SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8464 PSHUFDMask[Input / 2] = Input / 2;
8469 assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8470 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8471 InPlaceInputs[0] - HalfOffset;
8472 // Put the second input next to the first so that they are packed into
8473 // a dword. We find the adjacent index by toggling the low bit.
8474 int AdjIndex = InPlaceInputs[0] ^ 1;
8475 SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8476 std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8477 PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8479 fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8480 fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8482 // Now gather the cross-half inputs and place them into a free dword of
8483 // their target half.
8484 // FIXME: This operation could almost certainly be simplified dramatically to
8485 // look more like the 3-1 fixing operation.
8486 auto moveInputsToRightHalf = [&PSHUFDMask](
8487 MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8488 MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8489 MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8491 auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8492 return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8494 auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8496 int LowWord = Word & ~1;
8497 int HighWord = Word | 1;
8498 return isWordClobbered(SourceHalfMask, LowWord) ||
8499 isWordClobbered(SourceHalfMask, HighWord);
8502 if (IncomingInputs.empty())
8505 if (ExistingInputs.empty()) {
8506 // Map any dwords with inputs from them into the right half.
8507 for (int Input : IncomingInputs) {
8508 // If the source half mask maps over the inputs, turn those into
8509 // swaps and use the swapped lane.
8510 if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8511 if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8512 SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8513 Input - SourceOffset;
8514 // We have to swap the uses in our half mask in one sweep.
8515 for (int &M : HalfMask)
8516 if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8518 else if (M == Input)
8519 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8521 assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8522 Input - SourceOffset &&
8523 "Previous placement doesn't match!");
8525 // Note that this correctly re-maps both when we do a swap and when
8526 // we observe the other side of the swap above. We rely on that to
8527 // avoid swapping the members of the input list directly.
8528 Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8531 // Map the input's dword into the correct half.
8532 if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8533 PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8535 assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8537 "Previous placement doesn't match!");
8540 // And just directly shift any other-half mask elements to be same-half
8541 // as we will have mirrored the dword containing the element into the
8542 // same position within that half.
8543 for (int &M : HalfMask)
8544 if (M >= SourceOffset && M < SourceOffset + 4) {
8545 M = M - SourceOffset + DestOffset;
8546 assert(M >= 0 && "This should never wrap below zero!");
8551 // Ensure we have the input in a viable dword of its current half. This
8552 // is particularly tricky because the original position may be clobbered
8553 // by inputs being moved and *staying* in that half.
8554 if (IncomingInputs.size() == 1) {
8555 if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8556 int InputFixed = std::find(std::begin(SourceHalfMask),
8557 std::end(SourceHalfMask), -1) -
8558 std::begin(SourceHalfMask) + SourceOffset;
8559 SourceHalfMask[InputFixed - SourceOffset] =
8560 IncomingInputs[0] - SourceOffset;
8561 std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8563 IncomingInputs[0] = InputFixed;
8565 } else if (IncomingInputs.size() == 2) {
8566 if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8567 isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8568 // We have two non-adjacent or clobbered inputs we need to extract from
8569 // the source half. To do this, we need to map them into some adjacent
8570 // dword slot in the source mask.
8571 int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8572 IncomingInputs[1] - SourceOffset};
8574 // If there is a free slot in the source half mask adjacent to one of
8575 // the inputs, place the other input in it. We use (Index XOR 1) to
8576 // compute an adjacent index.
8577 if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8578 SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8579 SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8580 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8581 InputsFixed[1] = InputsFixed[0] ^ 1;
8582 } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8583 SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8584 SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8585 SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8586 InputsFixed[0] = InputsFixed[1] ^ 1;
8587 } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8588 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8589 // The two inputs are in the same DWord but it is clobbered and the
8590 // adjacent DWord isn't used at all. Move both inputs to the free
8592 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8593 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8594 InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8595 InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8597 // The only way we hit this point is if there is no clobbering
8598 // (because there are no off-half inputs to this half) and there is no
8599 // free slot adjacent to one of the inputs. In this case, we have to
8600 // swap an input with a non-input.
8601 for (int i = 0; i < 4; ++i)
8602 assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8603 "We can't handle any clobbers here!");
8604 assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8605 "Cannot have adjacent inputs here!");
8607 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8608 SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8610 // We also have to update the final source mask in this case because
8611 // it may need to undo the above swap.
8612 for (int &M : FinalSourceHalfMask)
8613 if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8614 M = InputsFixed[1] + SourceOffset;
8615 else if (M == InputsFixed[1] + SourceOffset)
8616 M = (InputsFixed[0] ^ 1) + SourceOffset;
8618 InputsFixed[1] = InputsFixed[0] ^ 1;
8621 // Point everything at the fixed inputs.
8622 for (int &M : HalfMask)
8623 if (M == IncomingInputs[0])
8624 M = InputsFixed[0] + SourceOffset;
8625 else if (M == IncomingInputs[1])
8626 M = InputsFixed[1] + SourceOffset;
8628 IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8629 IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8632 llvm_unreachable("Unhandled input size!");
8635 // Now hoist the DWord down to the right half.
8636 int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8637 assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8638 PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8639 for (int &M : HalfMask)
8640 for (int Input : IncomingInputs)
8642 M = FreeDWord * 2 + Input % 2;
8644 moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8645 /*SourceOffset*/ 4, /*DestOffset*/ 0);
8646 moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8647 /*SourceOffset*/ 0, /*DestOffset*/ 4);
8649 // Now enact all the shuffles we've computed to move the inputs into their
8651 if (!isNoopShuffleMask(PSHUFLMask))
8652 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8653 getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8654 if (!isNoopShuffleMask(PSHUFHMask))
8655 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8656 getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8657 if (!isNoopShuffleMask(PSHUFDMask))
8660 DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8661 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8663 // At this point, each half should contain all its inputs, and we can then
8664 // just shuffle them into their final position.
8665 assert(std::count_if(LoMask.begin(), LoMask.end(),
8666 [](int M) { return M >= 4; }) == 0 &&
8667 "Failed to lift all the high half inputs to the low mask!");
8668 assert(std::count_if(HiMask.begin(), HiMask.end(),
8669 [](int M) { return M >= 0 && M < 4; }) == 0 &&
8670 "Failed to lift all the low half inputs to the high mask!");
8672 // Do a half shuffle for the low mask.
8673 if (!isNoopShuffleMask(LoMask))
8674 V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8675 getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8677 // Do a half shuffle with the high mask after shifting its values down.
8678 for (int &M : HiMask)
8681 if (!isNoopShuffleMask(HiMask))
8682 V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8683 getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8688 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8689 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8690 SDValue V2, ArrayRef<int> Mask,
8691 SelectionDAG &DAG, bool &V1InUse,
8693 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8699 int Size = Mask.size();
8700 int Scale = 16 / Size;
8701 for (int i = 0; i < 16; ++i) {
8702 if (Mask[i / Scale] == -1) {
8703 V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8705 const int ZeroMask = 0x80;
8706 int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8708 int V2Idx = Mask[i / Scale] < Size
8710 : (Mask[i / Scale] - Size) * Scale + i % Scale;
8711 if (Zeroable[i / Scale])
8712 V1Idx = V2Idx = ZeroMask;
8713 V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
8714 V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
8715 V1InUse |= (ZeroMask != V1Idx);
8716 V2InUse |= (ZeroMask != V2Idx);
8721 V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8722 DAG.getBitcast(MVT::v16i8, V1),
8723 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8725 V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8726 DAG.getBitcast(MVT::v16i8, V2),
8727 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8729 // If we need shuffled inputs from both, blend the two.
8731 if (V1InUse && V2InUse)
8732 V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8734 V = V1InUse ? V1 : V2;
8736 // Cast the result back to the correct type.
8737 return DAG.getBitcast(VT, V);
8740 /// \brief Generic lowering of 8-lane i16 shuffles.
8742 /// This handles both single-input shuffles and combined shuffle/blends with
8743 /// two inputs. The single input shuffles are immediately delegated to
8744 /// a dedicated lowering routine.
8746 /// The blends are lowered in one of three fundamental ways. If there are few
8747 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8748 /// of the input is significantly cheaper when lowered as an interleaving of
8749 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8750 /// halves of the inputs separately (making them have relatively few inputs)
8751 /// and then concatenate them.
8752 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8753 const X86Subtarget *Subtarget,
8754 SelectionDAG &DAG) {
8756 assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8757 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8758 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8759 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8760 ArrayRef<int> OrigMask = SVOp->getMask();
8761 int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8762 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8763 MutableArrayRef<int> Mask(MaskStorage);
8765 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8767 // Whenever we can lower this as a zext, that instruction is strictly faster
8768 // than any alternative.
8769 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8770 DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8773 auto isV1 = [](int M) { return M >= 0 && M < 8; };
8775 auto isV2 = [](int M) { return M >= 8; };
8777 int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8779 if (NumV2Inputs == 0) {
8780 // Check for being able to broadcast a single element.
8781 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8782 Mask, Subtarget, DAG))
8785 // Try to use shift instructions.
8787 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8790 // Use dedicated unpack instructions for masks that match their pattern.
8791 if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8792 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8793 if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8794 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8796 // Try to use byte rotation instructions.
8797 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8798 Mask, Subtarget, DAG))
8801 return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8805 assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8806 "All single-input shuffles should be canonicalized to be V1-input "
8809 // Try to use shift instructions.
8811 lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8814 // See if we can use SSE4A Extraction / Insertion.
8815 if (Subtarget->hasSSE4A())
8816 if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
8819 // There are special ways we can lower some single-element blends.
8820 if (NumV2Inputs == 1)
8821 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8822 Mask, Subtarget, DAG))
8825 // We have different paths for blend lowering, but they all must use the
8826 // *exact* same predicate.
8827 bool IsBlendSupported = Subtarget->hasSSE41();
8828 if (IsBlendSupported)
8829 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8833 if (SDValue Masked =
8834 lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8837 // Use dedicated unpack instructions for masks that match their pattern.
8838 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8839 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8840 if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8841 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8843 // Try to use byte rotation instructions.
8844 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8845 DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8848 if (SDValue BitBlend =
8849 lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8852 if (SDValue Unpack =
8853 lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8856 // If we can't directly blend but can use PSHUFB, that will be better as it
8857 // can both shuffle and set up the inefficient blend.
8858 if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8859 bool V1InUse, V2InUse;
8860 return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8864 // We can always bit-blend if we have to so the fallback strategy is to
8865 // decompose into single-input permutes and blends.
8866 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8870 /// \brief Check whether a compaction lowering can be done by dropping even
8871 /// elements and compute how many times even elements must be dropped.
8873 /// This handles shuffles which take every Nth element where N is a power of
8874 /// two. Example shuffle masks:
8876 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14
8877 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8878 /// N = 2: 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12
8879 /// N = 2: 0, 4, 8, 12, 16, 20, 24, 28, 0, 4, 8, 12, 16, 20, 24, 28
8880 /// N = 3: 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8
8881 /// N = 3: 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24
8883 /// Any of these lanes can of course be undef.
8885 /// This routine only supports N <= 3.
8886 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8889 /// \returns N above, or the number of times even elements must be dropped if
8890 /// there is such a number. Otherwise returns zero.
8891 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8892 // Figure out whether we're looping over two inputs or just one.
8893 bool IsSingleInput = isSingleInputShuffleMask(Mask);
8895 // The modulus for the shuffle vector entries is based on whether this is
8896 // a single input or not.
8897 int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8898 assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8899 "We should only be called with masks with a power-of-2 size!");
8901 uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8903 // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8904 // and 2^3 simultaneously. This is because we may have ambiguity with
8905 // partially undef inputs.
8906 bool ViableForN[3] = {true, true, true};
8908 for (int i = 0, e = Mask.size(); i < e; ++i) {
8909 // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8914 bool IsAnyViable = false;
8915 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8916 if (ViableForN[j]) {
8919 // The shuffle mask must be equal to (i * 2^N) % M.
8920 if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8923 ViableForN[j] = false;
8925 // Early exit if we exhaust the possible powers of two.
8930 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8934 // Return 0 as there is no viable power of two.
8938 /// \brief Generic lowering of v16i8 shuffles.
8940 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8941 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8942 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8943 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8945 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8946 const X86Subtarget *Subtarget,
8947 SelectionDAG &DAG) {
8949 assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8950 assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8951 assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8952 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8953 ArrayRef<int> Mask = SVOp->getMask();
8954 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8956 // Try to use shift instructions.
8958 lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8961 // Try to use byte rotation instructions.
8962 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8963 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8966 // Try to use a zext lowering.
8967 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8968 DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8971 // See if we can use SSE4A Extraction / Insertion.
8972 if (Subtarget->hasSSE4A())
8973 if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
8977 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8979 // For single-input shuffles, there are some nicer lowering tricks we can use.
8980 if (NumV2Elements == 0) {
8981 // Check for being able to broadcast a single element.
8982 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
8983 Mask, Subtarget, DAG))
8986 // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8987 // Notably, this handles splat and partial-splat shuffles more efficiently.
8988 // However, it only makes sense if the pre-duplication shuffle simplifies
8989 // things significantly. Currently, this means we need to be able to
8990 // express the pre-duplication shuffle as an i16 shuffle.
8992 // FIXME: We should check for other patterns which can be widened into an
8993 // i16 shuffle as well.
8994 auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8995 for (int i = 0; i < 16; i += 2)
8996 if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9001 auto tryToWidenViaDuplication = [&]() -> SDValue {
9002 if (!canWidenViaDuplication(Mask))
9004 SmallVector<int, 4> LoInputs;
9005 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9006 [](int M) { return M >= 0 && M < 8; });
9007 std::sort(LoInputs.begin(), LoInputs.end());
9008 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9010 SmallVector<int, 4> HiInputs;
9011 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9012 [](int M) { return M >= 8; });
9013 std::sort(HiInputs.begin(), HiInputs.end());
9014 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9017 bool TargetLo = LoInputs.size() >= HiInputs.size();
9018 ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9019 ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9021 int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9022 SmallDenseMap<int, int, 8> LaneMap;
9023 for (int I : InPlaceInputs) {
9024 PreDupI16Shuffle[I/2] = I/2;
9027 int j = TargetLo ? 0 : 4, je = j + 4;
9028 for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9029 // Check if j is already a shuffle of this input. This happens when
9030 // there are two adjacent bytes after we move the low one.
9031 if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9032 // If we haven't yet mapped the input, search for a slot into which
9034 while (j < je && PreDupI16Shuffle[j] != -1)
9038 // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9041 // Map this input with the i16 shuffle.
9042 PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9045 // Update the lane map based on the mapping we ended up with.
9046 LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9048 V1 = DAG.getBitcast(
9050 DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9051 DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9053 // Unpack the bytes to form the i16s that will be shuffled into place.
9054 V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9055 MVT::v16i8, V1, V1);
9057 int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9058 for (int i = 0; i < 16; ++i)
9059 if (Mask[i] != -1) {
9060 int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9061 assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9062 if (PostDupI16Shuffle[i / 2] == -1)
9063 PostDupI16Shuffle[i / 2] = MappedMask;
9065 assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9066 "Conflicting entrties in the original shuffle!");
9068 return DAG.getBitcast(
9070 DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9071 DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9073 if (SDValue V = tryToWidenViaDuplication())
9077 if (SDValue Masked =
9078 lowerVectorShuffleAsBitMask(DL, MVT::v16i8, V1, V2, Mask, DAG))
9081 // Use dedicated unpack instructions for masks that match their pattern.
9082 if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9083 0, 16, 1, 17, 2, 18, 3, 19,
9085 4, 20, 5, 21, 6, 22, 7, 23}))
9086 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
9087 if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9088 8, 24, 9, 25, 10, 26, 11, 27,
9090 12, 28, 13, 29, 14, 30, 15, 31}))
9091 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
9093 // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9094 // with PSHUFB. It is important to do this before we attempt to generate any
9095 // blends but after all of the single-input lowerings. If the single input
9096 // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9097 // want to preserve that and we can DAG combine any longer sequences into
9098 // a PSHUFB in the end. But once we start blending from multiple inputs,
9099 // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9100 // and there are *very* few patterns that would actually be faster than the
9101 // PSHUFB approach because of its ability to zero lanes.
9103 // FIXME: The only exceptions to the above are blends which are exact
9104 // interleavings with direct instructions supporting them. We currently don't
9105 // handle those well here.
9106 if (Subtarget->hasSSSE3()) {
9107 bool V1InUse = false;
9108 bool V2InUse = false;
9110 SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9111 DAG, V1InUse, V2InUse);
9113 // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9114 // do so. This avoids using them to handle blends-with-zero which is
9115 // important as a single pshufb is significantly faster for that.
9116 if (V1InUse && V2InUse) {
9117 if (Subtarget->hasSSE41())
9118 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9119 Mask, Subtarget, DAG))
9122 // We can use an unpack to do the blending rather than an or in some
9123 // cases. Even though the or may be (very minorly) more efficient, we
9124 // preference this lowering because there are common cases where part of
9125 // the complexity of the shuffles goes away when we do the final blend as
9127 // FIXME: It might be worth trying to detect if the unpack-feeding
9128 // shuffles will both be pshufb, in which case we shouldn't bother with
9130 if (SDValue Unpack =
9131 lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
9138 // There are special ways we can lower some single-element blends.
9139 if (NumV2Elements == 1)
9140 if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9141 Mask, Subtarget, DAG))
9144 if (SDValue BitBlend =
9145 lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9148 // Check whether a compaction lowering can be done. This handles shuffles
9149 // which take every Nth element for some even N. See the helper function for
9152 // We special case these as they can be particularly efficiently handled with
9153 // the PACKUSB instruction on x86 and they show up in common patterns of
9154 // rearranging bytes to truncate wide elements.
9155 if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9156 // NumEvenDrops is the power of two stride of the elements. Another way of
9157 // thinking about it is that we need to drop the even elements this many
9158 // times to get the original input.
9159 bool IsSingleInput = isSingleInputShuffleMask(Mask);
9161 // First we need to zero all the dropped bytes.
9162 assert(NumEvenDrops <= 3 &&
9163 "No support for dropping even elements more than 3 times.");
9164 // We use the mask type to pick which bytes are preserved based on how many
9165 // elements are dropped.
9166 MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9167 SDValue ByteClearMask = DAG.getBitcast(
9168 MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9169 V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9171 V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9173 // Now pack things back together.
9174 V1 = DAG.getBitcast(MVT::v8i16, V1);
9175 V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9176 SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9177 for (int i = 1; i < NumEvenDrops; ++i) {
9178 Result = DAG.getBitcast(MVT::v8i16, Result);
9179 Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9185 // Handle multi-input cases by blending single-input shuffles.
9186 if (NumV2Elements > 0)
9187 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9190 // The fallback path for single-input shuffles widens this into two v8i16
9191 // vectors with unpacks, shuffles those, and then pulls them back together
9195 int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9196 int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9197 for (int i = 0; i < 16; ++i)
9199 (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9201 SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9203 SDValue VLoHalf, VHiHalf;
9204 // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9205 // them out and avoid using UNPCK{L,H} to extract the elements of V as
9207 if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9208 [](int M) { return M >= 0 && M % 2 == 1; }) &&
9209 std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9210 [](int M) { return M >= 0 && M % 2 == 1; })) {
9211 // Use a mask to drop the high bytes.
9212 VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9213 VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9214 DAG.getConstant(0x00FF, DL, MVT::v8i16));
9216 // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9217 VHiHalf = DAG.getUNDEF(MVT::v8i16);
9219 // Squash the masks to point directly into VLoHalf.
9220 for (int &M : LoBlendMask)
9223 for (int &M : HiBlendMask)
9227 // Otherwise just unpack the low half of V into VLoHalf and the high half into
9228 // VHiHalf so that we can blend them as i16s.
9229 VLoHalf = DAG.getBitcast(
9230 MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9231 VHiHalf = DAG.getBitcast(
9232 MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9235 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9236 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9238 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9241 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9243 /// This routine breaks down the specific type of 128-bit shuffle and
9244 /// dispatches to the lowering routines accordingly.
9245 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9246 MVT VT, const X86Subtarget *Subtarget,
9247 SelectionDAG &DAG) {
9248 switch (VT.SimpleTy) {
9250 return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9252 return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9254 return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9256 return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9258 return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9260 return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9263 llvm_unreachable("Unimplemented!");
9267 /// \brief Helper function to test whether a shuffle mask could be
9268 /// simplified by widening the elements being shuffled.
9270 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9271 /// leaves it in an unspecified state.
9273 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9274 /// shuffle masks. The latter have the special property of a '-2' representing
9275 /// a zero-ed lane of a vector.
9276 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9277 SmallVectorImpl<int> &WidenedMask) {
9278 for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9279 // If both elements are undef, its trivial.
9280 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9281 WidenedMask.push_back(SM_SentinelUndef);
9285 // Check for an undef mask and a mask value properly aligned to fit with
9286 // a pair of values. If we find such a case, use the non-undef mask's value.
9287 if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9288 WidenedMask.push_back(Mask[i + 1] / 2);
9291 if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9292 WidenedMask.push_back(Mask[i] / 2);
9296 // When zeroing, we need to spread the zeroing across both lanes to widen.
9297 if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9298 if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9299 (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9300 WidenedMask.push_back(SM_SentinelZero);
9306 // Finally check if the two mask values are adjacent and aligned with
9308 if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9309 WidenedMask.push_back(Mask[i] / 2);
9313 // Otherwise we can't safely widen the elements used in this shuffle.
9316 assert(WidenedMask.size() == Mask.size() / 2 &&
9317 "Incorrect size of mask after widening the elements!");
9322 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9324 /// This routine just extracts two subvectors, shuffles them independently, and
9325 /// then concatenates them back together. This should work effectively with all
9326 /// AVX vector shuffle types.
9327 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9328 SDValue V2, ArrayRef<int> Mask,
9329 SelectionDAG &DAG) {
9330 assert(VT.getSizeInBits() >= 256 &&
9331 "Only for 256-bit or wider vector shuffles!");
9332 assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9333 assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9335 ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9336 ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9338 int NumElements = VT.getVectorNumElements();
9339 int SplitNumElements = NumElements / 2;
9340 MVT ScalarVT = VT.getScalarType();
9341 MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9343 // Rather than splitting build-vectors, just build two narrower build
9344 // vectors. This helps shuffling with splats and zeros.
9345 auto SplitVector = [&](SDValue V) {
9346 while (V.getOpcode() == ISD::BITCAST)
9347 V = V->getOperand(0);
9349 MVT OrigVT = V.getSimpleValueType();
9350 int OrigNumElements = OrigVT.getVectorNumElements();
9351 int OrigSplitNumElements = OrigNumElements / 2;
9352 MVT OrigScalarVT = OrigVT.getScalarType();
9353 MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9357 auto *BV = dyn_cast<BuildVectorSDNode>(V);
9359 LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9360 DAG.getIntPtrConstant(0, DL));
9361 HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9362 DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9365 SmallVector<SDValue, 16> LoOps, HiOps;
9366 for (int i = 0; i < OrigSplitNumElements; ++i) {
9367 LoOps.push_back(BV->getOperand(i));
9368 HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9370 LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9371 HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9373 return std::make_pair(DAG.getBitcast(SplitVT, LoV),
9374 DAG.getBitcast(SplitVT, HiV));
9377 SDValue LoV1, HiV1, LoV2, HiV2;
9378 std::tie(LoV1, HiV1) = SplitVector(V1);
9379 std::tie(LoV2, HiV2) = SplitVector(V2);
9381 // Now create two 4-way blends of these half-width vectors.
9382 auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9383 bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9384 SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9385 for (int i = 0; i < SplitNumElements; ++i) {
9386 int M = HalfMask[i];
9387 if (M >= NumElements) {
9388 if (M >= NumElements + SplitNumElements)
9392 V2BlendMask.push_back(M - NumElements);
9393 V1BlendMask.push_back(-1);
9394 BlendMask.push_back(SplitNumElements + i);
9395 } else if (M >= 0) {
9396 if (M >= SplitNumElements)
9400 V2BlendMask.push_back(-1);
9401 V1BlendMask.push_back(M);
9402 BlendMask.push_back(i);
9404 V2BlendMask.push_back(-1);
9405 V1BlendMask.push_back(-1);
9406 BlendMask.push_back(-1);
9410 // Because the lowering happens after all combining takes place, we need to
9411 // manually combine these blend masks as much as possible so that we create
9412 // a minimal number of high-level vector shuffle nodes.
9414 // First try just blending the halves of V1 or V2.
9415 if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9416 return DAG.getUNDEF(SplitVT);
9417 if (!UseLoV2 && !UseHiV2)
9418 return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9419 if (!UseLoV1 && !UseHiV1)
9420 return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9422 SDValue V1Blend, V2Blend;
9423 if (UseLoV1 && UseHiV1) {
9425 DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9427 // We only use half of V1 so map the usage down into the final blend mask.
9428 V1Blend = UseLoV1 ? LoV1 : HiV1;
9429 for (int i = 0; i < SplitNumElements; ++i)
9430 if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9431 BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9433 if (UseLoV2 && UseHiV2) {
9435 DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9437 // We only use half of V2 so map the usage down into the final blend mask.
9438 V2Blend = UseLoV2 ? LoV2 : HiV2;
9439 for (int i = 0; i < SplitNumElements; ++i)
9440 if (BlendMask[i] >= SplitNumElements)
9441 BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9443 return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9445 SDValue Lo = HalfBlend(LoMask);
9446 SDValue Hi = HalfBlend(HiMask);
9447 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9450 /// \brief Either split a vector in halves or decompose the shuffles and the
9453 /// This is provided as a good fallback for many lowerings of non-single-input
9454 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9455 /// between splitting the shuffle into 128-bit components and stitching those
9456 /// back together vs. extracting the single-input shuffles and blending those
9458 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9459 SDValue V2, ArrayRef<int> Mask,
9460 SelectionDAG &DAG) {
9461 assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9462 "lower single-input shuffles as it "
9463 "could then recurse on itself.");
9464 int Size = Mask.size();
9466 // If this can be modeled as a broadcast of two elements followed by a blend,
9467 // prefer that lowering. This is especially important because broadcasts can
9468 // often fold with memory operands.
9469 auto DoBothBroadcast = [&] {
9470 int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9473 if (V2BroadcastIdx == -1)
9474 V2BroadcastIdx = M - Size;
9475 else if (M - Size != V2BroadcastIdx)
9477 } else if (M >= 0) {
9478 if (V1BroadcastIdx == -1)
9480 else if (M != V1BroadcastIdx)
9485 if (DoBothBroadcast())
9486 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9489 // If the inputs all stem from a single 128-bit lane of each input, then we
9490 // split them rather than blending because the split will decompose to
9491 // unusually few instructions.
9492 int LaneCount = VT.getSizeInBits() / 128;
9493 int LaneSize = Size / LaneCount;
9494 SmallBitVector LaneInputs[2];
9495 LaneInputs[0].resize(LaneCount, false);
9496 LaneInputs[1].resize(LaneCount, false);
9497 for (int i = 0; i < Size; ++i)
9499 LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9500 if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9501 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9503 // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9504 // that the decomposed single-input shuffles don't end up here.
9505 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9508 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9509 /// a permutation and blend of those lanes.
9511 /// This essentially blends the out-of-lane inputs to each lane into the lane
9512 /// from a permuted copy of the vector. This lowering strategy results in four
9513 /// instructions in the worst case for a single-input cross lane shuffle which
9514 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9515 /// of. Special cases for each particular shuffle pattern should be handled
9516 /// prior to trying this lowering.
9517 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9518 SDValue V1, SDValue V2,
9520 SelectionDAG &DAG) {
9521 // FIXME: This should probably be generalized for 512-bit vectors as well.
9522 assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9523 int LaneSize = Mask.size() / 2;
9525 // If there are only inputs from one 128-bit lane, splitting will in fact be
9526 // less expensive. The flags track whether the given lane contains an element
9527 // that crosses to another lane.
9528 bool LaneCrossing[2] = {false, false};
9529 for (int i = 0, Size = Mask.size(); i < Size; ++i)
9530 if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9531 LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9532 if (!LaneCrossing[0] || !LaneCrossing[1])
9533 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9535 if (isSingleInputShuffleMask(Mask)) {
9536 SmallVector<int, 32> FlippedBlendMask;
9537 for (int i = 0, Size = Mask.size(); i < Size; ++i)
9538 FlippedBlendMask.push_back(
9539 Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9541 : Mask[i] % LaneSize +
9542 (i / LaneSize) * LaneSize + Size));
9544 // Flip the vector, and blend the results which should now be in-lane. The
9545 // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9546 // 5 for the high source. The value 3 selects the high half of source 2 and
9547 // the value 2 selects the low half of source 2. We only use source 2 to
9548 // allow folding it into a memory operand.
9549 unsigned PERMMask = 3 | 2 << 4;
9550 SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9551 V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9552 return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9555 // This now reduces to two single-input shuffles of V1 and V2 which at worst
9556 // will be handled by the above logic and a blend of the results, much like
9557 // other patterns in AVX.
9558 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9561 /// \brief Handle lowering 2-lane 128-bit shuffles.
9562 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9563 SDValue V2, ArrayRef<int> Mask,
9564 const X86Subtarget *Subtarget,
9565 SelectionDAG &DAG) {
9566 // TODO: If minimizing size and one of the inputs is a zero vector and the
9567 // the zero vector has only one use, we could use a VPERM2X128 to save the
9568 // instruction bytes needed to explicitly generate the zero vector.
9570 // Blends are faster and handle all the non-lane-crossing cases.
9571 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9575 bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9576 bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9578 // If either input operand is a zero vector, use VPERM2X128 because its mask
9579 // allows us to replace the zero input with an implicit zero.
9580 if (!IsV1Zero && !IsV2Zero) {
9581 // Check for patterns which can be matched with a single insert of a 128-bit
9583 bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9584 if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9585 MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9586 VT.getVectorNumElements() / 2);
9587 SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9588 DAG.getIntPtrConstant(0, DL));
9589 SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9590 OnlyUsesV1 ? V1 : V2,
9591 DAG.getIntPtrConstant(0, DL));
9592 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9596 // Otherwise form a 128-bit permutation. After accounting for undefs,
9597 // convert the 64-bit shuffle mask selection values into 128-bit
9598 // selection bits by dividing the indexes by 2 and shifting into positions
9599 // defined by a vperm2*128 instruction's immediate control byte.
9601 // The immediate permute control byte looks like this:
9602 // [1:0] - select 128 bits from sources for low half of destination
9604 // [3] - zero low half of destination
9605 // [5:4] - select 128 bits from sources for high half of destination
9607 // [7] - zero high half of destination
9609 int MaskLO = Mask[0];
9610 if (MaskLO == SM_SentinelUndef)
9611 MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9613 int MaskHI = Mask[2];
9614 if (MaskHI == SM_SentinelUndef)
9615 MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9617 unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9619 // If either input is a zero vector, replace it with an undef input.
9620 // Shuffle mask values < 4 are selecting elements of V1.
9621 // Shuffle mask values >= 4 are selecting elements of V2.
9622 // Adjust each half of the permute mask by clearing the half that was
9623 // selecting the zero vector and setting the zero mask bit.
9625 V1 = DAG.getUNDEF(VT);
9627 PermMask = (PermMask & 0xf0) | 0x08;
9629 PermMask = (PermMask & 0x0f) | 0x80;
9632 V2 = DAG.getUNDEF(VT);
9634 PermMask = (PermMask & 0xf0) | 0x08;
9636 PermMask = (PermMask & 0x0f) | 0x80;
9639 return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9640 DAG.getConstant(PermMask, DL, MVT::i8));
9643 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9644 /// shuffling each lane.
9646 /// This will only succeed when the result of fixing the 128-bit lanes results
9647 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9648 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9649 /// the lane crosses early and then use simpler shuffles within each lane.
9651 /// FIXME: It might be worthwhile at some point to support this without
9652 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9653 /// in x86 only floating point has interesting non-repeating shuffles, and even
9654 /// those are still *marginally* more expensive.
9655 static SDValue lowerVectorShuffleByMerging128BitLanes(
9656 SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9657 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9658 assert(!isSingleInputShuffleMask(Mask) &&
9659 "This is only useful with multiple inputs.");
9661 int Size = Mask.size();
9662 int LaneSize = 128 / VT.getScalarSizeInBits();
9663 int NumLanes = Size / LaneSize;
9664 assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9666 // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9667 // check whether the in-128-bit lane shuffles share a repeating pattern.
9668 SmallVector<int, 4> Lanes;
9669 Lanes.resize(NumLanes, -1);
9670 SmallVector<int, 4> InLaneMask;
9671 InLaneMask.resize(LaneSize, -1);
9672 for (int i = 0; i < Size; ++i) {
9676 int j = i / LaneSize;
9679 // First entry we've seen for this lane.
9680 Lanes[j] = Mask[i] / LaneSize;
9681 } else if (Lanes[j] != Mask[i] / LaneSize) {
9682 // This doesn't match the lane selected previously!
9686 // Check that within each lane we have a consistent shuffle mask.
9687 int k = i % LaneSize;
9688 if (InLaneMask[k] < 0) {
9689 InLaneMask[k] = Mask[i] % LaneSize;
9690 } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9691 // This doesn't fit a repeating in-lane mask.
9696 // First shuffle the lanes into place.
9697 MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9698 VT.getSizeInBits() / 64);
9699 SmallVector<int, 8> LaneMask;
9700 LaneMask.resize(NumLanes * 2, -1);
9701 for (int i = 0; i < NumLanes; ++i)
9702 if (Lanes[i] >= 0) {
9703 LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9704 LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9707 V1 = DAG.getBitcast(LaneVT, V1);
9708 V2 = DAG.getBitcast(LaneVT, V2);
9709 SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9711 // Cast it back to the type we actually want.
9712 LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
9714 // Now do a simple shuffle that isn't lane crossing.
9715 SmallVector<int, 8> NewMask;
9716 NewMask.resize(Size, -1);
9717 for (int i = 0; i < Size; ++i)
9719 NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9720 assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9721 "Must not introduce lane crosses at this point!");
9723 return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9726 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9729 /// This returns true if the elements from a particular input are already in the
9730 /// slot required by the given mask and require no permutation.
9731 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9732 assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9733 int Size = Mask.size();
9734 for (int i = 0; i < Size; ++i)
9735 if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9741 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
9742 ArrayRef<int> Mask, SDValue V1,
9743 SDValue V2, SelectionDAG &DAG) {
9745 // Mask for V8F64: 0/1, 8/9, 2/3, 10/11, 4/5, ..
9746 // Mask for V4F64; 0/1, 4/5, 2/3, 6/7..
9747 assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
9748 int NumElts = VT.getVectorNumElements();
9749 bool ShufpdMask = true;
9750 bool CommutableMask = true;
9751 unsigned Immediate = 0;
9752 for (int i = 0; i < NumElts; ++i) {
9755 int Val = (i & 6) + NumElts * (i & 1);
9756 int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
9757 if (Mask[i] < Val || Mask[i] > Val + 1)
9759 if (Mask[i] < CommutVal || Mask[i] > CommutVal + 1)
9760 CommutableMask = false;
9761 Immediate |= (Mask[i] % 2) << i;
9764 return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
9765 DAG.getConstant(Immediate, DL, MVT::i8));
9767 return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
9768 DAG.getConstant(Immediate, DL, MVT::i8));
9772 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9774 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9775 /// isn't available.
9776 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9777 const X86Subtarget *Subtarget,
9778 SelectionDAG &DAG) {
9780 assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9781 assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9782 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9783 ArrayRef<int> Mask = SVOp->getMask();
9784 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9786 SmallVector<int, 4> WidenedMask;
9787 if (canWidenShuffleElements(Mask, WidenedMask))
9788 return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9791 if (isSingleInputShuffleMask(Mask)) {
9792 // Check for being able to broadcast a single element.
9793 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9794 Mask, Subtarget, DAG))
9797 // Use low duplicate instructions for masks that match their pattern.
9798 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9799 return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9801 if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9802 // Non-half-crossing single input shuffles can be lowerid with an
9803 // interleaved permutation.
9804 unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9805 ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9806 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9807 DAG.getConstant(VPERMILPMask, DL, MVT::i8));
9810 // With AVX2 we have direct support for this permutation.
9811 if (Subtarget->hasAVX2())
9812 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9813 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9815 // Otherwise, fall back.
9816 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9820 // X86 has dedicated unpack instructions that can handle specific blend
9821 // operations: UNPCKH and UNPCKL.
9822 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9823 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9824 if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9825 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9826 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9827 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9828 if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9829 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9831 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9835 // Check if the blend happens to exactly fit that of SHUFPD.
9837 lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
9840 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9841 // shuffle. However, if we have AVX2 and either inputs are already in place,
9842 // we will be able to shuffle even across lanes the other input in a single
9843 // instruction so skip this pattern.
9844 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9845 isShuffleMaskInputInPlace(1, Mask))))
9846 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9847 DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9850 // If we have AVX2 then we always want to lower with a blend because an v4 we
9851 // can fully permute the elements.
9852 if (Subtarget->hasAVX2())
9853 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9856 // Otherwise fall back on generic lowering.
9857 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9860 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9862 /// This routine is only called when we have AVX2 and thus a reasonable
9863 /// instruction set for v4i64 shuffling..
9864 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9865 const X86Subtarget *Subtarget,
9866 SelectionDAG &DAG) {
9868 assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9869 assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9870 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9871 ArrayRef<int> Mask = SVOp->getMask();
9872 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9873 assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9875 SmallVector<int, 4> WidenedMask;
9876 if (canWidenShuffleElements(Mask, WidenedMask))
9877 return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9880 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9884 // Check for being able to broadcast a single element.
9885 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9886 Mask, Subtarget, DAG))
9889 // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9890 // use lower latency instructions that will operate on both 128-bit lanes.
9891 SmallVector<int, 2> RepeatedMask;
9892 if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9893 if (isSingleInputShuffleMask(Mask)) {
9894 int PSHUFDMask[] = {-1, -1, -1, -1};
9895 for (int i = 0; i < 2; ++i)
9896 if (RepeatedMask[i] >= 0) {
9897 PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9898 PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9900 return DAG.getBitcast(
9902 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9903 DAG.getBitcast(MVT::v8i32, V1),
9904 getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9908 // AVX2 provides a direct instruction for permuting a single input across
9910 if (isSingleInputShuffleMask(Mask))
9911 return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9912 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9914 // Try to use shift instructions.
9916 lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9919 // Use dedicated unpack instructions for masks that match their pattern.
9920 if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9921 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9922 if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9923 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9924 if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9925 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9926 if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9927 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9929 // Try to simplify this by merging 128-bit lanes to enable a lane-based
9930 // shuffle. However, if we have AVX2 and either inputs are already in place,
9931 // we will be able to shuffle even across lanes the other input in a single
9932 // instruction so skip this pattern.
9933 if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9934 isShuffleMaskInputInPlace(1, Mask))))
9935 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9936 DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9939 // Otherwise fall back on generic blend lowering.
9940 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9944 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9946 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9947 /// isn't available.
9948 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9949 const X86Subtarget *Subtarget,
9950 SelectionDAG &DAG) {
9952 assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9953 assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9954 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9955 ArrayRef<int> Mask = SVOp->getMask();
9956 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9958 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9962 // Check for being able to broadcast a single element.
9963 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
9964 Mask, Subtarget, DAG))
9967 // If the shuffle mask is repeated in each 128-bit lane, we have many more
9968 // options to efficiently lower the shuffle.
9969 SmallVector<int, 4> RepeatedMask;
9970 if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9971 assert(RepeatedMask.size() == 4 &&
9972 "Repeated masks must be half the mask width!");
9974 // Use even/odd duplicate instructions for masks that match their pattern.
9975 if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
9976 return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
9977 if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
9978 return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
9980 if (isSingleInputShuffleMask(Mask))
9981 return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
9982 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9984 // Use dedicated unpack instructions for masks that match their pattern.
9985 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9986 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
9987 if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9988 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
9989 if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9990 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
9991 if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9992 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
9994 // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
9995 // have already handled any direct blends. We also need to squash the
9996 // repeated mask into a simulated v4f32 mask.
9997 for (int i = 0; i < 4; ++i)
9998 if (RepeatedMask[i] >= 8)
9999 RepeatedMask[i] -= 4;
10000 return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10003 // If we have a single input shuffle with different shuffle patterns in the
10004 // two 128-bit lanes use the variable mask to VPERMILPS.
10005 if (isSingleInputShuffleMask(Mask)) {
10006 SDValue VPermMask[8];
10007 for (int i = 0; i < 8; ++i)
10008 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10009 : DAG.getConstant(Mask[i], DL, MVT::i32);
10010 if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10011 return DAG.getNode(
10012 X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10013 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10015 if (Subtarget->hasAVX2())
10016 return DAG.getNode(
10017 X86ISD::VPERMV, DL, MVT::v8f32,
10018 DAG.getBitcast(MVT::v8f32, DAG.getNode(ISD::BUILD_VECTOR, DL,
10019 MVT::v8i32, VPermMask)),
10022 // Otherwise, fall back.
10023 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10027 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10029 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10030 DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10033 // If we have AVX2 then we always want to lower with a blend because at v8 we
10034 // can fully permute the elements.
10035 if (Subtarget->hasAVX2())
10036 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10039 // Otherwise fall back on generic lowering.
10040 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10043 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10045 /// This routine is only called when we have AVX2 and thus a reasonable
10046 /// instruction set for v8i32 shuffling..
10047 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10048 const X86Subtarget *Subtarget,
10049 SelectionDAG &DAG) {
10051 assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10052 assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10053 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10054 ArrayRef<int> Mask = SVOp->getMask();
10055 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10056 assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10058 // Whenever we can lower this as a zext, that instruction is strictly faster
10059 // than any alternative. It also allows us to fold memory operands into the
10060 // shuffle in many cases.
10061 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10062 Mask, Subtarget, DAG))
10065 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10069 // Check for being able to broadcast a single element.
10070 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10071 Mask, Subtarget, DAG))
10074 // If the shuffle mask is repeated in each 128-bit lane we can use more
10075 // efficient instructions that mirror the shuffles across the two 128-bit
10077 SmallVector<int, 4> RepeatedMask;
10078 if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10079 assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10080 if (isSingleInputShuffleMask(Mask))
10081 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10082 getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10084 // Use dedicated unpack instructions for masks that match their pattern.
10085 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10086 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
10087 if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10088 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
10089 if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10090 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
10091 if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10092 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
10095 // Try to use shift instructions.
10096 if (SDValue Shift =
10097 lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10100 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10101 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10104 // If the shuffle patterns aren't repeated but it is a single input, directly
10105 // generate a cross-lane VPERMD instruction.
10106 if (isSingleInputShuffleMask(Mask)) {
10107 SDValue VPermMask[8];
10108 for (int i = 0; i < 8; ++i)
10109 VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10110 : DAG.getConstant(Mask[i], DL, MVT::i32);
10111 return DAG.getNode(
10112 X86ISD::VPERMV, DL, MVT::v8i32,
10113 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10116 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10118 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10119 DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10122 // Otherwise fall back on generic blend lowering.
10123 return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10127 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10129 /// This routine is only called when we have AVX2 and thus a reasonable
10130 /// instruction set for v16i16 shuffling..
10131 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10132 const X86Subtarget *Subtarget,
10133 SelectionDAG &DAG) {
10135 assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10136 assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10137 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10138 ArrayRef<int> Mask = SVOp->getMask();
10139 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10140 assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10142 // Whenever we can lower this as a zext, that instruction is strictly faster
10143 // than any alternative. It also allows us to fold memory operands into the
10144 // shuffle in many cases.
10145 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10146 Mask, Subtarget, DAG))
10149 // Check for being able to broadcast a single element.
10150 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10151 Mask, Subtarget, DAG))
10154 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10158 // Use dedicated unpack instructions for masks that match their pattern.
10159 if (isShuffleEquivalent(V1, V2, Mask,
10160 {// First 128-bit lane:
10161 0, 16, 1, 17, 2, 18, 3, 19,
10162 // Second 128-bit lane:
10163 8, 24, 9, 25, 10, 26, 11, 27}))
10164 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
10165 if (isShuffleEquivalent(V1, V2, Mask,
10166 {// First 128-bit lane:
10167 4, 20, 5, 21, 6, 22, 7, 23,
10168 // Second 128-bit lane:
10169 12, 28, 13, 29, 14, 30, 15, 31}))
10170 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
10172 // Try to use shift instructions.
10173 if (SDValue Shift =
10174 lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10177 // Try to use byte rotation instructions.
10178 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10179 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10182 if (isSingleInputShuffleMask(Mask)) {
10183 // There are no generalized cross-lane shuffle operations available on i16
10185 if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10186 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10189 SmallVector<int, 8> RepeatedMask;
10190 if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10191 // As this is a single-input shuffle, the repeated mask should be
10192 // a strictly valid v8i16 mask that we can pass through to the v8i16
10193 // lowering to handle even the v16 case.
10194 return lowerV8I16GeneralSingleInputVectorShuffle(
10195 DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10198 SDValue PSHUFBMask[32];
10199 for (int i = 0; i < 16; ++i) {
10200 if (Mask[i] == -1) {
10201 PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10205 int M = i < 8 ? Mask[i] : Mask[i] - 8;
10206 assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10207 PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10208 PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10210 return DAG.getBitcast(MVT::v16i16,
10211 DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10212 DAG.getBitcast(MVT::v32i8, V1),
10213 DAG.getNode(ISD::BUILD_VECTOR, DL,
10214 MVT::v32i8, PSHUFBMask)));
10217 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10219 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10220 DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10223 // Otherwise fall back on generic lowering.
10224 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10227 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10229 /// This routine is only called when we have AVX2 and thus a reasonable
10230 /// instruction set for v32i8 shuffling..
10231 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10232 const X86Subtarget *Subtarget,
10233 SelectionDAG &DAG) {
10235 assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10236 assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10237 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10238 ArrayRef<int> Mask = SVOp->getMask();
10239 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10240 assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10242 // Whenever we can lower this as a zext, that instruction is strictly faster
10243 // than any alternative. It also allows us to fold memory operands into the
10244 // shuffle in many cases.
10245 if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10246 Mask, Subtarget, DAG))
10249 // Check for being able to broadcast a single element.
10250 if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10251 Mask, Subtarget, DAG))
10254 if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10258 // Use dedicated unpack instructions for masks that match their pattern.
10259 // Note that these are repeated 128-bit lane unpacks, not unpacks across all
10261 if (isShuffleEquivalent(
10263 {// First 128-bit lane:
10264 0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
10265 // Second 128-bit lane:
10266 16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
10267 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
10268 if (isShuffleEquivalent(
10270 {// First 128-bit lane:
10271 8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
10272 // Second 128-bit lane:
10273 24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
10274 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
10276 // Try to use shift instructions.
10277 if (SDValue Shift =
10278 lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10281 // Try to use byte rotation instructions.
10282 if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10283 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10286 if (isSingleInputShuffleMask(Mask)) {
10287 // There are no generalized cross-lane shuffle operations available on i8
10289 if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10290 return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10293 SDValue PSHUFBMask[32];
10294 for (int i = 0; i < 32; ++i)
10297 ? DAG.getUNDEF(MVT::i8)
10298 : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10301 return DAG.getNode(
10302 X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10303 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10306 // Try to simplify this by merging 128-bit lanes to enable a lane-based
10308 if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10309 DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10312 // Otherwise fall back on generic lowering.
10313 return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10316 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10318 /// This routine either breaks down the specific type of a 256-bit x86 vector
10319 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10320 /// together based on the available instructions.
10321 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10322 MVT VT, const X86Subtarget *Subtarget,
10323 SelectionDAG &DAG) {
10325 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10326 ArrayRef<int> Mask = SVOp->getMask();
10328 // If we have a single input to the zero element, insert that into V1 if we
10329 // can do so cheaply.
10330 int NumElts = VT.getVectorNumElements();
10331 int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10332 return M >= NumElts;
10335 if (NumV2Elements == 1 && Mask[0] >= NumElts)
10336 if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10337 DL, VT, V1, V2, Mask, Subtarget, DAG))
10340 // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
10341 // check for those subtargets here and avoid much of the subtarget querying in
10342 // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
10343 // ability to manipulate a 256-bit vector with integer types. Since we'll use
10344 // floating point types there eventually, just immediately cast everything to
10345 // a float and operate entirely in that domain.
10346 if (VT.isInteger() && !Subtarget->hasAVX2()) {
10347 int ElementBits = VT.getScalarSizeInBits();
10348 if (ElementBits < 32)
10349 // No floating point type available, decompose into 128-bit vectors.
10350 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10352 MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10353 VT.getVectorNumElements());
10354 V1 = DAG.getBitcast(FpVT, V1);
10355 V2 = DAG.getBitcast(FpVT, V2);
10356 return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10359 switch (VT.SimpleTy) {
10361 return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10363 return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10365 return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10367 return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10369 return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10371 return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10374 llvm_unreachable("Not a valid 256-bit x86 vector type!");
10378 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10379 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10380 const X86Subtarget *Subtarget,
10381 SelectionDAG &DAG) {
10383 assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10384 assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10385 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10386 ArrayRef<int> Mask = SVOp->getMask();
10387 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10389 // X86 has dedicated unpack instructions that can handle specific blend
10390 // operations: UNPCKH and UNPCKL.
10391 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10392 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
10393 if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10394 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
10396 // FIXME: Implement direct support for this type!
10397 return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10400 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10401 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10402 const X86Subtarget *Subtarget,
10403 SelectionDAG &DAG) {
10405 assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10406 assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10407 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10408 ArrayRef<int> Mask = SVOp->getMask();
10409 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10411 // Use dedicated unpack instructions for masks that match their pattern.
10412 if (isShuffleEquivalent(V1, V2, Mask,
10413 {// First 128-bit lane.
10414 0, 16, 1, 17, 4, 20, 5, 21,
10415 // Second 128-bit lane.
10416 8, 24, 9, 25, 12, 28, 13, 29}))
10417 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
10418 if (isShuffleEquivalent(V1, V2, Mask,
10419 {// First 128-bit lane.
10420 2, 18, 3, 19, 6, 22, 7, 23,
10421 // Second 128-bit lane.
10422 10, 26, 11, 27, 14, 30, 15, 31}))
10423 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
10425 // FIXME: Implement direct support for this type!
10426 return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10429 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10430 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10431 const X86Subtarget *Subtarget,
10432 SelectionDAG &DAG) {
10434 assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10435 assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10436 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10437 ArrayRef<int> Mask = SVOp->getMask();
10438 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10440 // X86 has dedicated unpack instructions that can handle specific blend
10441 // operations: UNPCKH and UNPCKL.
10442 if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10443 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
10444 if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10445 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
10447 // FIXME: Implement direct support for this type!
10448 return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10451 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10452 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10453 const X86Subtarget *Subtarget,
10454 SelectionDAG &DAG) {
10456 assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10457 assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10458 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10459 ArrayRef<int> Mask = SVOp->getMask();
10460 assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10462 // Use dedicated unpack instructions for masks that match their pattern.
10463 if (isShuffleEquivalent(V1, V2, Mask,
10464 {// First 128-bit lane.
10465 0, 16, 1, 17, 4, 20, 5, 21,
10466 // Second 128-bit lane.
10467 8, 24, 9, 25, 12, 28, 13, 29}))
10468 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
10469 if (isShuffleEquivalent(V1, V2, Mask,
10470 {// First 128-bit lane.
10471 2, 18, 3, 19, 6, 22, 7, 23,
10472 // Second 128-bit lane.
10473 10, 26, 11, 27, 14, 30, 15, 31}))
10474 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
10476 // FIXME: Implement direct support for this type!
10477 return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10480 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10481 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10482 const X86Subtarget *Subtarget,
10483 SelectionDAG &DAG) {
10485 assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10486 assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10487 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10488 ArrayRef<int> Mask = SVOp->getMask();
10489 assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10490 assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10492 // FIXME: Implement direct support for this type!
10493 return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10496 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10497 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10498 const X86Subtarget *Subtarget,
10499 SelectionDAG &DAG) {
10501 assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10502 assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10503 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10504 ArrayRef<int> Mask = SVOp->getMask();
10505 assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10506 assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10508 // FIXME: Implement direct support for this type!
10509 return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10512 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10514 /// This routine either breaks down the specific type of a 512-bit x86 vector
10515 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10516 /// together based on the available instructions.
10517 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10518 MVT VT, const X86Subtarget *Subtarget,
10519 SelectionDAG &DAG) {
10521 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10522 ArrayRef<int> Mask = SVOp->getMask();
10523 assert(Subtarget->hasAVX512() &&
10524 "Cannot lower 512-bit vectors w/ basic ISA!");
10526 // Check for being able to broadcast a single element.
10527 if (SDValue Broadcast =
10528 lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10531 // Dispatch to each element type for lowering. If we don't have supprot for
10532 // specific element type shuffles at 512 bits, immediately split them and
10533 // lower them. Each lowering routine of a given type is allowed to assume that
10534 // the requisite ISA extensions for that element type are available.
10535 switch (VT.SimpleTy) {
10537 return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10539 return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10541 return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10543 return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10545 if (Subtarget->hasBWI())
10546 return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10549 if (Subtarget->hasBWI())
10550 return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10554 llvm_unreachable("Not a valid 512-bit x86 vector type!");
10557 // Otherwise fall back on splitting.
10558 return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10561 /// \brief Top-level lowering for x86 vector shuffles.
10563 /// This handles decomposition, canonicalization, and lowering of all x86
10564 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10565 /// above in helper routines. The canonicalization attempts to widen shuffles
10566 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10567 /// s.t. only one of the two inputs needs to be tested, etc.
10568 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10569 SelectionDAG &DAG) {
10570 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10571 ArrayRef<int> Mask = SVOp->getMask();
10572 SDValue V1 = Op.getOperand(0);
10573 SDValue V2 = Op.getOperand(1);
10574 MVT VT = Op.getSimpleValueType();
10575 int NumElements = VT.getVectorNumElements();
10578 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10580 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10581 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10582 if (V1IsUndef && V2IsUndef)
10583 return DAG.getUNDEF(VT);
10585 // When we create a shuffle node we put the UNDEF node to second operand,
10586 // but in some cases the first operand may be transformed to UNDEF.
10587 // In this case we should just commute the node.
10589 return DAG.getCommutedVectorShuffle(*SVOp);
10591 // Check for non-undef masks pointing at an undef vector and make the masks
10592 // undef as well. This makes it easier to match the shuffle based solely on
10596 if (M >= NumElements) {
10597 SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10598 for (int &M : NewMask)
10599 if (M >= NumElements)
10601 return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10604 // We actually see shuffles that are entirely re-arrangements of a set of
10605 // zero inputs. This mostly happens while decomposing complex shuffles into
10606 // simple ones. Directly lower these as a buildvector of zeros.
10607 SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10608 if (Zeroable.all())
10609 return getZeroVector(VT, Subtarget, DAG, dl);
10611 // Try to collapse shuffles into using a vector type with fewer elements but
10612 // wider element types. We cap this to not form integers or floating point
10613 // elements wider than 64 bits, but it might be interesting to form i128
10614 // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10615 SmallVector<int, 16> WidenedMask;
10616 if (VT.getScalarSizeInBits() < 64 &&
10617 canWidenShuffleElements(Mask, WidenedMask)) {
10618 MVT NewEltVT = VT.isFloatingPoint()
10619 ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10620 : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10621 MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10622 // Make sure that the new vector type is legal. For example, v2f64 isn't
10624 if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10625 V1 = DAG.getBitcast(NewVT, V1);
10626 V2 = DAG.getBitcast(NewVT, V2);
10627 return DAG.getBitcast(
10628 VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10632 int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10633 for (int M : SVOp->getMask())
10635 ++NumUndefElements;
10636 else if (M < NumElements)
10641 // Commute the shuffle as needed such that more elements come from V1 than
10642 // V2. This allows us to match the shuffle pattern strictly on how many
10643 // elements come from V1 without handling the symmetric cases.
10644 if (NumV2Elements > NumV1Elements)
10645 return DAG.getCommutedVectorShuffle(*SVOp);
10647 // When the number of V1 and V2 elements are the same, try to minimize the
10648 // number of uses of V2 in the low half of the vector. When that is tied,
10649 // ensure that the sum of indices for V1 is equal to or lower than the sum
10650 // indices for V2. When those are equal, try to ensure that the number of odd
10651 // indices for V1 is lower than the number of odd indices for V2.
10652 if (NumV1Elements == NumV2Elements) {
10653 int LowV1Elements = 0, LowV2Elements = 0;
10654 for (int M : SVOp->getMask().slice(0, NumElements / 2))
10655 if (M >= NumElements)
10659 if (LowV2Elements > LowV1Elements) {
10660 return DAG.getCommutedVectorShuffle(*SVOp);
10661 } else if (LowV2Elements == LowV1Elements) {
10662 int SumV1Indices = 0, SumV2Indices = 0;
10663 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10664 if (SVOp->getMask()[i] >= NumElements)
10666 else if (SVOp->getMask()[i] >= 0)
10668 if (SumV2Indices < SumV1Indices) {
10669 return DAG.getCommutedVectorShuffle(*SVOp);
10670 } else if (SumV2Indices == SumV1Indices) {
10671 int NumV1OddIndices = 0, NumV2OddIndices = 0;
10672 for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10673 if (SVOp->getMask()[i] >= NumElements)
10674 NumV2OddIndices += i % 2;
10675 else if (SVOp->getMask()[i] >= 0)
10676 NumV1OddIndices += i % 2;
10677 if (NumV2OddIndices < NumV1OddIndices)
10678 return DAG.getCommutedVectorShuffle(*SVOp);
10683 // For each vector width, delegate to a specialized lowering routine.
10684 if (VT.getSizeInBits() == 128)
10685 return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10687 if (VT.getSizeInBits() == 256)
10688 return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10690 // Force AVX-512 vectors to be scalarized for now.
10691 // FIXME: Implement AVX-512 support!
10692 if (VT.getSizeInBits() == 512)
10693 return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10695 llvm_unreachable("Unimplemented!");
10698 // This function assumes its argument is a BUILD_VECTOR of constants or
10699 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10701 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10702 unsigned &MaskValue) {
10704 unsigned NumElems = BuildVector->getNumOperands();
10705 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10706 unsigned NumLanes = (NumElems - 1) / 8 + 1;
10707 unsigned NumElemsInLane = NumElems / NumLanes;
10709 // Blend for v16i16 should be symetric for the both lanes.
10710 for (unsigned i = 0; i < NumElemsInLane; ++i) {
10711 SDValue EltCond = BuildVector->getOperand(i);
10712 SDValue SndLaneEltCond =
10713 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10715 int Lane1Cond = -1, Lane2Cond = -1;
10716 if (isa<ConstantSDNode>(EltCond))
10717 Lane1Cond = !isZero(EltCond);
10718 if (isa<ConstantSDNode>(SndLaneEltCond))
10719 Lane2Cond = !isZero(SndLaneEltCond);
10721 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10722 // Lane1Cond != 0, means we want the first argument.
10723 // Lane1Cond == 0, means we want the second argument.
10724 // The encoding of this argument is 0 for the first argument, 1
10725 // for the second. Therefore, invert the condition.
10726 MaskValue |= !Lane1Cond << i;
10727 else if (Lane1Cond < 0)
10728 MaskValue |= !Lane2Cond << i;
10735 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10736 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10737 const X86Subtarget *Subtarget,
10738 SelectionDAG &DAG) {
10739 SDValue Cond = Op.getOperand(0);
10740 SDValue LHS = Op.getOperand(1);
10741 SDValue RHS = Op.getOperand(2);
10743 MVT VT = Op.getSimpleValueType();
10745 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10747 auto *CondBV = cast<BuildVectorSDNode>(Cond);
10749 // Only non-legal VSELECTs reach this lowering, convert those into generic
10750 // shuffles and re-use the shuffle lowering path for blends.
10751 SmallVector<int, 32> Mask;
10752 for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10753 SDValue CondElt = CondBV->getOperand(i);
10755 isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10757 return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10760 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10761 // A vselect where all conditions and data are constants can be optimized into
10762 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10763 if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10764 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10765 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10768 // Try to lower this to a blend-style vector shuffle. This can handle all
10769 // constant condition cases.
10770 if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10773 // Variable blends are only legal from SSE4.1 onward.
10774 if (!Subtarget->hasSSE41())
10777 // Only some types will be legal on some subtargets. If we can emit a legal
10778 // VSELECT-matching blend, return Op, and but if we need to expand, return
10780 switch (Op.getSimpleValueType().SimpleTy) {
10782 // Most of the vector types have blends past SSE4.1.
10786 // The byte blends for AVX vectors were introduced only in AVX2.
10787 if (Subtarget->hasAVX2())
10794 // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10795 if (Subtarget->hasBWI() && Subtarget->hasVLX())
10798 // FIXME: We should custom lower this by fixing the condition and using i8
10804 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10805 MVT VT = Op.getSimpleValueType();
10808 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10811 if (VT.getSizeInBits() == 8) {
10812 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10813 Op.getOperand(0), Op.getOperand(1));
10814 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10815 DAG.getValueType(VT));
10816 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10819 if (VT.getSizeInBits() == 16) {
10820 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10821 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10823 return DAG.getNode(
10824 ISD::TRUNCATE, dl, MVT::i16,
10825 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10826 DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10827 Op.getOperand(1)));
10828 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10829 Op.getOperand(0), Op.getOperand(1));
10830 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10831 DAG.getValueType(VT));
10832 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10835 if (VT == MVT::f32) {
10836 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10837 // the result back to FR32 register. It's only worth matching if the
10838 // result has a single use which is a store or a bitcast to i32. And in
10839 // the case of a store, it's not worth it if the index is a constant 0,
10840 // because a MOVSSmr can be used instead, which is smaller and faster.
10841 if (!Op.hasOneUse())
10843 SDNode *User = *Op.getNode()->use_begin();
10844 if ((User->getOpcode() != ISD::STORE ||
10845 (isa<ConstantSDNode>(Op.getOperand(1)) &&
10846 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10847 (User->getOpcode() != ISD::BITCAST ||
10848 User->getValueType(0) != MVT::i32))
10850 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10851 DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10853 return DAG.getBitcast(MVT::f32, Extract);
10856 if (VT == MVT::i32 || VT == MVT::i64) {
10857 // ExtractPS/pextrq works with constant index.
10858 if (isa<ConstantSDNode>(Op.getOperand(1)))
10864 /// Extract one bit from mask vector, like v16i1 or v8i1.
10865 /// AVX-512 feature.
10867 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10868 SDValue Vec = Op.getOperand(0);
10870 MVT VecVT = Vec.getSimpleValueType();
10871 SDValue Idx = Op.getOperand(1);
10872 MVT EltVT = Op.getSimpleValueType();
10874 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10875 assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10876 "Unexpected vector type in ExtractBitFromMaskVector");
10878 // variable index can't be handled in mask registers,
10879 // extend vector to VR512
10880 if (!isa<ConstantSDNode>(Idx)) {
10881 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
10882 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10883 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10884 ExtVT.getVectorElementType(), Ext, Idx);
10885 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10888 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10889 const TargetRegisterClass* rc = getRegClassFor(VecVT);
10890 if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10891 rc = getRegClassFor(MVT::v16i1);
10892 unsigned MaxSift = rc->getSize()*8 - 1;
10893 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10894 DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10895 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10896 DAG.getConstant(MaxSift, dl, MVT::i8));
10897 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10898 DAG.getIntPtrConstant(0, dl));
10902 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10903 SelectionDAG &DAG) const {
10905 SDValue Vec = Op.getOperand(0);
10906 MVT VecVT = Vec.getSimpleValueType();
10907 SDValue Idx = Op.getOperand(1);
10909 if (Op.getSimpleValueType() == MVT::i1)
10910 return ExtractBitFromMaskVector(Op, DAG);
10912 if (!isa<ConstantSDNode>(Idx)) {
10913 if (VecVT.is512BitVector() ||
10914 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10915 VecVT.getVectorElementType().getSizeInBits() == 32)) {
10918 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10919 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10920 MaskEltVT.getSizeInBits());
10922 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10923 auto PtrVT = getPointerTy(DAG.getDataLayout());
10924 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10925 getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
10926 DAG.getConstant(0, dl, PtrVT));
10927 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10928 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
10929 DAG.getConstant(0, dl, PtrVT));
10934 // If this is a 256-bit vector result, first extract the 128-bit vector and
10935 // then extract the element from the 128-bit vector.
10936 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10938 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10939 // Get the 128-bit vector.
10940 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10941 MVT EltVT = VecVT.getVectorElementType();
10943 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10945 //if (IdxVal >= NumElems/2)
10946 // IdxVal -= NumElems/2;
10947 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10948 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10949 DAG.getConstant(IdxVal, dl, MVT::i32));
10952 assert(VecVT.is128BitVector() && "Unexpected vector length");
10954 if (Subtarget->hasSSE41())
10955 if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
10958 MVT VT = Op.getSimpleValueType();
10959 // TODO: handle v16i8.
10960 if (VT.getSizeInBits() == 16) {
10961 SDValue Vec = Op.getOperand(0);
10962 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10964 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10965 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10966 DAG.getBitcast(MVT::v4i32, Vec),
10967 Op.getOperand(1)));
10968 // Transform it so it match pextrw which produces a 32-bit result.
10969 MVT EltVT = MVT::i32;
10970 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10971 Op.getOperand(0), Op.getOperand(1));
10972 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10973 DAG.getValueType(VT));
10974 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10977 if (VT.getSizeInBits() == 32) {
10978 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10982 // SHUFPS the element to the lowest double word, then movss.
10983 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10984 MVT VVT = Op.getOperand(0).getSimpleValueType();
10985 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10986 DAG.getUNDEF(VVT), Mask);
10987 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10988 DAG.getIntPtrConstant(0, dl));
10991 if (VT.getSizeInBits() == 64) {
10992 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10993 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10994 // to match extract_elt for f64.
10995 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10999 // UNPCKHPD the element to the lowest double word, then movsd.
11000 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
11001 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
11002 int Mask[2] = { 1, -1 };
11003 MVT VVT = Op.getOperand(0).getSimpleValueType();
11004 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11005 DAG.getUNDEF(VVT), Mask);
11006 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11007 DAG.getIntPtrConstant(0, dl));
11013 /// Insert one bit to mask vector, like v16i1 or v8i1.
11014 /// AVX-512 feature.
11016 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11018 SDValue Vec = Op.getOperand(0);
11019 SDValue Elt = Op.getOperand(1);
11020 SDValue Idx = Op.getOperand(2);
11021 MVT VecVT = Vec.getSimpleValueType();
11023 if (!isa<ConstantSDNode>(Idx)) {
11024 // Non constant index. Extend source and destination,
11025 // insert element and then truncate the result.
11026 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
11027 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
11028 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11029 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11030 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11031 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11034 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11035 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11037 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11038 DAG.getConstant(IdxVal, dl, MVT::i8));
11039 if (Vec.getOpcode() == ISD::UNDEF)
11041 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11044 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11045 SelectionDAG &DAG) const {
11046 MVT VT = Op.getSimpleValueType();
11047 MVT EltVT = VT.getVectorElementType();
11049 if (EltVT == MVT::i1)
11050 return InsertBitToMaskVector(Op, DAG);
11053 SDValue N0 = Op.getOperand(0);
11054 SDValue N1 = Op.getOperand(1);
11055 SDValue N2 = Op.getOperand(2);
11056 if (!isa<ConstantSDNode>(N2))
11058 auto *N2C = cast<ConstantSDNode>(N2);
11059 unsigned IdxVal = N2C->getZExtValue();
11061 // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11062 // into that, and then insert the subvector back into the result.
11063 if (VT.is256BitVector() || VT.is512BitVector()) {
11064 // With a 256-bit vector, we can insert into the zero element efficiently
11065 // using a blend if we have AVX or AVX2 and the right data type.
11066 if (VT.is256BitVector() && IdxVal == 0) {
11067 // TODO: It is worthwhile to cast integer to floating point and back
11068 // and incur a domain crossing penalty if that's what we'll end up
11069 // doing anyway after extracting to a 128-bit vector.
11070 if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11071 (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11072 SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11073 N2 = DAG.getIntPtrConstant(1, dl);
11074 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11078 // Get the desired 128-bit vector chunk.
11079 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11081 // Insert the element into the desired chunk.
11082 unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11083 unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
11085 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11086 DAG.getConstant(IdxIn128, dl, MVT::i32));
11088 // Insert the changed part back into the bigger vector
11089 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11091 assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11093 if (Subtarget->hasSSE41()) {
11094 if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11096 if (VT == MVT::v8i16) {
11097 Opc = X86ISD::PINSRW;
11099 assert(VT == MVT::v16i8);
11100 Opc = X86ISD::PINSRB;
11103 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11105 if (N1.getValueType() != MVT::i32)
11106 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11107 if (N2.getValueType() != MVT::i32)
11108 N2 = DAG.getIntPtrConstant(IdxVal, dl);
11109 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11112 if (EltVT == MVT::f32) {
11113 // Bits [7:6] of the constant are the source select. This will always be
11114 // zero here. The DAG Combiner may combine an extract_elt index into
11115 // these bits. For example (insert (extract, 3), 2) could be matched by
11116 // putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11117 // Bits [5:4] of the constant are the destination select. This is the
11118 // value of the incoming immediate.
11119 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11120 // combine either bitwise AND or insert of float 0.0 to set these bits.
11122 bool MinSize = DAG.getMachineFunction().getFunction()->optForMinSize();
11123 if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11124 // If this is an insertion of 32-bits into the low 32-bits of
11125 // a vector, we prefer to generate a blend with immediate rather
11126 // than an insertps. Blends are simpler operations in hardware and so
11127 // will always have equal or better performance than insertps.
11128 // But if optimizing for size and there's a load folding opportunity,
11129 // generate insertps because blendps does not have a 32-bit memory
11131 N2 = DAG.getIntPtrConstant(1, dl);
11132 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11133 return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11135 N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11136 // Create this as a scalar to vector..
11137 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11138 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11141 if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11142 // PINSR* works with constant index.
11147 if (EltVT == MVT::i8)
11150 if (EltVT.getSizeInBits() == 16) {
11151 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11152 // as its second argument.
11153 if (N1.getValueType() != MVT::i32)
11154 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11155 if (N2.getValueType() != MVT::i32)
11156 N2 = DAG.getIntPtrConstant(IdxVal, dl);
11157 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11162 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11164 MVT OpVT = Op.getSimpleValueType();
11166 // If this is a 256-bit vector result, first insert into a 128-bit
11167 // vector and then insert into the 256-bit vector.
11168 if (!OpVT.is128BitVector()) {
11169 // Insert into a 128-bit vector.
11170 unsigned SizeFactor = OpVT.getSizeInBits()/128;
11171 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11172 OpVT.getVectorNumElements() / SizeFactor);
11174 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11176 // Insert the 128-bit vector.
11177 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11180 if (OpVT == MVT::v1i64 &&
11181 Op.getOperand(0).getValueType() == MVT::i64)
11182 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11184 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11185 assert(OpVT.is128BitVector() && "Expected an SSE type!");
11186 return DAG.getBitcast(
11187 OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11190 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
11191 // a simple subregister reference or explicit instructions to grab
11192 // upper bits of a vector.
11193 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11194 SelectionDAG &DAG) {
11196 SDValue In = Op.getOperand(0);
11197 SDValue Idx = Op.getOperand(1);
11198 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11199 MVT ResVT = Op.getSimpleValueType();
11200 MVT InVT = In.getSimpleValueType();
11202 if (Subtarget->hasFp256()) {
11203 if (ResVT.is128BitVector() &&
11204 (InVT.is256BitVector() || InVT.is512BitVector()) &&
11205 isa<ConstantSDNode>(Idx)) {
11206 return Extract128BitVector(In, IdxVal, DAG, dl);
11208 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
11209 isa<ConstantSDNode>(Idx)) {
11210 return Extract256BitVector(In, IdxVal, DAG, dl);
11216 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
11217 // simple superregister reference or explicit instructions to insert
11218 // the upper bits of a vector.
11219 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11220 SelectionDAG &DAG) {
11221 if (!Subtarget->hasAVX())
11225 SDValue Vec = Op.getOperand(0);
11226 SDValue SubVec = Op.getOperand(1);
11227 SDValue Idx = Op.getOperand(2);
11229 if (!isa<ConstantSDNode>(Idx))
11232 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11233 MVT OpVT = Op.getSimpleValueType();
11234 MVT SubVecVT = SubVec.getSimpleValueType();
11236 // Fold two 16-byte subvector loads into one 32-byte load:
11237 // (insert_subvector (insert_subvector undef, (load addr), 0),
11238 // (load addr + 16), Elts/2)
11240 if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
11241 Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
11242 OpVT.is256BitVector() && SubVecVT.is128BitVector() &&
11243 !Subtarget->isUnalignedMem32Slow()) {
11244 SDValue SubVec2 = Vec.getOperand(1);
11245 if (auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2))) {
11246 if (Idx2->getZExtValue() == 0) {
11247 SDValue Ops[] = { SubVec2, SubVec };
11248 if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
11254 if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
11255 SubVecVT.is128BitVector())
11256 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11258 if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
11259 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11261 if (OpVT.getVectorElementType() == MVT::i1) {
11262 if (IdxVal == 0 && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
11264 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
11265 SDValue Undef = DAG.getUNDEF(OpVT);
11266 unsigned NumElems = OpVT.getVectorNumElements();
11267 SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
11269 if (IdxVal == OpVT.getVectorNumElements() / 2) {
11270 // Zero upper bits of the Vec
11271 Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11272 Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11274 SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11276 Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11277 return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11280 SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11282 // Zero upper bits of the Vec2
11283 Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11284 Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
11285 // Zero lower bits of the Vec
11286 Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11287 Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11288 // Merge them together
11289 return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11295 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11296 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11297 // one of the above mentioned nodes. It has to be wrapped because otherwise
11298 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11299 // be used to form addressing mode. These wrapped nodes will be selected
11302 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11303 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11305 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11306 // global base reg.
11307 unsigned char OpFlag = 0;
11308 unsigned WrapperKind = X86ISD::Wrapper;
11309 CodeModel::Model M = DAG.getTarget().getCodeModel();
11311 if (Subtarget->isPICStyleRIPRel() &&
11312 (M == CodeModel::Small || M == CodeModel::Kernel))
11313 WrapperKind = X86ISD::WrapperRIP;
11314 else if (Subtarget->isPICStyleGOT())
11315 OpFlag = X86II::MO_GOTOFF;
11316 else if (Subtarget->isPICStyleStubPIC())
11317 OpFlag = X86II::MO_PIC_BASE_OFFSET;
11319 auto PtrVT = getPointerTy(DAG.getDataLayout());
11320 SDValue Result = DAG.getTargetConstantPool(
11321 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
11323 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11324 // With PIC, the address is actually $g + Offset.
11327 DAG.getNode(ISD::ADD, DL, PtrVT,
11328 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11334 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11335 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11337 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11338 // global base reg.
11339 unsigned char OpFlag = 0;
11340 unsigned WrapperKind = X86ISD::Wrapper;
11341 CodeModel::Model M = DAG.getTarget().getCodeModel();
11343 if (Subtarget->isPICStyleRIPRel() &&
11344 (M == CodeModel::Small || M == CodeModel::Kernel))
11345 WrapperKind = X86ISD::WrapperRIP;
11346 else if (Subtarget->isPICStyleGOT())
11347 OpFlag = X86II::MO_GOTOFF;
11348 else if (Subtarget->isPICStyleStubPIC())
11349 OpFlag = X86II::MO_PIC_BASE_OFFSET;
11351 auto PtrVT = getPointerTy(DAG.getDataLayout());
11352 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
11354 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11356 // With PIC, the address is actually $g + Offset.
11359 DAG.getNode(ISD::ADD, DL, PtrVT,
11360 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11366 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11367 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11369 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11370 // global base reg.
11371 unsigned char OpFlag = 0;
11372 unsigned WrapperKind = X86ISD::Wrapper;
11373 CodeModel::Model M = DAG.getTarget().getCodeModel();
11375 if (Subtarget->isPICStyleRIPRel() &&
11376 (M == CodeModel::Small || M == CodeModel::Kernel)) {
11377 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11378 OpFlag = X86II::MO_GOTPCREL;
11379 WrapperKind = X86ISD::WrapperRIP;
11380 } else if (Subtarget->isPICStyleGOT()) {
11381 OpFlag = X86II::MO_GOT;
11382 } else if (Subtarget->isPICStyleStubPIC()) {
11383 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11384 } else if (Subtarget->isPICStyleStubNoDynamic()) {
11385 OpFlag = X86II::MO_DARWIN_NONLAZY;
11388 auto PtrVT = getPointerTy(DAG.getDataLayout());
11389 SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
11392 Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11394 // With PIC, the address is actually $g + Offset.
11395 if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11396 !Subtarget->is64Bit()) {
11398 DAG.getNode(ISD::ADD, DL, PtrVT,
11399 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11402 // For symbols that require a load from a stub to get the address, emit the
11404 if (isGlobalStubReference(OpFlag))
11405 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
11406 MachinePointerInfo::getGOT(), false, false, false, 0);
11412 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11413 // Create the TargetBlockAddressAddress node.
11414 unsigned char OpFlags =
11415 Subtarget->ClassifyBlockAddressReference();
11416 CodeModel::Model M = DAG.getTarget().getCodeModel();
11417 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11418 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11420 auto PtrVT = getPointerTy(DAG.getDataLayout());
11421 SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
11423 if (Subtarget->isPICStyleRIPRel() &&
11424 (M == CodeModel::Small || M == CodeModel::Kernel))
11425 Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11427 Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11429 // With PIC, the address is actually $g + Offset.
11430 if (isGlobalRelativeToPICBase(OpFlags)) {
11431 Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11432 DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11439 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11440 int64_t Offset, SelectionDAG &DAG) const {
11441 // Create the TargetGlobalAddress node, folding in the constant
11442 // offset if it is legal.
11443 unsigned char OpFlags =
11444 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11445 CodeModel::Model M = DAG.getTarget().getCodeModel();
11446 auto PtrVT = getPointerTy(DAG.getDataLayout());
11448 if (OpFlags == X86II::MO_NO_FLAG &&
11449 X86::isOffsetSuitableForCodeModel(Offset, M)) {
11450 // A direct static reference to a global.
11451 Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
11454 Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
11457 if (Subtarget->isPICStyleRIPRel() &&
11458 (M == CodeModel::Small || M == CodeModel::Kernel))
11459 Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11461 Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11463 // With PIC, the address is actually $g + Offset.
11464 if (isGlobalRelativeToPICBase(OpFlags)) {
11465 Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11466 DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11469 // For globals that require a load from a stub to get the address, emit the
11471 if (isGlobalStubReference(OpFlags))
11472 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
11473 MachinePointerInfo::getGOT(), false, false, false, 0);
11475 // If there was a non-zero offset that we didn't fold, create an explicit
11476 // addition for it.
11478 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
11479 DAG.getConstant(Offset, dl, PtrVT));
11485 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11486 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11487 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11488 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11492 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11493 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11494 unsigned char OperandFlags, bool LocalDynamic = false) {
11495 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11496 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11498 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11499 GA->getValueType(0),
11503 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11507 SDValue Ops[] = { Chain, TGA, *InFlag };
11508 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11510 SDValue Ops[] = { Chain, TGA };
11511 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11514 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11515 MFI->setAdjustsStack(true);
11516 MFI->setHasCalls(true);
11518 SDValue Flag = Chain.getValue(1);
11519 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11522 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11524 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11527 SDLoc dl(GA); // ? function entry point might be better
11528 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11529 DAG.getNode(X86ISD::GlobalBaseReg,
11530 SDLoc(), PtrVT), InFlag);
11531 InFlag = Chain.getValue(1);
11533 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11536 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11538 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11540 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11541 X86::RAX, X86II::MO_TLSGD);
11544 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11550 // Get the start address of the TLS block for this module.
11551 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11552 .getInfo<X86MachineFunctionInfo>();
11553 MFI->incNumLocalDynamicTLSAccesses();
11557 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11558 X86II::MO_TLSLD, /*LocalDynamic=*/true);
11561 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11562 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11563 InFlag = Chain.getValue(1);
11564 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11565 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11568 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11572 unsigned char OperandFlags = X86II::MO_DTPOFF;
11573 unsigned WrapperKind = X86ISD::Wrapper;
11574 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11575 GA->getValueType(0),
11576 GA->getOffset(), OperandFlags);
11577 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11579 // Add x@dtpoff with the base.
11580 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11583 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11584 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11585 const EVT PtrVT, TLSModel::Model model,
11586 bool is64Bit, bool isPIC) {
11589 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11590 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11591 is64Bit ? 257 : 256));
11593 SDValue ThreadPointer =
11594 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11595 MachinePointerInfo(Ptr), false, false, false, 0);
11597 unsigned char OperandFlags = 0;
11598 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
11600 unsigned WrapperKind = X86ISD::Wrapper;
11601 if (model == TLSModel::LocalExec) {
11602 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11603 } else if (model == TLSModel::InitialExec) {
11605 OperandFlags = X86II::MO_GOTTPOFF;
11606 WrapperKind = X86ISD::WrapperRIP;
11608 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11611 llvm_unreachable("Unexpected model");
11614 // emit "addl x@ntpoff,%eax" (local exec)
11615 // or "addl x@indntpoff,%eax" (initial exec)
11616 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11618 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11619 GA->getOffset(), OperandFlags);
11620 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11622 if (model == TLSModel::InitialExec) {
11623 if (isPIC && !is64Bit) {
11624 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11625 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11629 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11630 MachinePointerInfo::getGOT(), false, false, false, 0);
11633 // The address of the thread local variable is the add of the thread
11634 // pointer with the offset of the variable.
11635 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11639 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11641 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11642 const GlobalValue *GV = GA->getGlobal();
11643 auto PtrVT = getPointerTy(DAG.getDataLayout());
11645 if (Subtarget->isTargetELF()) {
11646 if (DAG.getTarget().Options.EmulatedTLS)
11647 return LowerToTLSEmulatedModel(GA, DAG);
11648 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11650 case TLSModel::GeneralDynamic:
11651 if (Subtarget->is64Bit())
11652 return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
11653 return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
11654 case TLSModel::LocalDynamic:
11655 return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
11656 Subtarget->is64Bit());
11657 case TLSModel::InitialExec:
11658 case TLSModel::LocalExec:
11659 return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
11660 DAG.getTarget().getRelocationModel() ==
11663 llvm_unreachable("Unknown TLS model.");
11666 if (Subtarget->isTargetDarwin()) {
11667 // Darwin only has one model of TLS. Lower to that.
11668 unsigned char OpFlag = 0;
11669 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11670 X86ISD::WrapperRIP : X86ISD::Wrapper;
11672 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11673 // global base reg.
11674 bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11675 !Subtarget->is64Bit();
11677 OpFlag = X86II::MO_TLVP_PIC_BASE;
11679 OpFlag = X86II::MO_TLVP;
11681 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11682 GA->getValueType(0),
11683 GA->getOffset(), OpFlag);
11684 SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11686 // With PIC32, the address is actually $g + Offset.
11688 Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
11689 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11692 // Lowering the machine isd will make sure everything is in the right
11694 SDValue Chain = DAG.getEntryNode();
11695 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11696 SDValue Args[] = { Chain, Offset };
11697 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11699 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11700 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11701 MFI->setAdjustsStack(true);
11703 // And our return value (tls address) is in the standard call return value
11705 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11706 return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
11709 if (Subtarget->isTargetKnownWindowsMSVC() ||
11710 Subtarget->isTargetWindowsGNU()) {
11711 // Just use the implicit TLS architecture
11712 // Need to generate someting similar to:
11713 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11715 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
11716 // mov rcx, qword [rdx+rcx*8]
11717 // mov eax, .tls$:tlsvar
11718 // [rax+rcx] contains the address
11719 // Windows 64bit: gs:0x58
11720 // Windows 32bit: fs:__tls_array
11723 SDValue Chain = DAG.getEntryNode();
11725 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11726 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11727 // use its literal value of 0x2C.
11728 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11729 ? Type::getInt8PtrTy(*DAG.getContext(),
11731 : Type::getInt32PtrTy(*DAG.getContext(),
11734 SDValue TlsArray = Subtarget->is64Bit()
11735 ? DAG.getIntPtrConstant(0x58, dl)
11736 : (Subtarget->isTargetWindowsGNU()
11737 ? DAG.getIntPtrConstant(0x2C, dl)
11738 : DAG.getExternalSymbol("_tls_array", PtrVT));
11740 SDValue ThreadPointer =
11741 DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
11745 if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
11746 res = ThreadPointer;
11748 // Load the _tls_index variable
11749 SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
11750 if (Subtarget->is64Bit())
11751 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
11752 MachinePointerInfo(), MVT::i32, false, false,
11755 IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
11758 auto &DL = DAG.getDataLayout();
11760 DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
11761 IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
11763 res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
11766 res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
11769 // Get the offset of start of .tls section
11770 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11771 GA->getValueType(0),
11772 GA->getOffset(), X86II::MO_SECREL);
11773 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
11775 // The address of the thread local variable is the add of the thread
11776 // pointer with the offset of the variable.
11777 return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
11780 llvm_unreachable("TLS not implemented for this target.");
11783 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11784 /// and take a 2 x i32 value to shift plus a shift amount.
11785 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11786 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11787 MVT VT = Op.getSimpleValueType();
11788 unsigned VTBits = VT.getSizeInBits();
11790 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11791 SDValue ShOpLo = Op.getOperand(0);
11792 SDValue ShOpHi = Op.getOperand(1);
11793 SDValue ShAmt = Op.getOperand(2);
11794 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11795 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11797 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11798 DAG.getConstant(VTBits - 1, dl, MVT::i8));
11799 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11800 DAG.getConstant(VTBits - 1, dl, MVT::i8))
11801 : DAG.getConstant(0, dl, VT);
11803 SDValue Tmp2, Tmp3;
11804 if (Op.getOpcode() == ISD::SHL_PARTS) {
11805 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11806 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11808 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11809 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11812 // If the shift amount is larger or equal than the width of a part we can't
11813 // rely on the results of shld/shrd. Insert a test and select the appropriate
11814 // values for large shift amounts.
11815 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11816 DAG.getConstant(VTBits, dl, MVT::i8));
11817 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11818 AndNode, DAG.getConstant(0, dl, MVT::i8));
11821 SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
11822 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11823 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11825 if (Op.getOpcode() == ISD::SHL_PARTS) {
11826 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11827 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11829 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11830 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11833 SDValue Ops[2] = { Lo, Hi };
11834 return DAG.getMergeValues(Ops, dl);
11837 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11838 SelectionDAG &DAG) const {
11839 SDValue Src = Op.getOperand(0);
11840 MVT SrcVT = Src.getSimpleValueType();
11841 MVT VT = Op.getSimpleValueType();
11844 if (SrcVT.isVector()) {
11845 if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
11846 return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
11847 DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
11848 DAG.getUNDEF(SrcVT)));
11850 if (SrcVT.getVectorElementType() == MVT::i1) {
11851 MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11852 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11853 DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
11858 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11859 "Unknown SINT_TO_FP to lower!");
11861 // These are really Legal; return the operand so the caller accepts it as
11863 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11865 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11866 Subtarget->is64Bit()) {
11870 unsigned Size = SrcVT.getSizeInBits()/8;
11871 MachineFunction &MF = DAG.getMachineFunction();
11872 auto PtrVT = getPointerTy(MF.getDataLayout());
11873 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11874 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
11875 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11877 MachinePointerInfo::getFixedStack(SSFI),
11879 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11882 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11884 SelectionDAG &DAG) const {
11888 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11890 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11892 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11894 unsigned ByteSize = SrcVT.getSizeInBits()/8;
11896 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11897 MachineMemOperand *MMO;
11899 int SSFI = FI->getIndex();
11901 DAG.getMachineFunction()
11902 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11903 MachineMemOperand::MOLoad, ByteSize, ByteSize);
11905 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11906 StackSlot = StackSlot.getOperand(1);
11908 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11909 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11911 Tys, Ops, SrcVT, MMO);
11914 Chain = Result.getValue(1);
11915 SDValue InFlag = Result.getValue(2);
11917 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11918 // shouldn't be necessary except that RFP cannot be live across
11919 // multiple blocks. When stackifier is fixed, they can be uncoupled.
11920 MachineFunction &MF = DAG.getMachineFunction();
11921 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11922 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11923 auto PtrVT = getPointerTy(MF.getDataLayout());
11924 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
11925 Tys = DAG.getVTList(MVT::Other);
11927 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11929 MachineMemOperand *MMO =
11930 DAG.getMachineFunction()
11931 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11932 MachineMemOperand::MOStore, SSFISize, SSFISize);
11934 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11935 Ops, Op.getValueType(), MMO);
11936 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11937 MachinePointerInfo::getFixedStack(SSFI),
11938 false, false, false, 0);
11944 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11945 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11946 SelectionDAG &DAG) const {
11947 // This algorithm is not obvious. Here it is what we're trying to output:
11950 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11951 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11953 haddpd %xmm0, %xmm0
11955 pshufd $0x4e, %xmm0, %xmm1
11961 LLVMContext *Context = DAG.getContext();
11963 // Build some magic constants.
11964 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11965 Constant *C0 = ConstantDataVector::get(*Context, CV0);
11966 auto PtrVT = getPointerTy(DAG.getDataLayout());
11967 SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
11969 SmallVector<Constant*,2> CV1;
11971 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11972 APInt(64, 0x4330000000000000ULL))));
11974 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11975 APInt(64, 0x4530000000000000ULL))));
11976 Constant *C1 = ConstantVector::get(CV1);
11977 SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
11979 // Load the 64-bit value into an XMM register.
11980 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11982 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11983 MachinePointerInfo::getConstantPool(),
11984 false, false, false, 16);
11986 getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
11988 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11989 MachinePointerInfo::getConstantPool(),
11990 false, false, false, 16);
11991 SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
11992 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11995 if (Subtarget->hasSSE3()) {
11996 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11997 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11999 SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
12000 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
12002 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
12003 DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
12006 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
12007 DAG.getIntPtrConstant(0, dl));
12010 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
12011 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
12012 SelectionDAG &DAG) const {
12014 // FP constant to bias correct the final result.
12015 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
12018 // Load the 32-bit value into an XMM register.
12019 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12022 // Zero out the upper parts of the register.
12023 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12025 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12026 DAG.getBitcast(MVT::v2f64, Load),
12027 DAG.getIntPtrConstant(0, dl));
12029 // Or the load with the bias.
12030 SDValue Or = DAG.getNode(
12031 ISD::OR, dl, MVT::v2i64,
12032 DAG.getBitcast(MVT::v2i64,
12033 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12034 DAG.getBitcast(MVT::v2i64,
12035 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12037 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12038 DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12040 // Subtract the bias.
12041 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12043 // Handle final rounding.
12044 EVT DestVT = Op.getValueType();
12046 if (DestVT.bitsLT(MVT::f64))
12047 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12048 DAG.getIntPtrConstant(0, dl));
12049 if (DestVT.bitsGT(MVT::f64))
12050 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12052 // Handle final rounding.
12056 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12057 const X86Subtarget &Subtarget) {
12058 // The algorithm is the following:
12059 // #ifdef __SSE4_1__
12060 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12061 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12062 // (uint4) 0x53000000, 0xaa);
12064 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12065 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
12067 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12068 // return (float4) lo + fhi;
12071 SDValue V = Op->getOperand(0);
12072 EVT VecIntVT = V.getValueType();
12073 bool Is128 = VecIntVT == MVT::v4i32;
12074 EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12075 // If we convert to something else than the supported type, e.g., to v4f64,
12077 if (VecFloatVT != Op->getValueType(0))
12080 unsigned NumElts = VecIntVT.getVectorNumElements();
12081 assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12082 "Unsupported custom type");
12083 assert(NumElts <= 8 && "The size of the constant array must be fixed");
12085 // In the #idef/#else code, we have in common:
12086 // - The vector of constants:
12092 // Create the splat vector for 0x4b000000.
12093 SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12094 SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12095 CstLow, CstLow, CstLow, CstLow};
12096 SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12097 makeArrayRef(&CstLowArray[0], NumElts));
12098 // Create the splat vector for 0x53000000.
12099 SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12100 SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12101 CstHigh, CstHigh, CstHigh, CstHigh};
12102 SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12103 makeArrayRef(&CstHighArray[0], NumElts));
12105 // Create the right shift.
12106 SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12107 SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12108 CstShift, CstShift, CstShift, CstShift};
12109 SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12110 makeArrayRef(&CstShiftArray[0], NumElts));
12111 SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12114 if (Subtarget.hasSSE41()) {
12115 EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12116 // uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12117 SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12118 SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12119 // Low will be bitcasted right away, so do not bother bitcasting back to its
12121 Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12122 VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12123 // uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12124 // (uint4) 0x53000000, 0xaa);
12125 SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12126 SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12127 // High will be bitcasted right away, so do not bother bitcasting back to
12128 // its original type.
12129 High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12130 VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12132 SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12133 SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12134 CstMask, CstMask, CstMask);
12135 // uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12136 SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12137 Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12139 // uint4 hi = (v >> 16) | (uint4) 0x53000000;
12140 High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12143 // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12144 SDValue CstFAdd = DAG.getConstantFP(
12145 APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12146 SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12147 CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12148 SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12149 makeArrayRef(&CstFAddArray[0], NumElts));
12151 // float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12152 SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12154 DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12155 // return (float4) lo + fhi;
12156 SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12157 return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12160 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12161 SelectionDAG &DAG) const {
12162 SDValue N0 = Op.getOperand(0);
12163 MVT SVT = N0.getSimpleValueType();
12166 switch (SVT.SimpleTy) {
12168 llvm_unreachable("Custom UINT_TO_FP is not supported!");
12173 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12174 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12175 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12179 return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
12182 if (Subtarget->hasAVX512())
12183 return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
12184 DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
12186 llvm_unreachable(nullptr);
12189 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12190 SelectionDAG &DAG) const {
12191 SDValue N0 = Op.getOperand(0);
12193 auto PtrVT = getPointerTy(DAG.getDataLayout());
12195 if (Op.getValueType().isVector())
12196 return lowerUINT_TO_FP_vec(Op, DAG);
12198 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
12199 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
12200 // the optimization here.
12201 if (DAG.SignBitIsZero(N0))
12202 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
12204 MVT SrcVT = N0.getSimpleValueType();
12205 MVT DstVT = Op.getSimpleValueType();
12206 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
12207 return LowerUINT_TO_FP_i64(Op, DAG);
12208 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
12209 return LowerUINT_TO_FP_i32(Op, DAG);
12210 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
12213 // Make a 64-bit buffer, and use it to build an FILD.
12214 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
12215 if (SrcVT == MVT::i32) {
12216 SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
12217 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
12218 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12219 StackSlot, MachinePointerInfo(),
12221 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
12222 OffsetSlot, MachinePointerInfo(),
12224 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
12228 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
12229 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12230 StackSlot, MachinePointerInfo(),
12232 // For i64 source, we need to add the appropriate power of 2 if the input
12233 // was negative. This is the same as the optimization in
12234 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
12235 // we must be careful to do the computation in x87 extended precision, not
12236 // in SSE. (The generic code can't know it's OK to do this, or how to.)
12237 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
12238 MachineMemOperand *MMO =
12239 DAG.getMachineFunction()
12240 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12241 MachineMemOperand::MOLoad, 8, 8);
12243 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
12244 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
12245 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
12248 APInt FF(32, 0x5F800000ULL);
12250 // Check whether the sign bit is set.
12251 SDValue SignSet = DAG.getSetCC(
12252 dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
12253 Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
12255 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
12256 SDValue FudgePtr = DAG.getConstantPool(
12257 ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
12259 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
12260 SDValue Zero = DAG.getIntPtrConstant(0, dl);
12261 SDValue Four = DAG.getIntPtrConstant(4, dl);
12262 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
12264 FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
12266 // Load the value out, extending it from f32 to f80.
12267 // FIXME: Avoid the extend by constructing the right constant pool?
12268 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
12269 FudgePtr, MachinePointerInfo::getConstantPool(),
12270 MVT::f32, false, false, false, 4);
12271 // Extend everything to 80 bits to force it to be done on x87.
12272 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
12273 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
12274 DAG.getIntPtrConstant(0, dl));
12277 std::pair<SDValue,SDValue>
12278 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
12279 bool IsSigned, bool IsReplace) const {
12282 EVT DstTy = Op.getValueType();
12283 auto PtrVT = getPointerTy(DAG.getDataLayout());
12285 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
12286 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
12290 assert(DstTy.getSimpleVT() <= MVT::i64 &&
12291 DstTy.getSimpleVT() >= MVT::i16 &&
12292 "Unknown FP_TO_INT to lower!");
12294 // These are really Legal.
12295 if (DstTy == MVT::i32 &&
12296 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12297 return std::make_pair(SDValue(), SDValue());
12298 if (Subtarget->is64Bit() &&
12299 DstTy == MVT::i64 &&
12300 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12301 return std::make_pair(SDValue(), SDValue());
12303 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
12304 // stack slot, or into the FTOL runtime function.
12305 MachineFunction &MF = DAG.getMachineFunction();
12306 unsigned MemSize = DstTy.getSizeInBits()/8;
12307 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12308 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12311 if (!IsSigned && isIntegerTypeFTOL(DstTy))
12312 Opc = X86ISD::WIN_FTOL;
12314 switch (DstTy.getSimpleVT().SimpleTy) {
12315 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12316 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12317 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12318 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12321 SDValue Chain = DAG.getEntryNode();
12322 SDValue Value = Op.getOperand(0);
12323 EVT TheVT = Op.getOperand(0).getValueType();
12324 // FIXME This causes a redundant load/store if the SSE-class value is already
12325 // in memory, such as if it is on the callstack.
12326 if (isScalarFPTypeInSSEReg(TheVT)) {
12327 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12328 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12329 MachinePointerInfo::getFixedStack(SSFI),
12331 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12333 Chain, StackSlot, DAG.getValueType(TheVT)
12336 MachineMemOperand *MMO =
12337 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12338 MachineMemOperand::MOLoad, MemSize, MemSize);
12339 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12340 Chain = Value.getValue(1);
12341 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12342 StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12345 MachineMemOperand *MMO =
12346 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12347 MachineMemOperand::MOStore, MemSize, MemSize);
12349 if (Opc != X86ISD::WIN_FTOL) {
12350 // Build the FP_TO_INT*_IN_MEM
12351 SDValue Ops[] = { Chain, Value, StackSlot };
12352 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12354 return std::make_pair(FIST, StackSlot);
12356 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
12357 DAG.getVTList(MVT::Other, MVT::Glue),
12359 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
12360 MVT::i32, ftol.getValue(1));
12361 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
12362 MVT::i32, eax.getValue(2));
12363 SDValue Ops[] = { eax, edx };
12364 SDValue pair = IsReplace
12365 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
12366 : DAG.getMergeValues(Ops, DL);
12367 return std::make_pair(pair, SDValue());
12371 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12372 const X86Subtarget *Subtarget) {
12373 MVT VT = Op->getSimpleValueType(0);
12374 SDValue In = Op->getOperand(0);
12375 MVT InVT = In.getSimpleValueType();
12378 if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12379 return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12381 // Optimize vectors in AVX mode:
12384 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
12385 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
12386 // Concat upper and lower parts.
12389 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
12390 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
12391 // Concat upper and lower parts.
12394 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12395 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12396 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12399 if (Subtarget->hasInt256())
12400 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12402 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12403 SDValue Undef = DAG.getUNDEF(InVT);
12404 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12405 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12406 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12408 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12409 VT.getVectorNumElements()/2);
12411 OpLo = DAG.getBitcast(HVT, OpLo);
12412 OpHi = DAG.getBitcast(HVT, OpHi);
12414 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12417 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12418 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
12419 MVT VT = Op->getSimpleValueType(0);
12420 SDValue In = Op->getOperand(0);
12421 MVT InVT = In.getSimpleValueType();
12423 unsigned int NumElts = VT.getVectorNumElements();
12424 if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
12427 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12428 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12430 assert(InVT.getVectorElementType() == MVT::i1);
12431 MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12433 DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12435 DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12437 SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12438 if (VT.is512BitVector())
12440 return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12443 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12444 SelectionDAG &DAG) {
12445 if (Subtarget->hasFp256())
12446 if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12452 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12453 SelectionDAG &DAG) {
12455 MVT VT = Op.getSimpleValueType();
12456 SDValue In = Op.getOperand(0);
12457 MVT SVT = In.getSimpleValueType();
12459 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12460 return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
12462 if (Subtarget->hasFp256())
12463 if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12466 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12467 VT.getVectorNumElements() != SVT.getVectorNumElements());
12471 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12473 MVT VT = Op.getSimpleValueType();
12474 SDValue In = Op.getOperand(0);
12475 MVT InVT = In.getSimpleValueType();
12477 if (VT == MVT::i1) {
12478 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12479 "Invalid scalar TRUNCATE operation");
12480 if (InVT.getSizeInBits() >= 32)
12482 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12483 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12485 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12486 "Invalid TRUNCATE operation");
12488 // move vector to mask - truncate solution for SKX
12489 if (VT.getVectorElementType() == MVT::i1) {
12490 if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12491 Subtarget->hasBWI())
12492 return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12493 if ((InVT.is256BitVector() || InVT.is128BitVector())
12494 && InVT.getScalarSizeInBits() <= 16 &&
12495 Subtarget->hasBWI() && Subtarget->hasVLX())
12496 return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12497 if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12498 Subtarget->hasDQI())
12499 return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12500 if ((InVT.is256BitVector() || InVT.is128BitVector())
12501 && InVT.getScalarSizeInBits() >= 32 &&
12502 Subtarget->hasDQI() && Subtarget->hasVLX())
12503 return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12506 if (VT.getVectorElementType() == MVT::i1) {
12507 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12508 unsigned NumElts = InVT.getVectorNumElements();
12509 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12510 if (InVT.getSizeInBits() < 512) {
12511 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12512 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12517 DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
12518 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12519 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12522 // vpmovqb/w/d, vpmovdb/w, vpmovwb
12523 if (((!InVT.is512BitVector() && Subtarget->hasVLX()) || InVT.is512BitVector()) &&
12524 (InVT.getVectorElementType() != MVT::i16 || Subtarget->hasBWI()))
12525 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12527 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12528 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12529 if (Subtarget->hasInt256()) {
12530 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12531 In = DAG.getBitcast(MVT::v8i32, In);
12532 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12534 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12535 DAG.getIntPtrConstant(0, DL));
12538 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12539 DAG.getIntPtrConstant(0, DL));
12540 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12541 DAG.getIntPtrConstant(2, DL));
12542 OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12543 OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12544 static const int ShufMask[] = {0, 2, 4, 6};
12545 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12548 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12549 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12550 if (Subtarget->hasInt256()) {
12551 In = DAG.getBitcast(MVT::v32i8, In);
12553 SmallVector<SDValue,32> pshufbMask;
12554 for (unsigned i = 0; i < 2; ++i) {
12555 pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
12556 pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
12557 pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
12558 pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
12559 pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
12560 pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
12561 pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
12562 pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
12563 for (unsigned j = 0; j < 8; ++j)
12564 pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
12566 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12567 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12568 In = DAG.getBitcast(MVT::v4i64, In);
12570 static const int ShufMask[] = {0, 2, -1, -1};
12571 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
12573 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12574 DAG.getIntPtrConstant(0, DL));
12575 return DAG.getBitcast(VT, In);
12578 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12579 DAG.getIntPtrConstant(0, DL));
12581 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12582 DAG.getIntPtrConstant(4, DL));
12584 OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
12585 OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
12587 // The PSHUFB mask:
12588 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
12589 -1, -1, -1, -1, -1, -1, -1, -1};
12591 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12592 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12593 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12595 OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12596 OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12598 // The MOVLHPS Mask:
12599 static const int ShufMask2[] = {0, 1, 4, 5};
12600 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12601 return DAG.getBitcast(MVT::v8i16, res);
12604 // Handle truncation of V256 to V128 using shuffles.
12605 if (!VT.is128BitVector() || !InVT.is256BitVector())
12608 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12610 unsigned NumElems = VT.getVectorNumElements();
12611 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12613 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12614 // Prepare truncation shuffle mask
12615 for (unsigned i = 0; i != NumElems; ++i)
12616 MaskVec[i] = i * 2;
12617 SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
12618 DAG.getUNDEF(NVT), &MaskVec[0]);
12619 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12620 DAG.getIntPtrConstant(0, DL));
12623 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12624 SelectionDAG &DAG) const {
12625 assert(!Op.getSimpleValueType().isVector());
12627 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12628 /*IsSigned=*/ true, /*IsReplace=*/ false);
12629 SDValue FIST = Vals.first, StackSlot = Vals.second;
12630 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12631 if (!FIST.getNode()) return Op;
12633 if (StackSlot.getNode())
12634 // Load the result.
12635 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12636 FIST, StackSlot, MachinePointerInfo(),
12637 false, false, false, 0);
12639 // The node is the result.
12643 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12644 SelectionDAG &DAG) const {
12645 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12646 /*IsSigned=*/ false, /*IsReplace=*/ false);
12647 SDValue FIST = Vals.first, StackSlot = Vals.second;
12648 assert(FIST.getNode() && "Unexpected failure");
12650 if (StackSlot.getNode())
12651 // Load the result.
12652 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12653 FIST, StackSlot, MachinePointerInfo(),
12654 false, false, false, 0);
12656 // The node is the result.
12660 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12662 MVT VT = Op.getSimpleValueType();
12663 SDValue In = Op.getOperand(0);
12664 MVT SVT = In.getSimpleValueType();
12666 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12668 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12669 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12670 In, DAG.getUNDEF(SVT)));
12673 /// The only differences between FABS and FNEG are the mask and the logic op.
12674 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12675 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12676 assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12677 "Wrong opcode for lowering FABS or FNEG.");
12679 bool IsFABS = (Op.getOpcode() == ISD::FABS);
12681 // If this is a FABS and it has an FNEG user, bail out to fold the combination
12682 // into an FNABS. We'll lower the FABS after that if it is still in use.
12684 for (SDNode *User : Op->uses())
12685 if (User->getOpcode() == ISD::FNEG)
12689 MVT VT = Op.getSimpleValueType();
12691 // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12692 // decide if we should generate a 16-byte constant mask when we only need 4 or
12693 // 8 bytes for the scalar case.
12699 if (VT.isVector()) {
12701 EltVT = VT.getVectorElementType();
12702 NumElts = VT.getVectorNumElements();
12704 // There are no scalar bitwise logical SSE/AVX instructions, so we
12705 // generate a 16-byte vector constant and logic op even for the scalar case.
12706 // Using a 16-byte mask allows folding the load of the mask with
12707 // the logic op, so it can save (~4 bytes) on code size.
12708 LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
12710 NumElts = (VT == MVT::f64) ? 2 : 4;
12713 unsigned EltBits = EltVT.getSizeInBits();
12714 LLVMContext *Context = DAG.getContext();
12715 // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12717 IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12718 Constant *C = ConstantInt::get(*Context, MaskElt);
12719 C = ConstantVector::getSplat(NumElts, C);
12720 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12721 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
12722 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12723 SDValue Mask = DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
12724 MachinePointerInfo::getConstantPool(),
12725 false, false, false, Alignment);
12727 SDValue Op0 = Op.getOperand(0);
12728 bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12730 IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12731 SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12734 return DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
12736 // For the scalar case extend to a 128-bit vector, perform the logic op,
12737 // and extract the scalar result back out.
12738 Operand = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Operand);
12739 SDValue LogicNode = DAG.getNode(LogicOp, dl, LogicVT, Operand, Mask);
12740 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, LogicNode,
12741 DAG.getIntPtrConstant(0, dl));
12744 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12745 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12746 LLVMContext *Context = DAG.getContext();
12747 SDValue Op0 = Op.getOperand(0);
12748 SDValue Op1 = Op.getOperand(1);
12750 MVT VT = Op.getSimpleValueType();
12751 MVT SrcVT = Op1.getSimpleValueType();
12753 // If second operand is smaller, extend it first.
12754 if (SrcVT.bitsLT(VT)) {
12755 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12758 // And if it is bigger, shrink it first.
12759 if (SrcVT.bitsGT(VT)) {
12760 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
12764 // At this point the operands and the result should have the same
12765 // type, and that won't be f80 since that is not custom lowered.
12767 const fltSemantics &Sem =
12768 VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12769 const unsigned SizeInBits = VT.getSizeInBits();
12771 SmallVector<Constant *, 4> CV(
12772 VT == MVT::f64 ? 2 : 4,
12773 ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12775 // First, clear all bits but the sign bit from the second operand (sign).
12776 CV[0] = ConstantFP::get(*Context,
12777 APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12778 Constant *C = ConstantVector::get(CV);
12779 auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
12780 SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
12782 // Perform all logic operations as 16-byte vectors because there are no
12783 // scalar FP logic instructions in SSE. This allows load folding of the
12784 // constants into the logic instructions.
12785 MVT LogicVT = (VT == MVT::f64) ? MVT::v2f64 : MVT::v4f32;
12786 SDValue Mask1 = DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
12787 MachinePointerInfo::getConstantPool(),
12788 false, false, false, 16);
12789 Op1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op1);
12790 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op1, Mask1);
12792 // Next, clear the sign bit from the first operand (magnitude).
12793 // If it's a constant, we can clear it here.
12794 if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12795 APFloat APF = Op0CN->getValueAPF();
12796 // If the magnitude is a positive zero, the sign bit alone is enough.
12797 if (APF.isPosZero())
12798 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, SignBit,
12799 DAG.getIntPtrConstant(0, dl));
12801 CV[0] = ConstantFP::get(*Context, APF);
12803 CV[0] = ConstantFP::get(
12805 APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12807 C = ConstantVector::get(CV);
12808 CPIdx = DAG.getConstantPool(C, PtrVT, 16);
12809 SDValue Val = DAG.getLoad(LogicVT, dl, DAG.getEntryNode(), CPIdx,
12810 MachinePointerInfo::getConstantPool(),
12811 false, false, false, 16);
12812 // If the magnitude operand wasn't a constant, we need to AND out the sign.
12813 if (!isa<ConstantFPSDNode>(Op0)) {
12814 Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LogicVT, Op0);
12815 Val = DAG.getNode(X86ISD::FAND, dl, LogicVT, Op0, Val);
12817 // OR the magnitude value with the sign bit.
12818 Val = DAG.getNode(X86ISD::FOR, dl, LogicVT, Val, SignBit);
12819 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SrcVT, Val,
12820 DAG.getIntPtrConstant(0, dl));
12823 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12824 SDValue N0 = Op.getOperand(0);
12826 MVT VT = Op.getSimpleValueType();
12828 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12829 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12830 DAG.getConstant(1, dl, VT));
12831 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
12834 // Check whether an OR'd tree is PTEST-able.
12835 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12836 SelectionDAG &DAG) {
12837 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12839 if (!Subtarget->hasSSE41())
12842 if (!Op->hasOneUse())
12845 SDNode *N = Op.getNode();
12848 SmallVector<SDValue, 8> Opnds;
12849 DenseMap<SDValue, unsigned> VecInMap;
12850 SmallVector<SDValue, 8> VecIns;
12851 EVT VT = MVT::Other;
12853 // Recognize a special case where a vector is casted into wide integer to
12855 Opnds.push_back(N->getOperand(0));
12856 Opnds.push_back(N->getOperand(1));
12858 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12859 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12860 // BFS traverse all OR'd operands.
12861 if (I->getOpcode() == ISD::OR) {
12862 Opnds.push_back(I->getOperand(0));
12863 Opnds.push_back(I->getOperand(1));
12864 // Re-evaluate the number of nodes to be traversed.
12865 e += 2; // 2 more nodes (LHS and RHS) are pushed.
12869 // Quit if a non-EXTRACT_VECTOR_ELT
12870 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12873 // Quit if without a constant index.
12874 SDValue Idx = I->getOperand(1);
12875 if (!isa<ConstantSDNode>(Idx))
12878 SDValue ExtractedFromVec = I->getOperand(0);
12879 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12880 if (M == VecInMap.end()) {
12881 VT = ExtractedFromVec.getValueType();
12882 // Quit if not 128/256-bit vector.
12883 if (!VT.is128BitVector() && !VT.is256BitVector())
12885 // Quit if not the same type.
12886 if (VecInMap.begin() != VecInMap.end() &&
12887 VT != VecInMap.begin()->first.getValueType())
12889 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12890 VecIns.push_back(ExtractedFromVec);
12892 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12895 assert((VT.is128BitVector() || VT.is256BitVector()) &&
12896 "Not extracted from 128-/256-bit vector.");
12898 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12900 for (DenseMap<SDValue, unsigned>::const_iterator
12901 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12902 // Quit if not all elements are used.
12903 if (I->second != FullMask)
12907 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12909 // Cast all vectors into TestVT for PTEST.
12910 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12911 VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
12913 // If more than one full vectors are evaluated, OR them first before PTEST.
12914 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12915 // Each iteration will OR 2 nodes and append the result until there is only
12916 // 1 node left, i.e. the final OR'd value of all vectors.
12917 SDValue LHS = VecIns[Slot];
12918 SDValue RHS = VecIns[Slot + 1];
12919 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12922 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12923 VecIns.back(), VecIns.back());
12926 /// \brief return true if \c Op has a use that doesn't just read flags.
12927 static bool hasNonFlagsUse(SDValue Op) {
12928 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12930 SDNode *User = *UI;
12931 unsigned UOpNo = UI.getOperandNo();
12932 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12933 // Look pass truncate.
12934 UOpNo = User->use_begin().getOperandNo();
12935 User = *User->use_begin();
12938 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12939 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12945 /// Emit nodes that will be selected as "test Op0,Op0", or something
12947 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12948 SelectionDAG &DAG) const {
12949 if (Op.getValueType() == MVT::i1) {
12950 SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
12951 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
12952 DAG.getConstant(0, dl, MVT::i8));
12954 // CF and OF aren't always set the way we want. Determine which
12955 // of these we need.
12956 bool NeedCF = false;
12957 bool NeedOF = false;
12960 case X86::COND_A: case X86::COND_AE:
12961 case X86::COND_B: case X86::COND_BE:
12964 case X86::COND_G: case X86::COND_GE:
12965 case X86::COND_L: case X86::COND_LE:
12966 case X86::COND_O: case X86::COND_NO: {
12967 // Check if we really need to set the
12968 // Overflow flag. If NoSignedWrap is present
12969 // that is not actually needed.
12970 switch (Op->getOpcode()) {
12975 const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
12976 if (BinNode->Flags.hasNoSignedWrap())
12986 // See if we can use the EFLAGS value from the operand instead of
12987 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12988 // we prove that the arithmetic won't overflow, we can't use OF or CF.
12989 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12990 // Emit a CMP with 0, which is the TEST pattern.
12991 //if (Op.getValueType() == MVT::i1)
12992 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12993 // DAG.getConstant(0, MVT::i1));
12994 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12995 DAG.getConstant(0, dl, Op.getValueType()));
12997 unsigned Opcode = 0;
12998 unsigned NumOperands = 0;
13000 // Truncate operations may prevent the merge of the SETCC instruction
13001 // and the arithmetic instruction before it. Attempt to truncate the operands
13002 // of the arithmetic instruction and use a reduced bit-width instruction.
13003 bool NeedTruncation = false;
13004 SDValue ArithOp = Op;
13005 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
13006 SDValue Arith = Op->getOperand(0);
13007 // Both the trunc and the arithmetic op need to have one user each.
13008 if (Arith->hasOneUse())
13009 switch (Arith.getOpcode()) {
13016 NeedTruncation = true;
13022 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
13023 // which may be the result of a CAST. We use the variable 'Op', which is the
13024 // non-casted variable when we check for possible users.
13025 switch (ArithOp.getOpcode()) {
13027 // Due to an isel shortcoming, be conservative if this add is likely to be
13028 // selected as part of a load-modify-store instruction. When the root node
13029 // in a match is a store, isel doesn't know how to remap non-chain non-flag
13030 // uses of other nodes in the match, such as the ADD in this case. This
13031 // leads to the ADD being left around and reselected, with the result being
13032 // two adds in the output. Alas, even if none our users are stores, that
13033 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
13034 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
13035 // climbing the DAG back to the root, and it doesn't seem to be worth the
13037 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13038 UE = Op.getNode()->use_end(); UI != UE; ++UI)
13039 if (UI->getOpcode() != ISD::CopyToReg &&
13040 UI->getOpcode() != ISD::SETCC &&
13041 UI->getOpcode() != ISD::STORE)
13044 if (ConstantSDNode *C =
13045 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
13046 // An add of one will be selected as an INC.
13047 if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
13048 Opcode = X86ISD::INC;
13053 // An add of negative one (subtract of one) will be selected as a DEC.
13054 if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
13055 Opcode = X86ISD::DEC;
13061 // Otherwise use a regular EFLAGS-setting add.
13062 Opcode = X86ISD::ADD;
13067 // If we have a constant logical shift that's only used in a comparison
13068 // against zero turn it into an equivalent AND. This allows turning it into
13069 // a TEST instruction later.
13070 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
13071 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
13072 EVT VT = Op.getValueType();
13073 unsigned BitWidth = VT.getSizeInBits();
13074 unsigned ShAmt = Op->getConstantOperandVal(1);
13075 if (ShAmt >= BitWidth) // Avoid undefined shifts.
13077 APInt Mask = ArithOp.getOpcode() == ISD::SRL
13078 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
13079 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
13080 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
13082 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
13083 DAG.getConstant(Mask, dl, VT));
13084 DAG.ReplaceAllUsesWith(Op, New);
13090 // If the primary and result isn't used, don't bother using X86ISD::AND,
13091 // because a TEST instruction will be better.
13092 if (!hasNonFlagsUse(Op))
13098 // Due to the ISEL shortcoming noted above, be conservative if this op is
13099 // likely to be selected as part of a load-modify-store instruction.
13100 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13101 UE = Op.getNode()->use_end(); UI != UE; ++UI)
13102 if (UI->getOpcode() == ISD::STORE)
13105 // Otherwise use a regular EFLAGS-setting instruction.
13106 switch (ArithOp.getOpcode()) {
13107 default: llvm_unreachable("unexpected operator!");
13108 case ISD::SUB: Opcode = X86ISD::SUB; break;
13109 case ISD::XOR: Opcode = X86ISD::XOR; break;
13110 case ISD::AND: Opcode = X86ISD::AND; break;
13112 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
13113 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
13114 if (EFLAGS.getNode())
13117 Opcode = X86ISD::OR;
13131 return SDValue(Op.getNode(), 1);
13137 // If we found that truncation is beneficial, perform the truncation and
13139 if (NeedTruncation) {
13140 EVT VT = Op.getValueType();
13141 SDValue WideVal = Op->getOperand(0);
13142 EVT WideVT = WideVal.getValueType();
13143 unsigned ConvertedOp = 0;
13144 // Use a target machine opcode to prevent further DAGCombine
13145 // optimizations that may separate the arithmetic operations
13146 // from the setcc node.
13147 switch (WideVal.getOpcode()) {
13149 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
13150 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
13151 case ISD::AND: ConvertedOp = X86ISD::AND; break;
13152 case ISD::OR: ConvertedOp = X86ISD::OR; break;
13153 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
13157 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13158 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
13159 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
13160 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
13161 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
13167 // Emit a CMP with 0, which is the TEST pattern.
13168 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13169 DAG.getConstant(0, dl, Op.getValueType()));
13171 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
13172 SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
13174 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
13175 DAG.ReplaceAllUsesWith(Op, New);
13176 return SDValue(New.getNode(), 1);
13179 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
13181 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
13182 SDLoc dl, SelectionDAG &DAG) const {
13183 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
13184 if (C->getAPIntValue() == 0)
13185 return EmitTest(Op0, X86CC, dl, DAG);
13187 if (Op0.getValueType() == MVT::i1)
13188 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
13191 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
13192 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
13193 // Do the comparison at i32 if it's smaller, besides the Atom case.
13194 // This avoids subregister aliasing issues. Keep the smaller reference
13195 // if we're optimizing for size, however, as that'll allow better folding
13196 // of memory operations.
13197 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
13198 !DAG.getMachineFunction().getFunction()->optForMinSize() &&
13199 !Subtarget->isAtom()) {
13200 unsigned ExtendOp =
13201 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
13202 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
13203 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
13205 // Use SUB instead of CMP to enable CSE between SUB and CMP.
13206 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
13207 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
13209 return SDValue(Sub.getNode(), 1);
13211 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
13214 /// Convert a comparison if required by the subtarget.
13215 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
13216 SelectionDAG &DAG) const {
13217 // If the subtarget does not support the FUCOMI instruction, floating-point
13218 // comparisons have to be converted.
13219 if (Subtarget->hasCMov() ||
13220 Cmp.getOpcode() != X86ISD::CMP ||
13221 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
13222 !Cmp.getOperand(1).getValueType().isFloatingPoint())
13225 // The instruction selector will select an FUCOM instruction instead of
13226 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
13227 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
13228 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
13230 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
13231 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
13232 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
13233 DAG.getConstant(8, dl, MVT::i8));
13234 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
13235 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
13238 /// The minimum architected relative accuracy is 2^-12. We need one
13239 /// Newton-Raphson step to have a good float result (24 bits of precision).
13240 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
13241 DAGCombinerInfo &DCI,
13242 unsigned &RefinementSteps,
13243 bool &UseOneConstNR) const {
13244 EVT VT = Op.getValueType();
13245 const char *RecipOp;
13247 // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
13248 // TODO: Add support for AVX512 (v16f32).
13249 // It is likely not profitable to do this for f64 because a double-precision
13250 // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
13251 // instructions: convert to single, rsqrtss, convert back to double, refine
13252 // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
13253 // along with FMA, this could be a throughput win.
13254 if (VT == MVT::f32 && Subtarget->hasSSE1())
13256 else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13257 (VT == MVT::v8f32 && Subtarget->hasAVX()))
13258 RecipOp = "vec-sqrtf";
13262 TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13263 if (!Recips.isEnabled(RecipOp))
13266 RefinementSteps = Recips.getRefinementSteps(RecipOp);
13267 UseOneConstNR = false;
13268 return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
13271 /// The minimum architected relative accuracy is 2^-12. We need one
13272 /// Newton-Raphson step to have a good float result (24 bits of precision).
13273 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
13274 DAGCombinerInfo &DCI,
13275 unsigned &RefinementSteps) const {
13276 EVT VT = Op.getValueType();
13277 const char *RecipOp;
13279 // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
13280 // TODO: Add support for AVX512 (v16f32).
13281 // It is likely not profitable to do this for f64 because a double-precision
13282 // reciprocal estimate with refinement on x86 prior to FMA requires
13283 // 15 instructions: convert to single, rcpss, convert back to double, refine
13284 // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
13285 // along with FMA, this could be a throughput win.
13286 if (VT == MVT::f32 && Subtarget->hasSSE1())
13288 else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13289 (VT == MVT::v8f32 && Subtarget->hasAVX()))
13290 RecipOp = "vec-divf";
13294 TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13295 if (!Recips.isEnabled(RecipOp))
13298 RefinementSteps = Recips.getRefinementSteps(RecipOp);
13299 return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
13302 /// If we have at least two divisions that use the same divisor, convert to
13303 /// multplication by a reciprocal. This may need to be adjusted for a given
13304 /// CPU if a division's cost is not at least twice the cost of a multiplication.
13305 /// This is because we still need one division to calculate the reciprocal and
13306 /// then we need two multiplies by that reciprocal as replacements for the
13307 /// original divisions.
13308 unsigned X86TargetLowering::combineRepeatedFPDivisors() const {
13312 static bool isAllOnes(SDValue V) {
13313 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13314 return C && C->isAllOnesValue();
13317 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
13318 /// if it's possible.
13319 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
13320 SDLoc dl, SelectionDAG &DAG) const {
13321 SDValue Op0 = And.getOperand(0);
13322 SDValue Op1 = And.getOperand(1);
13323 if (Op0.getOpcode() == ISD::TRUNCATE)
13324 Op0 = Op0.getOperand(0);
13325 if (Op1.getOpcode() == ISD::TRUNCATE)
13326 Op1 = Op1.getOperand(0);
13329 if (Op1.getOpcode() == ISD::SHL)
13330 std::swap(Op0, Op1);
13331 if (Op0.getOpcode() == ISD::SHL) {
13332 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
13333 if (And00C->getZExtValue() == 1) {
13334 // If we looked past a truncate, check that it's only truncating away
13336 unsigned BitWidth = Op0.getValueSizeInBits();
13337 unsigned AndBitWidth = And.getValueSizeInBits();
13338 if (BitWidth > AndBitWidth) {
13340 DAG.computeKnownBits(Op0, Zeros, Ones);
13341 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13345 RHS = Op0.getOperand(1);
13347 } else if (Op1.getOpcode() == ISD::Constant) {
13348 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13349 uint64_t AndRHSVal = AndRHS->getZExtValue();
13350 SDValue AndLHS = Op0;
13352 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13353 LHS = AndLHS.getOperand(0);
13354 RHS = AndLHS.getOperand(1);
13357 // Use BT if the immediate can't be encoded in a TEST instruction.
13358 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13360 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13364 if (LHS.getNode()) {
13365 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
13366 // instruction. Since the shift amount is in-range-or-undefined, we know
13367 // that doing a bittest on the i32 value is ok. We extend to i32 because
13368 // the encoding for the i16 version is larger than the i32 version.
13369 // Also promote i16 to i32 for performance / code size reason.
13370 if (LHS.getValueType() == MVT::i8 ||
13371 LHS.getValueType() == MVT::i16)
13372 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13374 // If the operand types disagree, extend the shift amount to match. Since
13375 // BT ignores high bits (like shifts) we can use anyextend.
13376 if (LHS.getValueType() != RHS.getValueType())
13377 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13379 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13380 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13381 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13382 DAG.getConstant(Cond, dl, MVT::i8), BT);
13388 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13390 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13395 // SSE Condition code mapping:
13404 switch (SetCCOpcode) {
13405 default: llvm_unreachable("Unexpected SETCC condition");
13407 case ISD::SETEQ: SSECC = 0; break;
13409 case ISD::SETGT: Swap = true; // Fallthrough
13411 case ISD::SETOLT: SSECC = 1; break;
13413 case ISD::SETGE: Swap = true; // Fallthrough
13415 case ISD::SETOLE: SSECC = 2; break;
13416 case ISD::SETUO: SSECC = 3; break;
13418 case ISD::SETNE: SSECC = 4; break;
13419 case ISD::SETULE: Swap = true; // Fallthrough
13420 case ISD::SETUGE: SSECC = 5; break;
13421 case ISD::SETULT: Swap = true; // Fallthrough
13422 case ISD::SETUGT: SSECC = 6; break;
13423 case ISD::SETO: SSECC = 7; break;
13425 case ISD::SETONE: SSECC = 8; break;
13428 std::swap(Op0, Op1);
13433 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13434 // ones, and then concatenate the result back.
13435 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13436 MVT VT = Op.getSimpleValueType();
13438 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13439 "Unsupported value type for operation");
13441 unsigned NumElems = VT.getVectorNumElements();
13443 SDValue CC = Op.getOperand(2);
13445 // Extract the LHS vectors
13446 SDValue LHS = Op.getOperand(0);
13447 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13448 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13450 // Extract the RHS vectors
13451 SDValue RHS = Op.getOperand(1);
13452 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13453 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13455 // Issue the operation on the smaller types and concatenate the result back
13456 MVT EltVT = VT.getVectorElementType();
13457 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13458 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13459 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13460 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13463 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13464 SDValue Op0 = Op.getOperand(0);
13465 SDValue Op1 = Op.getOperand(1);
13466 SDValue CC = Op.getOperand(2);
13467 MVT VT = Op.getSimpleValueType();
13470 assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13471 "Unexpected type for boolean compare operation");
13472 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13473 SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13474 DAG.getConstant(-1, dl, VT));
13475 SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13476 DAG.getConstant(-1, dl, VT));
13477 switch (SetCCOpcode) {
13478 default: llvm_unreachable("Unexpected SETCC condition");
13480 // (x == y) -> ~(x ^ y)
13481 return DAG.getNode(ISD::XOR, dl, VT,
13482 DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13483 DAG.getConstant(-1, dl, VT));
13485 // (x != y) -> (x ^ y)
13486 return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13489 // (x > y) -> (x & ~y)
13490 return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13493 // (x < y) -> (~x & y)
13494 return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13497 // (x <= y) -> (~x | y)
13498 return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13501 // (x >=y) -> (x | ~y)
13502 return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13506 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13507 const X86Subtarget *Subtarget) {
13508 SDValue Op0 = Op.getOperand(0);
13509 SDValue Op1 = Op.getOperand(1);
13510 SDValue CC = Op.getOperand(2);
13511 MVT VT = Op.getSimpleValueType();
13514 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13515 Op.getValueType().getScalarType() == MVT::i1 &&
13516 "Cannot set masked compare for this operation");
13518 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13520 bool Unsigned = false;
13523 switch (SetCCOpcode) {
13524 default: llvm_unreachable("Unexpected SETCC condition");
13525 case ISD::SETNE: SSECC = 4; break;
13526 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
13527 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13528 case ISD::SETLT: Swap = true; //fall-through
13529 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
13530 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13531 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13532 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
13533 case ISD::SETULE: Unsigned = true; //fall-through
13534 case ISD::SETLE: SSECC = 2; break;
13538 std::swap(Op0, Op1);
13540 return DAG.getNode(Opc, dl, VT, Op0, Op1);
13541 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13542 return DAG.getNode(Opc, dl, VT, Op0, Op1,
13543 DAG.getConstant(SSECC, dl, MVT::i8));
13546 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13547 /// operand \p Op1. If non-trivial (for example because it's not constant)
13548 /// return an empty value.
13549 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13551 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13555 MVT VT = Op1.getSimpleValueType();
13556 MVT EVT = VT.getVectorElementType();
13557 unsigned n = VT.getVectorNumElements();
13558 SmallVector<SDValue, 8> ULTOp1;
13560 for (unsigned i = 0; i < n; ++i) {
13561 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13562 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13565 // Avoid underflow.
13566 APInt Val = Elt->getAPIntValue();
13570 ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
13573 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13576 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13577 SelectionDAG &DAG) {
13578 SDValue Op0 = Op.getOperand(0);
13579 SDValue Op1 = Op.getOperand(1);
13580 SDValue CC = Op.getOperand(2);
13581 MVT VT = Op.getSimpleValueType();
13582 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13583 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13588 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13589 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13592 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13593 unsigned Opc = X86ISD::CMPP;
13594 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13595 assert(VT.getVectorNumElements() <= 16);
13596 Opc = X86ISD::CMPM;
13598 // In the two special cases we can't handle, emit two comparisons.
13601 unsigned CombineOpc;
13602 if (SetCCOpcode == ISD::SETUEQ) {
13603 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13605 assert(SetCCOpcode == ISD::SETONE);
13606 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13609 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13610 DAG.getConstant(CC0, dl, MVT::i8));
13611 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13612 DAG.getConstant(CC1, dl, MVT::i8));
13613 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13615 // Handle all other FP comparisons here.
13616 return DAG.getNode(Opc, dl, VT, Op0, Op1,
13617 DAG.getConstant(SSECC, dl, MVT::i8));
13620 // Break 256-bit integer vector compare into smaller ones.
13621 if (VT.is256BitVector() && !Subtarget->hasInt256())
13622 return Lower256IntVSETCC(Op, DAG);
13624 EVT OpVT = Op1.getValueType();
13625 if (OpVT.getVectorElementType() == MVT::i1)
13626 return LowerBoolVSETCC_AVX512(Op, DAG);
13628 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13629 if (Subtarget->hasAVX512()) {
13630 if (Op1.getValueType().is512BitVector() ||
13631 (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13632 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13633 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13635 // In AVX-512 architecture setcc returns mask with i1 elements,
13636 // But there is no compare instruction for i8 and i16 elements in KNL.
13637 // We are not talking about 512-bit operands in this case, these
13638 // types are illegal.
13640 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13641 OpVT.getVectorElementType().getSizeInBits() >= 8))
13642 return DAG.getNode(ISD::TRUNCATE, dl, VT,
13643 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13646 // We are handling one of the integer comparisons here. Since SSE only has
13647 // GT and EQ comparisons for integer, swapping operands and multiple
13648 // operations may be required for some comparisons.
13650 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13651 bool Subus = false;
13653 switch (SetCCOpcode) {
13654 default: llvm_unreachable("Unexpected SETCC condition");
13655 case ISD::SETNE: Invert = true;
13656 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
13657 case ISD::SETLT: Swap = true;
13658 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
13659 case ISD::SETGE: Swap = true;
13660 case ISD::SETLE: Opc = X86ISD::PCMPGT;
13661 Invert = true; break;
13662 case ISD::SETULT: Swap = true;
13663 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13664 FlipSigns = true; break;
13665 case ISD::SETUGE: Swap = true;
13666 case ISD::SETULE: Opc = X86ISD::PCMPGT;
13667 FlipSigns = true; Invert = true; break;
13670 // Special case: Use min/max operations for SETULE/SETUGE
13671 MVT VET = VT.getVectorElementType();
13673 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13674 || (Subtarget->hasSSE2() && (VET == MVT::i8));
13677 switch (SetCCOpcode) {
13679 case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
13680 case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
13683 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13686 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13687 if (!MinMax && hasSubus) {
13688 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13690 // t = psubus Op0, Op1
13691 // pcmpeq t, <0..0>
13692 switch (SetCCOpcode) {
13694 case ISD::SETULT: {
13695 // If the comparison is against a constant we can turn this into a
13696 // setule. With psubus, setule does not require a swap. This is
13697 // beneficial because the constant in the register is no longer
13698 // destructed as the destination so it can be hoisted out of a loop.
13699 // Only do this pre-AVX since vpcmp* is no longer destructive.
13700 if (Subtarget->hasAVX())
13702 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13703 if (ULEOp1.getNode()) {
13705 Subus = true; Invert = false; Swap = false;
13709 // Psubus is better than flip-sign because it requires no inversion.
13710 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
13711 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13715 Opc = X86ISD::SUBUS;
13721 std::swap(Op0, Op1);
13723 // Check that the operation in question is available (most are plain SSE2,
13724 // but PCMPGTQ and PCMPEQQ have different requirements).
13725 if (VT == MVT::v2i64) {
13726 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13727 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13729 // First cast everything to the right type.
13730 Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13731 Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13733 // Since SSE has no unsigned integer comparisons, we need to flip the sign
13734 // bits of the inputs before performing those operations. The lower
13735 // compare is always unsigned.
13738 SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
13740 SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
13741 SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
13742 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13743 Sign, Zero, Sign, Zero);
13745 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13746 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13748 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13749 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13750 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13752 // Create masks for only the low parts/high parts of the 64 bit integers.
13753 static const int MaskHi[] = { 1, 1, 3, 3 };
13754 static const int MaskLo[] = { 0, 0, 2, 2 };
13755 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13756 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13757 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13759 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13760 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13763 Result = DAG.getNOT(dl, Result, MVT::v4i32);
13765 return DAG.getBitcast(VT, Result);
13768 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13769 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13770 // pcmpeqd + pshufd + pand.
13771 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13773 // First cast everything to the right type.
13774 Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13775 Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13778 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13780 // Make sure the lower and upper halves are both all-ones.
13781 static const int Mask[] = { 1, 0, 3, 2 };
13782 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13783 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13786 Result = DAG.getNOT(dl, Result, MVT::v4i32);
13788 return DAG.getBitcast(VT, Result);
13792 // Since SSE has no unsigned integer comparisons, we need to flip the sign
13793 // bits of the inputs before performing those operations.
13795 EVT EltVT = VT.getVectorElementType();
13796 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
13798 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13799 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13802 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13804 // If the logical-not of the result is required, perform that now.
13806 Result = DAG.getNOT(dl, Result, VT);
13809 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13812 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13813 getZeroVector(VT, Subtarget, DAG, dl));
13818 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13820 MVT VT = Op.getSimpleValueType();
13822 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13824 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13825 && "SetCC type must be 8-bit or 1-bit integer");
13826 SDValue Op0 = Op.getOperand(0);
13827 SDValue Op1 = Op.getOperand(1);
13829 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13831 // Optimize to BT if possible.
13832 // Lower (X & (1 << N)) == 0 to BT(X, N).
13833 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13834 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13835 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13836 Op1.getOpcode() == ISD::Constant &&
13837 cast<ConstantSDNode>(Op1)->isNullValue() &&
13838 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13839 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13840 if (NewSetCC.getNode()) {
13842 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13847 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
13849 if (Op1.getOpcode() == ISD::Constant &&
13850 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13851 cast<ConstantSDNode>(Op1)->isNullValue()) &&
13852 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13854 // If the input is a setcc, then reuse the input setcc or use a new one with
13855 // the inverted condition.
13856 if (Op0.getOpcode() == X86ISD::SETCC) {
13857 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13858 bool Invert = (CC == ISD::SETNE) ^
13859 cast<ConstantSDNode>(Op1)->isNullValue();
13863 CCode = X86::GetOppositeBranchCondition(CCode);
13864 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13865 DAG.getConstant(CCode, dl, MVT::i8),
13866 Op0.getOperand(1));
13868 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13872 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13873 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13874 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13876 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13877 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
13880 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13881 unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
13882 if (X86CC == X86::COND_INVALID)
13885 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13886 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13887 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13888 DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
13890 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13894 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13895 static bool isX86LogicalCmp(SDValue Op) {
13896 unsigned Opc = Op.getNode()->getOpcode();
13897 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13898 Opc == X86ISD::SAHF)
13900 if (Op.getResNo() == 1 &&
13901 (Opc == X86ISD::ADD ||
13902 Opc == X86ISD::SUB ||
13903 Opc == X86ISD::ADC ||
13904 Opc == X86ISD::SBB ||
13905 Opc == X86ISD::SMUL ||
13906 Opc == X86ISD::UMUL ||
13907 Opc == X86ISD::INC ||
13908 Opc == X86ISD::DEC ||
13909 Opc == X86ISD::OR ||
13910 Opc == X86ISD::XOR ||
13911 Opc == X86ISD::AND))
13914 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13920 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13921 if (V.getOpcode() != ISD::TRUNCATE)
13924 SDValue VOp0 = V.getOperand(0);
13925 unsigned InBits = VOp0.getValueSizeInBits();
13926 unsigned Bits = V.getValueSizeInBits();
13927 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13930 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13931 bool addTest = true;
13932 SDValue Cond = Op.getOperand(0);
13933 SDValue Op1 = Op.getOperand(1);
13934 SDValue Op2 = Op.getOperand(2);
13936 EVT VT = Op1.getValueType();
13939 // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13940 // are available or VBLENDV if AVX is available.
13941 // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
13942 if (Cond.getOpcode() == ISD::SETCC &&
13943 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13944 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13945 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13946 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13947 int SSECC = translateX86FSETCC(
13948 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13951 if (Subtarget->hasAVX512()) {
13952 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13953 DAG.getConstant(SSECC, DL, MVT::i8));
13954 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13957 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13958 DAG.getConstant(SSECC, DL, MVT::i8));
13960 // If we have AVX, we can use a variable vector select (VBLENDV) instead
13961 // of 3 logic instructions for size savings and potentially speed.
13962 // Unfortunately, there is no scalar form of VBLENDV.
13964 // If either operand is a constant, don't try this. We can expect to
13965 // optimize away at least one of the logic instructions later in that
13966 // case, so that sequence would be faster than a variable blend.
13968 // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
13969 // uses XMM0 as the selection register. That may need just as many
13970 // instructions as the AND/ANDN/OR sequence due to register moves, so
13973 if (Subtarget->hasAVX() &&
13974 !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
13976 // Convert to vectors, do a VSELECT, and convert back to scalar.
13977 // All of the conversions should be optimized away.
13979 EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
13980 SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
13981 SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
13982 SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
13984 EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
13985 VCmp = DAG.getBitcast(VCmpVT, VCmp);
13987 SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
13989 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
13990 VSel, DAG.getIntPtrConstant(0, DL));
13992 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13993 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13994 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13998 if (VT.isVector() && VT.getScalarType() == MVT::i1) {
14000 if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
14001 Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
14002 else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
14003 Op1Scalar = Op1.getOperand(0);
14005 if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
14006 Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
14007 else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
14008 Op2Scalar = Op2.getOperand(0);
14009 if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
14010 SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
14011 Op1Scalar.getValueType(),
14012 Cond, Op1Scalar, Op2Scalar);
14013 if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
14014 return DAG.getBitcast(VT, newSelect);
14015 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
14016 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
14017 DAG.getIntPtrConstant(0, DL));
14021 if (VT == MVT::v4i1 || VT == MVT::v2i1) {
14022 SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
14023 Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14024 DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
14025 Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14026 DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
14027 SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
14029 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
14032 if (Cond.getOpcode() == ISD::SETCC) {
14033 SDValue NewCond = LowerSETCC(Cond, DAG);
14034 if (NewCond.getNode())
14038 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
14039 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
14040 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
14041 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
14042 if (Cond.getOpcode() == X86ISD::SETCC &&
14043 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
14044 isZero(Cond.getOperand(1).getOperand(1))) {
14045 SDValue Cmp = Cond.getOperand(1);
14047 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
14049 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
14050 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
14051 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
14053 SDValue CmpOp0 = Cmp.getOperand(0);
14054 // Apply further optimizations for special cases
14055 // (select (x != 0), -1, 0) -> neg & sbb
14056 // (select (x == 0), 0, -1) -> neg & sbb
14057 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
14058 if (YC->isNullValue() &&
14059 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
14060 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
14061 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
14062 DAG.getConstant(0, DL,
14063 CmpOp0.getValueType()),
14065 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14066 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14067 SDValue(Neg.getNode(), 1));
14071 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
14072 CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
14073 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14075 SDValue Res = // Res = 0 or -1.
14076 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14077 DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
14079 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
14080 Res = DAG.getNOT(DL, Res, Res.getValueType());
14082 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
14083 if (!N2C || !N2C->isNullValue())
14084 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
14089 // Look past (and (setcc_carry (cmp ...)), 1).
14090 if (Cond.getOpcode() == ISD::AND &&
14091 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14092 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14093 if (C && C->getAPIntValue() == 1)
14094 Cond = Cond.getOperand(0);
14097 // If condition flag is set by a X86ISD::CMP, then use it as the condition
14098 // setting operand in place of the X86ISD::SETCC.
14099 unsigned CondOpcode = Cond.getOpcode();
14100 if (CondOpcode == X86ISD::SETCC ||
14101 CondOpcode == X86ISD::SETCC_CARRY) {
14102 CC = Cond.getOperand(0);
14104 SDValue Cmp = Cond.getOperand(1);
14105 unsigned Opc = Cmp.getOpcode();
14106 MVT VT = Op.getSimpleValueType();
14108 bool IllegalFPCMov = false;
14109 if (VT.isFloatingPoint() && !VT.isVector() &&
14110 !isScalarFPTypeInSSEReg(VT)) // FPStack?
14111 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
14113 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
14114 Opc == X86ISD::BT) { // FIXME
14118 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14119 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14120 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14121 Cond.getOperand(0).getValueType() != MVT::i8)) {
14122 SDValue LHS = Cond.getOperand(0);
14123 SDValue RHS = Cond.getOperand(1);
14124 unsigned X86Opcode;
14127 switch (CondOpcode) {
14128 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14129 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14130 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14131 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14132 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14133 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14134 default: llvm_unreachable("unexpected overflowing operator");
14136 if (CondOpcode == ISD::UMULO)
14137 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14140 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14142 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
14144 if (CondOpcode == ISD::UMULO)
14145 Cond = X86Op.getValue(2);
14147 Cond = X86Op.getValue(1);
14149 CC = DAG.getConstant(X86Cond, DL, MVT::i8);
14154 // Look past the truncate if the high bits are known zero.
14155 if (isTruncWithZeroHighBitsInput(Cond, DAG))
14156 Cond = Cond.getOperand(0);
14158 // We know the result of AND is compared against zero. Try to match
14160 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14161 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
14162 if (NewSetCC.getNode()) {
14163 CC = NewSetCC.getOperand(0);
14164 Cond = NewSetCC.getOperand(1);
14171 CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
14172 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
14175 // a < b ? -1 : 0 -> RES = ~setcc_carry
14176 // a < b ? 0 : -1 -> RES = setcc_carry
14177 // a >= b ? -1 : 0 -> RES = setcc_carry
14178 // a >= b ? 0 : -1 -> RES = ~setcc_carry
14179 if (Cond.getOpcode() == X86ISD::SUB) {
14180 Cond = ConvertCmpIfNecessary(Cond, DAG);
14181 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
14183 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
14184 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
14185 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14186 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14188 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
14189 return DAG.getNOT(DL, Res, Res.getValueType());
14194 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
14195 // widen the cmov and push the truncate through. This avoids introducing a new
14196 // branch during isel and doesn't add any extensions.
14197 if (Op.getValueType() == MVT::i8 &&
14198 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
14199 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
14200 if (T1.getValueType() == T2.getValueType() &&
14201 // Blacklist CopyFromReg to avoid partial register stalls.
14202 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
14203 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
14204 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
14205 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
14209 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
14210 // condition is true.
14211 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
14212 SDValue Ops[] = { Op2, Op1, CC, Cond };
14213 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
14216 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
14217 const X86Subtarget *Subtarget,
14218 SelectionDAG &DAG) {
14219 MVT VT = Op->getSimpleValueType(0);
14220 SDValue In = Op->getOperand(0);
14221 MVT InVT = In.getSimpleValueType();
14222 MVT VTElt = VT.getVectorElementType();
14223 MVT InVTElt = InVT.getVectorElementType();
14227 if ((InVTElt == MVT::i1) &&
14228 (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
14229 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
14231 ((Subtarget->hasBWI() && VT.is512BitVector() &&
14232 VTElt.getSizeInBits() <= 16)) ||
14234 ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
14235 VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
14237 ((Subtarget->hasDQI() && VT.is512BitVector() &&
14238 VTElt.getSizeInBits() >= 32))))
14239 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14241 unsigned int NumElts = VT.getVectorNumElements();
14243 if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
14246 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
14247 if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
14248 return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
14249 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14252 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
14253 MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
14255 DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
14258 DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
14260 SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
14261 if (VT.is512BitVector())
14263 return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
14266 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
14267 const X86Subtarget *Subtarget,
14268 SelectionDAG &DAG) {
14269 SDValue In = Op->getOperand(0);
14270 MVT VT = Op->getSimpleValueType(0);
14271 MVT InVT = In.getSimpleValueType();
14272 assert(VT.getSizeInBits() == InVT.getSizeInBits());
14274 MVT InSVT = InVT.getScalarType();
14275 assert(VT.getScalarType().getScalarSizeInBits() > InSVT.getScalarSizeInBits());
14277 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
14279 if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
14284 // SSE41 targets can use the pmovsx* instructions directly.
14285 if (Subtarget->hasSSE41())
14286 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14288 // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
14292 // As SRAI is only available on i16/i32 types, we expand only up to i32
14293 // and handle i64 separately.
14294 while (CurrVT != VT && CurrVT.getScalarType() != MVT::i32) {
14295 Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
14296 MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
14297 CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
14298 Curr = DAG.getBitcast(CurrVT, Curr);
14301 SDValue SignExt = Curr;
14302 if (CurrVT != InVT) {
14303 unsigned SignExtShift =
14304 CurrVT.getScalarSizeInBits() - InSVT.getScalarSizeInBits();
14305 SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14306 DAG.getConstant(SignExtShift, dl, MVT::i8));
14312 if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
14313 SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14314 DAG.getConstant(31, dl, MVT::i8));
14315 SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
14316 return DAG.getBitcast(VT, Ext);
14322 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14323 SelectionDAG &DAG) {
14324 MVT VT = Op->getSimpleValueType(0);
14325 SDValue In = Op->getOperand(0);
14326 MVT InVT = In.getSimpleValueType();
14329 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
14330 return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
14332 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
14333 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
14334 (VT != MVT::v16i16 || InVT != MVT::v16i8))
14337 if (Subtarget->hasInt256())
14338 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14340 // Optimize vectors in AVX mode
14341 // Sign extend v8i16 to v8i32 and
14344 // Divide input vector into two parts
14345 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
14346 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14347 // concat the vectors to original VT
14349 unsigned NumElems = InVT.getVectorNumElements();
14350 SDValue Undef = DAG.getUNDEF(InVT);
14352 SmallVector<int,8> ShufMask1(NumElems, -1);
14353 for (unsigned i = 0; i != NumElems/2; ++i)
14356 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
14358 SmallVector<int,8> ShufMask2(NumElems, -1);
14359 for (unsigned i = 0; i != NumElems/2; ++i)
14360 ShufMask2[i] = i + NumElems/2;
14362 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
14364 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
14365 VT.getVectorNumElements()/2);
14367 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
14368 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
14370 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14373 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
14374 // may emit an illegal shuffle but the expansion is still better than scalar
14375 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
14376 // we'll emit a shuffle and a arithmetic shift.
14377 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
14378 // TODO: It is possible to support ZExt by zeroing the undef values during
14379 // the shuffle phase or after the shuffle.
14380 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
14381 SelectionDAG &DAG) {
14382 MVT RegVT = Op.getSimpleValueType();
14383 assert(RegVT.isVector() && "We only custom lower vector sext loads.");
14384 assert(RegVT.isInteger() &&
14385 "We only custom lower integer vector sext loads.");
14387 // Nothing useful we can do without SSE2 shuffles.
14388 assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
14390 LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
14392 EVT MemVT = Ld->getMemoryVT();
14393 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14394 unsigned RegSz = RegVT.getSizeInBits();
14396 ISD::LoadExtType Ext = Ld->getExtensionType();
14398 assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
14399 && "Only anyext and sext are currently implemented.");
14400 assert(MemVT != RegVT && "Cannot extend to the same type");
14401 assert(MemVT.isVector() && "Must load a vector from memory");
14403 unsigned NumElems = RegVT.getVectorNumElements();
14404 unsigned MemSz = MemVT.getSizeInBits();
14405 assert(RegSz > MemSz && "Register size must be greater than the mem size");
14407 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
14408 // The only way in which we have a legal 256-bit vector result but not the
14409 // integer 256-bit operations needed to directly lower a sextload is if we
14410 // have AVX1 but not AVX2. In that case, we can always emit a sextload to
14411 // a 128-bit vector and a normal sign_extend to 256-bits that should get
14412 // correctly legalized. We do this late to allow the canonical form of
14413 // sextload to persist throughout the rest of the DAG combiner -- it wants
14414 // to fold together any extensions it can, and so will fuse a sign_extend
14415 // of an sextload into a sextload targeting a wider value.
14417 if (MemSz == 128) {
14418 // Just switch this to a normal load.
14419 assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
14420 "it must be a legal 128-bit vector "
14422 Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
14423 Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
14424 Ld->isInvariant(), Ld->getAlignment());
14426 assert(MemSz < 128 &&
14427 "Can't extend a type wider than 128 bits to a 256 bit vector!");
14428 // Do an sext load to a 128-bit vector type. We want to use the same
14429 // number of elements, but elements half as wide. This will end up being
14430 // recursively lowered by this routine, but will succeed as we definitely
14431 // have all the necessary features if we're using AVX1.
14433 EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
14434 EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
14436 DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
14437 Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
14438 Ld->isNonTemporal(), Ld->isInvariant(),
14439 Ld->getAlignment());
14442 // Replace chain users with the new chain.
14443 assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
14444 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
14446 // Finally, do a normal sign-extend to the desired register.
14447 return DAG.getSExtOrTrunc(Load, dl, RegVT);
14450 // All sizes must be a power of two.
14451 assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
14452 "Non-power-of-two elements are not custom lowered!");
14454 // Attempt to load the original value using scalar loads.
14455 // Find the largest scalar type that divides the total loaded size.
14456 MVT SclrLoadTy = MVT::i8;
14457 for (MVT Tp : MVT::integer_valuetypes()) {
14458 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14463 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14464 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14466 SclrLoadTy = MVT::f64;
14468 // Calculate the number of scalar loads that we need to perform
14469 // in order to load our vector from memory.
14470 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14472 assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
14473 "Can only lower sext loads with a single scalar load!");
14475 unsigned loadRegZize = RegSz;
14476 if (Ext == ISD::SEXTLOAD && RegSz >= 256)
14479 // Represent our vector as a sequence of elements which are the
14480 // largest scalar that we can load.
14481 EVT LoadUnitVecVT = EVT::getVectorVT(
14482 *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14484 // Represent the data using the same element type that is stored in
14485 // memory. In practice, we ''widen'' MemVT.
14487 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14488 loadRegZize / MemVT.getScalarType().getSizeInBits());
14490 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14491 "Invalid vector type");
14493 // We can't shuffle using an illegal type.
14494 assert(TLI.isTypeLegal(WideVecVT) &&
14495 "We only lower types that form legal widened vector types");
14497 SmallVector<SDValue, 8> Chains;
14498 SDValue Ptr = Ld->getBasePtr();
14499 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
14500 TLI.getPointerTy(DAG.getDataLayout()));
14501 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14503 for (unsigned i = 0; i < NumLoads; ++i) {
14504 // Perform a single load.
14505 SDValue ScalarLoad =
14506 DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14507 Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14508 Ld->getAlignment());
14509 Chains.push_back(ScalarLoad.getValue(1));
14510 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14511 // another round of DAGCombining.
14513 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14515 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14516 ScalarLoad, DAG.getIntPtrConstant(i, dl));
14518 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14521 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14523 // Bitcast the loaded value to a vector of the original element type, in
14524 // the size of the target vector type.
14525 SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
14526 unsigned SizeRatio = RegSz / MemSz;
14528 if (Ext == ISD::SEXTLOAD) {
14529 // If we have SSE4.1, we can directly emit a VSEXT node.
14530 if (Subtarget->hasSSE41()) {
14531 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14532 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14536 // Otherwise we'll shuffle the small elements in the high bits of the
14537 // larger type and perform an arithmetic shift. If the shift is not legal
14538 // it's better to scalarize.
14539 assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14540 "We can't implement a sext load without an arithmetic right shift!");
14542 // Redistribute the loaded elements into the different locations.
14543 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14544 for (unsigned i = 0; i != NumElems; ++i)
14545 ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14547 SDValue Shuff = DAG.getVectorShuffle(
14548 WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14550 Shuff = DAG.getBitcast(RegVT, Shuff);
14552 // Build the arithmetic shift.
14553 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14554 MemVT.getVectorElementType().getSizeInBits();
14556 DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
14557 DAG.getConstant(Amt, dl, RegVT));
14559 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14563 // Redistribute the loaded elements into the different locations.
14564 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14565 for (unsigned i = 0; i != NumElems; ++i)
14566 ShuffleVec[i * SizeRatio] = i;
14568 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14569 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14571 // Bitcast to the requested type.
14572 Shuff = DAG.getBitcast(RegVT, Shuff);
14573 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14577 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14578 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14579 // from the AND / OR.
14580 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14581 Opc = Op.getOpcode();
14582 if (Opc != ISD::OR && Opc != ISD::AND)
14584 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14585 Op.getOperand(0).hasOneUse() &&
14586 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14587 Op.getOperand(1).hasOneUse());
14590 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14591 // 1 and that the SETCC node has a single use.
14592 static bool isXor1OfSetCC(SDValue Op) {
14593 if (Op.getOpcode() != ISD::XOR)
14595 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14596 if (N1C && N1C->getAPIntValue() == 1) {
14597 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14598 Op.getOperand(0).hasOneUse();
14603 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14604 bool addTest = true;
14605 SDValue Chain = Op.getOperand(0);
14606 SDValue Cond = Op.getOperand(1);
14607 SDValue Dest = Op.getOperand(2);
14610 bool Inverted = false;
14612 if (Cond.getOpcode() == ISD::SETCC) {
14613 // Check for setcc([su]{add,sub,mul}o == 0).
14614 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14615 isa<ConstantSDNode>(Cond.getOperand(1)) &&
14616 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14617 Cond.getOperand(0).getResNo() == 1 &&
14618 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14619 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14620 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14621 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14622 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14623 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14625 Cond = Cond.getOperand(0);
14627 SDValue NewCond = LowerSETCC(Cond, DAG);
14628 if (NewCond.getNode())
14633 // FIXME: LowerXALUO doesn't handle these!!
14634 else if (Cond.getOpcode() == X86ISD::ADD ||
14635 Cond.getOpcode() == X86ISD::SUB ||
14636 Cond.getOpcode() == X86ISD::SMUL ||
14637 Cond.getOpcode() == X86ISD::UMUL)
14638 Cond = LowerXALUO(Cond, DAG);
14641 // Look pass (and (setcc_carry (cmp ...)), 1).
14642 if (Cond.getOpcode() == ISD::AND &&
14643 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14644 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14645 if (C && C->getAPIntValue() == 1)
14646 Cond = Cond.getOperand(0);
14649 // If condition flag is set by a X86ISD::CMP, then use it as the condition
14650 // setting operand in place of the X86ISD::SETCC.
14651 unsigned CondOpcode = Cond.getOpcode();
14652 if (CondOpcode == X86ISD::SETCC ||
14653 CondOpcode == X86ISD::SETCC_CARRY) {
14654 CC = Cond.getOperand(0);
14656 SDValue Cmp = Cond.getOperand(1);
14657 unsigned Opc = Cmp.getOpcode();
14658 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14659 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14663 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14667 // These can only come from an arithmetic instruction with overflow,
14668 // e.g. SADDO, UADDO.
14669 Cond = Cond.getNode()->getOperand(1);
14675 CondOpcode = Cond.getOpcode();
14676 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14677 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14678 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14679 Cond.getOperand(0).getValueType() != MVT::i8)) {
14680 SDValue LHS = Cond.getOperand(0);
14681 SDValue RHS = Cond.getOperand(1);
14682 unsigned X86Opcode;
14685 // Keep this in sync with LowerXALUO, otherwise we might create redundant
14686 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14688 switch (CondOpcode) {
14689 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14691 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14693 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14696 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14697 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14699 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14701 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14704 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14705 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14706 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14707 default: llvm_unreachable("unexpected overflowing operator");
14710 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14711 if (CondOpcode == ISD::UMULO)
14712 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14715 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14717 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14719 if (CondOpcode == ISD::UMULO)
14720 Cond = X86Op.getValue(2);
14722 Cond = X86Op.getValue(1);
14724 CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14728 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14729 SDValue Cmp = Cond.getOperand(0).getOperand(1);
14730 if (CondOpc == ISD::OR) {
14731 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14732 // two branches instead of an explicit OR instruction with a
14734 if (Cmp == Cond.getOperand(1).getOperand(1) &&
14735 isX86LogicalCmp(Cmp)) {
14736 CC = Cond.getOperand(0).getOperand(0);
14737 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14738 Chain, Dest, CC, Cmp);
14739 CC = Cond.getOperand(1).getOperand(0);
14743 } else { // ISD::AND
14744 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14745 // two branches instead of an explicit AND instruction with a
14746 // separate test. However, we only do this if this block doesn't
14747 // have a fall-through edge, because this requires an explicit
14748 // jmp when the condition is false.
14749 if (Cmp == Cond.getOperand(1).getOperand(1) &&
14750 isX86LogicalCmp(Cmp) &&
14751 Op.getNode()->hasOneUse()) {
14752 X86::CondCode CCode =
14753 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14754 CCode = X86::GetOppositeBranchCondition(CCode);
14755 CC = DAG.getConstant(CCode, dl, MVT::i8);
14756 SDNode *User = *Op.getNode()->use_begin();
14757 // Look for an unconditional branch following this conditional branch.
14758 // We need this because we need to reverse the successors in order
14759 // to implement FCMP_OEQ.
14760 if (User->getOpcode() == ISD::BR) {
14761 SDValue FalseBB = User->getOperand(1);
14763 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14764 assert(NewBR == User);
14768 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14769 Chain, Dest, CC, Cmp);
14770 X86::CondCode CCode =
14771 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14772 CCode = X86::GetOppositeBranchCondition(CCode);
14773 CC = DAG.getConstant(CCode, dl, MVT::i8);
14779 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14780 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14781 // It should be transformed during dag combiner except when the condition
14782 // is set by a arithmetics with overflow node.
14783 X86::CondCode CCode =
14784 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14785 CCode = X86::GetOppositeBranchCondition(CCode);
14786 CC = DAG.getConstant(CCode, dl, MVT::i8);
14787 Cond = Cond.getOperand(0).getOperand(1);
14789 } else if (Cond.getOpcode() == ISD::SETCC &&
14790 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14791 // For FCMP_OEQ, we can emit
14792 // two branches instead of an explicit AND instruction with a
14793 // separate test. However, we only do this if this block doesn't
14794 // have a fall-through edge, because this requires an explicit
14795 // jmp when the condition is false.
14796 if (Op.getNode()->hasOneUse()) {
14797 SDNode *User = *Op.getNode()->use_begin();
14798 // Look for an unconditional branch following this conditional branch.
14799 // We need this because we need to reverse the successors in order
14800 // to implement FCMP_OEQ.
14801 if (User->getOpcode() == ISD::BR) {
14802 SDValue FalseBB = User->getOperand(1);
14804 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14805 assert(NewBR == User);
14809 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14810 Cond.getOperand(0), Cond.getOperand(1));
14811 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14812 CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14813 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14814 Chain, Dest, CC, Cmp);
14815 CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
14820 } else if (Cond.getOpcode() == ISD::SETCC &&
14821 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14822 // For FCMP_UNE, we can emit
14823 // two branches instead of an explicit AND instruction with a
14824 // separate test. However, we only do this if this block doesn't
14825 // have a fall-through edge, because this requires an explicit
14826 // jmp when the condition is false.
14827 if (Op.getNode()->hasOneUse()) {
14828 SDNode *User = *Op.getNode()->use_begin();
14829 // Look for an unconditional branch following this conditional branch.
14830 // We need this because we need to reverse the successors in order
14831 // to implement FCMP_UNE.
14832 if (User->getOpcode() == ISD::BR) {
14833 SDValue FalseBB = User->getOperand(1);
14835 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14836 assert(NewBR == User);
14839 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14840 Cond.getOperand(0), Cond.getOperand(1));
14841 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14842 CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14843 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14844 Chain, Dest, CC, Cmp);
14845 CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
14855 // Look pass the truncate if the high bits are known zero.
14856 if (isTruncWithZeroHighBitsInput(Cond, DAG))
14857 Cond = Cond.getOperand(0);
14859 // We know the result of AND is compared against zero. Try to match
14861 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14862 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14863 if (NewSetCC.getNode()) {
14864 CC = NewSetCC.getOperand(0);
14865 Cond = NewSetCC.getOperand(1);
14872 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14873 CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14874 Cond = EmitTest(Cond, X86Cond, dl, DAG);
14876 Cond = ConvertCmpIfNecessary(Cond, DAG);
14877 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14878 Chain, Dest, CC, Cond);
14881 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14882 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14883 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14884 // that the guard pages used by the OS virtual memory manager are allocated in
14885 // correct sequence.
14887 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14888 SelectionDAG &DAG) const {
14889 MachineFunction &MF = DAG.getMachineFunction();
14890 bool SplitStack = MF.shouldSplitStack();
14891 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
14896 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14897 SDNode* Node = Op.getNode();
14899 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14900 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14901 " not tell us which reg is the stack pointer!");
14902 EVT VT = Node->getValueType(0);
14903 SDValue Tmp1 = SDValue(Node, 0);
14904 SDValue Tmp2 = SDValue(Node, 1);
14905 SDValue Tmp3 = Node->getOperand(2);
14906 SDValue Chain = Tmp1.getOperand(0);
14908 // Chain the dynamic stack allocation so that it doesn't modify the stack
14909 // pointer when other instructions are using the stack.
14910 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
14913 SDValue Size = Tmp2.getOperand(1);
14914 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14915 Chain = SP.getValue(1);
14916 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14917 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
14918 unsigned StackAlign = TFI.getStackAlignment();
14919 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14920 if (Align > StackAlign)
14921 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14922 DAG.getConstant(-(uint64_t)Align, dl, VT));
14923 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14925 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
14926 DAG.getIntPtrConstant(0, dl, true), SDValue(),
14929 SDValue Ops[2] = { Tmp1, Tmp2 };
14930 return DAG.getMergeValues(Ops, dl);
14934 SDValue Chain = Op.getOperand(0);
14935 SDValue Size = Op.getOperand(1);
14936 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14937 EVT VT = Op.getNode()->getValueType(0);
14939 bool Is64Bit = Subtarget->is64Bit();
14940 MVT SPTy = getPointerTy(DAG.getDataLayout());
14943 MachineRegisterInfo &MRI = MF.getRegInfo();
14946 // The 64 bit implementation of segmented stacks needs to clobber both r10
14947 // r11. This makes it impossible to use it along with nested parameters.
14948 const Function *F = MF.getFunction();
14950 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14952 if (I->hasNestAttr())
14953 report_fatal_error("Cannot use segmented stacks with functions that "
14954 "have nested arguments.");
14957 const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
14958 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14959 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14960 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14961 DAG.getRegister(Vreg, SPTy));
14962 SDValue Ops1[2] = { Value, Chain };
14963 return DAG.getMergeValues(Ops1, dl);
14966 const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
14968 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14969 Flag = Chain.getValue(1);
14970 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14972 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14974 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
14975 unsigned SPReg = RegInfo->getStackRegister();
14976 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14977 Chain = SP.getValue(1);
14980 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14981 DAG.getConstant(-(uint64_t)Align, dl, VT));
14982 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14985 SDValue Ops1[2] = { SP, Chain };
14986 return DAG.getMergeValues(Ops1, dl);
14990 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14991 MachineFunction &MF = DAG.getMachineFunction();
14992 auto PtrVT = getPointerTy(MF.getDataLayout());
14993 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14995 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14998 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14999 // vastart just stores the address of the VarArgsFrameIndex slot into the
15000 // memory location argument.
15001 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15002 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
15003 MachinePointerInfo(SV), false, false, 0);
15007 // gp_offset (0 - 6 * 8)
15008 // fp_offset (48 - 48 + 8 * 16)
15009 // overflow_arg_area (point to parameters coming in memory).
15011 SmallVector<SDValue, 8> MemOps;
15012 SDValue FIN = Op.getOperand(1);
15014 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
15015 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
15017 FIN, MachinePointerInfo(SV), false, false, 0);
15018 MemOps.push_back(Store);
15021 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15022 Store = DAG.getStore(Op.getOperand(0), DL,
15023 DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
15025 FIN, MachinePointerInfo(SV, 4), false, false, 0);
15026 MemOps.push_back(Store);
15028 // Store ptr to overflow_arg_area
15029 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15030 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15031 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
15032 MachinePointerInfo(SV, 8),
15034 MemOps.push_back(Store);
15036 // Store ptr to reg_save_area.
15037 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(8, DL));
15038 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
15039 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
15040 MachinePointerInfo(SV, 16), false, false, 0);
15041 MemOps.push_back(Store);
15042 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
15045 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
15046 assert(Subtarget->is64Bit() &&
15047 "LowerVAARG only handles 64-bit va_arg!");
15048 assert((Subtarget->isTargetLinux() ||
15049 Subtarget->isTargetDarwin()) &&
15050 "Unhandled target in LowerVAARG");
15051 assert(Op.getNode()->getNumOperands() == 4);
15052 SDValue Chain = Op.getOperand(0);
15053 SDValue SrcPtr = Op.getOperand(1);
15054 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15055 unsigned Align = Op.getConstantOperandVal(3);
15058 EVT ArgVT = Op.getNode()->getValueType(0);
15059 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15060 uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
15063 // Decide which area this value should be read from.
15064 // TODO: Implement the AMD64 ABI in its entirety. This simple
15065 // selection mechanism works only for the basic types.
15066 if (ArgVT == MVT::f80) {
15067 llvm_unreachable("va_arg for f80 not yet implemented");
15068 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
15069 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
15070 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
15071 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
15073 llvm_unreachable("Unhandled argument type in LowerVAARG");
15076 if (ArgMode == 2) {
15077 // Sanity Check: Make sure using fp_offset makes sense.
15078 assert(!Subtarget->useSoftFloat() &&
15079 !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
15080 Attribute::NoImplicitFloat)) &&
15081 Subtarget->hasSSE1());
15084 // Insert VAARG_64 node into the DAG
15085 // VAARG_64 returns two values: Variable Argument Address, Chain
15086 SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
15087 DAG.getConstant(ArgMode, dl, MVT::i8),
15088 DAG.getConstant(Align, dl, MVT::i32)};
15089 SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
15090 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
15091 VTs, InstOps, MVT::i64,
15092 MachinePointerInfo(SV),
15094 /*Volatile=*/false,
15096 /*WriteMem=*/true);
15097 Chain = VAARG.getValue(1);
15099 // Load the next argument and return it
15100 return DAG.getLoad(ArgVT, dl,
15103 MachinePointerInfo(),
15104 false, false, false, 0);
15107 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
15108 SelectionDAG &DAG) {
15109 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
15110 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
15111 SDValue Chain = Op.getOperand(0);
15112 SDValue DstPtr = Op.getOperand(1);
15113 SDValue SrcPtr = Op.getOperand(2);
15114 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
15115 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15118 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
15119 DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
15121 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
15124 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
15125 // amount is a constant. Takes immediate version of shift as input.
15126 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
15127 SDValue SrcOp, uint64_t ShiftAmt,
15128 SelectionDAG &DAG) {
15129 MVT ElementType = VT.getVectorElementType();
15131 // Fold this packed shift into its first operand if ShiftAmt is 0.
15135 // Check for ShiftAmt >= element width
15136 if (ShiftAmt >= ElementType.getSizeInBits()) {
15137 if (Opc == X86ISD::VSRAI)
15138 ShiftAmt = ElementType.getSizeInBits() - 1;
15140 return DAG.getConstant(0, dl, VT);
15143 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
15144 && "Unknown target vector shift-by-constant node");
15146 // Fold this packed vector shift into a build vector if SrcOp is a
15147 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
15148 if (VT == SrcOp.getSimpleValueType() &&
15149 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
15150 SmallVector<SDValue, 8> Elts;
15151 unsigned NumElts = SrcOp->getNumOperands();
15152 ConstantSDNode *ND;
15155 default: llvm_unreachable(nullptr);
15156 case X86ISD::VSHLI:
15157 for (unsigned i=0; i!=NumElts; ++i) {
15158 SDValue CurrentOp = SrcOp->getOperand(i);
15159 if (CurrentOp->getOpcode() == ISD::UNDEF) {
15160 Elts.push_back(CurrentOp);
15163 ND = cast<ConstantSDNode>(CurrentOp);
15164 const APInt &C = ND->getAPIntValue();
15165 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
15168 case X86ISD::VSRLI:
15169 for (unsigned i=0; i!=NumElts; ++i) {
15170 SDValue CurrentOp = SrcOp->getOperand(i);
15171 if (CurrentOp->getOpcode() == ISD::UNDEF) {
15172 Elts.push_back(CurrentOp);
15175 ND = cast<ConstantSDNode>(CurrentOp);
15176 const APInt &C = ND->getAPIntValue();
15177 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
15180 case X86ISD::VSRAI:
15181 for (unsigned i=0; i!=NumElts; ++i) {
15182 SDValue CurrentOp = SrcOp->getOperand(i);
15183 if (CurrentOp->getOpcode() == ISD::UNDEF) {
15184 Elts.push_back(CurrentOp);
15187 ND = cast<ConstantSDNode>(CurrentOp);
15188 const APInt &C = ND->getAPIntValue();
15189 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
15194 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15197 return DAG.getNode(Opc, dl, VT, SrcOp,
15198 DAG.getConstant(ShiftAmt, dl, MVT::i8));
15201 // getTargetVShiftNode - Handle vector element shifts where the shift amount
15202 // may or may not be a constant. Takes immediate version of shift as input.
15203 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
15204 SDValue SrcOp, SDValue ShAmt,
15205 SelectionDAG &DAG) {
15206 MVT SVT = ShAmt.getSimpleValueType();
15207 assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
15209 // Catch shift-by-constant.
15210 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
15211 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
15212 CShAmt->getZExtValue(), DAG);
15214 // Change opcode to non-immediate version
15216 default: llvm_unreachable("Unknown target vector shift node");
15217 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
15218 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
15219 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
15222 const X86Subtarget &Subtarget =
15223 static_cast<const X86Subtarget &>(DAG.getSubtarget());
15224 if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
15225 ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
15226 // Let the shuffle legalizer expand this shift amount node.
15227 SDValue Op0 = ShAmt.getOperand(0);
15228 Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
15229 ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
15231 // Need to build a vector containing shift amount.
15232 // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
15233 SmallVector<SDValue, 4> ShOps;
15234 ShOps.push_back(ShAmt);
15235 if (SVT == MVT::i32) {
15236 ShOps.push_back(DAG.getConstant(0, dl, SVT));
15237 ShOps.push_back(DAG.getUNDEF(SVT));
15239 ShOps.push_back(DAG.getUNDEF(SVT));
15241 MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
15242 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
15245 // The return type has to be a 128-bit type with the same element
15246 // type as the input type.
15247 MVT EltVT = VT.getVectorElementType();
15248 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
15250 ShAmt = DAG.getBitcast(ShVT, ShAmt);
15251 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
15254 /// \brief Return (and \p Op, \p Mask) for compare instructions or
15255 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
15256 /// necessary casting or extending for \p Mask when lowering masking intrinsics
15257 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
15258 SDValue PreservedSrc,
15259 const X86Subtarget *Subtarget,
15260 SelectionDAG &DAG) {
15261 EVT VT = Op.getValueType();
15262 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
15263 MVT::i1, VT.getVectorNumElements());
15264 SDValue VMask = SDValue();
15265 unsigned OpcodeSelect = ISD::VSELECT;
15268 assert(MaskVT.isSimple() && "invalid mask type");
15270 if (isAllOnes(Mask))
15273 if (MaskVT.bitsGT(Mask.getValueType())) {
15274 EVT newMaskVT = EVT::getIntegerVT(*DAG.getContext(),
15275 MaskVT.getSizeInBits());
15276 VMask = DAG.getBitcast(MaskVT,
15277 DAG.getNode(ISD::ANY_EXTEND, dl, newMaskVT, Mask));
15279 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15280 Mask.getValueType().getSizeInBits());
15281 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15282 // are extracted by EXTRACT_SUBVECTOR.
15283 VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15284 DAG.getBitcast(BitcastVT, Mask),
15285 DAG.getIntPtrConstant(0, dl));
15288 switch (Op.getOpcode()) {
15290 case X86ISD::PCMPEQM:
15291 case X86ISD::PCMPGTM:
15293 case X86ISD::CMPMU:
15294 return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
15295 case X86ISD::VTRUNC:
15296 case X86ISD::VTRUNCS:
15297 case X86ISD::VTRUNCUS:
15298 // We can't use ISD::VSELECT here because it is not always "Legal"
15299 // for the destination type. For example vpmovqb require only AVX512
15300 // and vselect that can operate on byte element type require BWI
15301 OpcodeSelect = X86ISD::SELECT;
15304 if (PreservedSrc.getOpcode() == ISD::UNDEF)
15305 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15306 return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
15309 /// \brief Creates an SDNode for a predicated scalar operation.
15310 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
15311 /// The mask is coming as MVT::i8 and it should be truncated
15312 /// to MVT::i1 while lowering masking intrinsics.
15313 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
15314 /// "X86select" instead of "vselect". We just can't create the "vselect" node
15315 /// for a scalar instruction.
15316 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
15317 SDValue PreservedSrc,
15318 const X86Subtarget *Subtarget,
15319 SelectionDAG &DAG) {
15320 if (isAllOnes(Mask))
15323 EVT VT = Op.getValueType();
15325 // The mask should be of type MVT::i1
15326 SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
15328 if (PreservedSrc.getOpcode() == ISD::UNDEF)
15329 PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15330 return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
15333 static int getSEHRegistrationNodeSize(const Function *Fn) {
15334 if (!Fn->hasPersonalityFn())
15335 report_fatal_error(
15336 "querying registration node size for function without personality");
15337 // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
15338 // WinEHStatePass for the full struct definition.
15339 switch (classifyEHPersonality(Fn->getPersonalityFn())) {
15340 case EHPersonality::MSVC_X86SEH: return 24;
15341 case EHPersonality::MSVC_CXX: return 16;
15344 report_fatal_error("can only recover FP for MSVC EH personality functions");
15347 /// When the 32-bit MSVC runtime transfers control to us, either to an outlined
15348 /// function or when returning to a parent frame after catching an exception, we
15349 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
15350 /// Here's the math:
15351 /// RegNodeBase = EntryEBP - RegNodeSize
15352 /// ParentFP = RegNodeBase - RegNodeFrameOffset
15353 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
15354 /// subtracting the offset (negative on x86) takes us back to the parent FP.
15355 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
15356 SDValue EntryEBP) {
15357 MachineFunction &MF = DAG.getMachineFunction();
15360 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15361 MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
15363 // It's possible that the parent function no longer has a personality function
15364 // if the exceptional code was optimized away, in which case we just return
15365 // the incoming EBP.
15366 if (!Fn->hasPersonalityFn())
15369 int RegNodeSize = getSEHRegistrationNodeSize(Fn);
15371 // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
15373 MCSymbol *OffsetSym =
15374 MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
15375 GlobalValue::getRealLinkageName(Fn->getName()));
15376 SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
15377 SDValue RegNodeFrameOffset =
15378 DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
15380 // RegNodeBase = EntryEBP - RegNodeSize
15381 // ParentFP = RegNodeBase - RegNodeFrameOffset
15382 SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
15383 DAG.getConstant(RegNodeSize, dl, PtrVT));
15384 return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, RegNodeFrameOffset);
15387 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15388 SelectionDAG &DAG) {
15390 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15391 EVT VT = Op.getValueType();
15392 const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
15394 switch(IntrData->Type) {
15395 case INTR_TYPE_1OP:
15396 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
15397 case INTR_TYPE_2OP:
15398 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15400 case INTR_TYPE_3OP:
15401 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15402 Op.getOperand(2), Op.getOperand(3));
15403 case INTR_TYPE_4OP:
15404 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15405 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
15406 case INTR_TYPE_1OP_MASK_RM: {
15407 SDValue Src = Op.getOperand(1);
15408 SDValue PassThru = Op.getOperand(2);
15409 SDValue Mask = Op.getOperand(3);
15410 SDValue RoundingMode;
15411 // We allways add rounding mode to the Node.
15412 // If the rounding mode is not specified, we add the
15413 // "current direction" mode.
15414 if (Op.getNumOperands() == 4)
15416 DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15418 RoundingMode = Op.getOperand(4);
15419 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15420 if (IntrWithRoundingModeOpcode != 0)
15421 if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
15422 X86::STATIC_ROUNDING::CUR_DIRECTION)
15423 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15424 dl, Op.getValueType(), Src, RoundingMode),
15425 Mask, PassThru, Subtarget, DAG);
15426 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
15428 Mask, PassThru, Subtarget, DAG);
15430 case INTR_TYPE_1OP_MASK: {
15431 SDValue Src = Op.getOperand(1);
15432 SDValue PassThru = Op.getOperand(2);
15433 SDValue Mask = Op.getOperand(3);
15434 // We add rounding mode to the Node when
15435 // - RM Opcode is specified and
15436 // - RM is not "current direction".
15437 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15438 if (IntrWithRoundingModeOpcode != 0) {
15439 SDValue Rnd = Op.getOperand(4);
15440 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15441 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15442 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15443 dl, Op.getValueType(),
15445 Mask, PassThru, Subtarget, DAG);
15448 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
15449 Mask, PassThru, Subtarget, DAG);
15451 case INTR_TYPE_SCALAR_MASK_RM: {
15452 SDValue Src1 = Op.getOperand(1);
15453 SDValue Src2 = Op.getOperand(2);
15454 SDValue Src0 = Op.getOperand(3);
15455 SDValue Mask = Op.getOperand(4);
15456 // There are 2 kinds of intrinsics in this group:
15457 // (1) With suppress-all-exceptions (sae) or rounding mode- 6 operands
15458 // (2) With rounding mode and sae - 7 operands.
15459 if (Op.getNumOperands() == 6) {
15460 SDValue Sae = Op.getOperand(5);
15461 unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
15462 return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
15464 Mask, Src0, Subtarget, DAG);
15466 assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
15467 SDValue RoundingMode = Op.getOperand(5);
15468 SDValue Sae = Op.getOperand(6);
15469 return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
15470 RoundingMode, Sae),
15471 Mask, Src0, Subtarget, DAG);
15473 case INTR_TYPE_2OP_MASK: {
15474 SDValue Src1 = Op.getOperand(1);
15475 SDValue Src2 = Op.getOperand(2);
15476 SDValue PassThru = Op.getOperand(3);
15477 SDValue Mask = Op.getOperand(4);
15478 // We specify 2 possible opcodes for intrinsics with rounding modes.
15479 // First, we check if the intrinsic may have non-default rounding mode,
15480 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15481 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15482 if (IntrWithRoundingModeOpcode != 0) {
15483 SDValue Rnd = Op.getOperand(5);
15484 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15485 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15486 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15487 dl, Op.getValueType(),
15489 Mask, PassThru, Subtarget, DAG);
15492 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15494 Mask, PassThru, Subtarget, DAG);
15496 case INTR_TYPE_2OP_MASK_RM: {
15497 SDValue Src1 = Op.getOperand(1);
15498 SDValue Src2 = Op.getOperand(2);
15499 SDValue PassThru = Op.getOperand(3);
15500 SDValue Mask = Op.getOperand(4);
15501 // We specify 2 possible modes for intrinsics, with/without rounding modes.
15502 // First, we check if the intrinsic have rounding mode (6 operands),
15503 // if not, we set rounding mode to "current".
15505 if (Op.getNumOperands() == 6)
15506 Rnd = Op.getOperand(5);
15508 Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15509 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15511 Mask, PassThru, Subtarget, DAG);
15513 case INTR_TYPE_3OP_MASK_RM: {
15514 SDValue Src1 = Op.getOperand(1);
15515 SDValue Src2 = Op.getOperand(2);
15516 SDValue Imm = Op.getOperand(3);
15517 SDValue PassThru = Op.getOperand(4);
15518 SDValue Mask = Op.getOperand(5);
15519 // We specify 2 possible modes for intrinsics, with/without rounding modes.
15520 // First, we check if the intrinsic have rounding mode (7 operands),
15521 // if not, we set rounding mode to "current".
15523 if (Op.getNumOperands() == 7)
15524 Rnd = Op.getOperand(6);
15526 Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15527 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15528 Src1, Src2, Imm, Rnd),
15529 Mask, PassThru, Subtarget, DAG);
15531 case INTR_TYPE_3OP_MASK: {
15532 SDValue Src1 = Op.getOperand(1);
15533 SDValue Src2 = Op.getOperand(2);
15534 SDValue Src3 = Op.getOperand(3);
15535 SDValue PassThru = Op.getOperand(4);
15536 SDValue Mask = Op.getOperand(5);
15537 // We specify 2 possible opcodes for intrinsics with rounding modes.
15538 // First, we check if the intrinsic may have non-default rounding mode,
15539 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15540 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15541 if (IntrWithRoundingModeOpcode != 0) {
15542 SDValue Rnd = Op.getOperand(6);
15543 unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15544 if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15545 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15546 dl, Op.getValueType(),
15547 Src1, Src2, Src3, Rnd),
15548 Mask, PassThru, Subtarget, DAG);
15551 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15553 Mask, PassThru, Subtarget, DAG);
15555 case VPERM_3OP_MASKZ:
15556 case VPERM_3OP_MASK:
15559 case FMA_OP_MASK: {
15560 SDValue Src1 = Op.getOperand(1);
15561 SDValue Src2 = Op.getOperand(2);
15562 SDValue Src3 = Op.getOperand(3);
15563 SDValue Mask = Op.getOperand(4);
15564 EVT VT = Op.getValueType();
15565 SDValue PassThru = SDValue();
15567 // set PassThru element
15568 if (IntrData->Type == VPERM_3OP_MASKZ || IntrData->Type == FMA_OP_MASKZ)
15569 PassThru = getZeroVector(VT, Subtarget, DAG, dl);
15570 else if (IntrData->Type == FMA_OP_MASK3)
15575 // We specify 2 possible opcodes for intrinsics with rounding modes.
15576 // First, we check if the intrinsic may have non-default rounding mode,
15577 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15578 unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15579 if (IntrWithRoundingModeOpcode != 0) {
15580 SDValue Rnd = Op.getOperand(5);
15581 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15582 X86::STATIC_ROUNDING::CUR_DIRECTION)
15583 return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15584 dl, Op.getValueType(),
15585 Src1, Src2, Src3, Rnd),
15586 Mask, PassThru, Subtarget, DAG);
15588 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
15589 dl, Op.getValueType(),
15591 Mask, PassThru, Subtarget, DAG);
15594 case CMP_MASK_CC: {
15595 // Comparison intrinsics with masks.
15596 // Example of transformation:
15597 // (i8 (int_x86_avx512_mask_pcmpeq_q_128
15598 // (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
15600 // (v8i1 (insert_subvector undef,
15601 // (v2i1 (and (PCMPEQM %a, %b),
15602 // (extract_subvector
15603 // (v8i1 (bitcast %mask)), 0))), 0))))
15604 EVT VT = Op.getOperand(1).getValueType();
15605 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15606 VT.getVectorNumElements());
15607 SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
15608 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15609 Mask.getValueType().getSizeInBits());
15611 if (IntrData->Type == CMP_MASK_CC) {
15612 SDValue CC = Op.getOperand(3);
15613 CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
15614 // We specify 2 possible opcodes for intrinsics with rounding modes.
15615 // First, we check if the intrinsic may have non-default rounding mode,
15616 // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15617 if (IntrData->Opc1 != 0) {
15618 SDValue Rnd = Op.getOperand(5);
15619 if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15620 X86::STATIC_ROUNDING::CUR_DIRECTION)
15621 Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
15622 Op.getOperand(2), CC, Rnd);
15624 //default rounding mode
15626 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15627 Op.getOperand(2), CC);
15630 assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
15631 Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15634 SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
15635 DAG.getTargetConstant(0, dl,
15638 SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
15639 DAG.getUNDEF(BitcastVT), CmpMask,
15640 DAG.getIntPtrConstant(0, dl));
15641 return DAG.getBitcast(Op.getValueType(), Res);
15643 case COMI: { // Comparison intrinsics
15644 ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
15645 SDValue LHS = Op.getOperand(1);
15646 SDValue RHS = Op.getOperand(2);
15647 unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
15648 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
15649 SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
15650 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15651 DAG.getConstant(X86CC, dl, MVT::i8), Cond);
15652 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15655 return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
15656 Op.getOperand(1), Op.getOperand(2), DAG);
15658 return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
15659 Op.getSimpleValueType(),
15661 Op.getOperand(2), DAG),
15662 Op.getOperand(4), Op.getOperand(3), Subtarget,
15664 case COMPRESS_EXPAND_IN_REG: {
15665 SDValue Mask = Op.getOperand(3);
15666 SDValue DataToCompress = Op.getOperand(1);
15667 SDValue PassThru = Op.getOperand(2);
15668 if (isAllOnes(Mask)) // return data as is
15669 return Op.getOperand(1);
15671 return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15673 Mask, PassThru, Subtarget, DAG);
15676 SDValue Mask = Op.getOperand(3);
15677 EVT VT = Op.getValueType();
15678 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15679 VT.getVectorNumElements());
15680 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15681 Mask.getValueType().getSizeInBits());
15683 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15684 DAG.getBitcast(BitcastVT, Mask),
15685 DAG.getIntPtrConstant(0, dl));
15686 return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
15695 default: return SDValue(); // Don't custom lower most intrinsics.
15697 case Intrinsic::x86_avx2_permd:
15698 case Intrinsic::x86_avx2_permps:
15699 // Operands intentionally swapped. Mask is last operand to intrinsic,
15700 // but second operand for node/instruction.
15701 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
15702 Op.getOperand(2), Op.getOperand(1));
15704 // ptest and testp intrinsics. The intrinsic these come from are designed to
15705 // return an integer value, not just an instruction so lower it to the ptest
15706 // or testp pattern and a setcc for the result.
15707 case Intrinsic::x86_sse41_ptestz:
15708 case Intrinsic::x86_sse41_ptestc:
15709 case Intrinsic::x86_sse41_ptestnzc:
15710 case Intrinsic::x86_avx_ptestz_256:
15711 case Intrinsic::x86_avx_ptestc_256:
15712 case Intrinsic::x86_avx_ptestnzc_256:
15713 case Intrinsic::x86_avx_vtestz_ps:
15714 case Intrinsic::x86_avx_vtestc_ps:
15715 case Intrinsic::x86_avx_vtestnzc_ps:
15716 case Intrinsic::x86_avx_vtestz_pd:
15717 case Intrinsic::x86_avx_vtestc_pd:
15718 case Intrinsic::x86_avx_vtestnzc_pd:
15719 case Intrinsic::x86_avx_vtestz_ps_256:
15720 case Intrinsic::x86_avx_vtestc_ps_256:
15721 case Intrinsic::x86_avx_vtestnzc_ps_256:
15722 case Intrinsic::x86_avx_vtestz_pd_256:
15723 case Intrinsic::x86_avx_vtestc_pd_256:
15724 case Intrinsic::x86_avx_vtestnzc_pd_256: {
15725 bool IsTestPacked = false;
15728 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
15729 case Intrinsic::x86_avx_vtestz_ps:
15730 case Intrinsic::x86_avx_vtestz_pd:
15731 case Intrinsic::x86_avx_vtestz_ps_256:
15732 case Intrinsic::x86_avx_vtestz_pd_256:
15733 IsTestPacked = true; // Fallthrough
15734 case Intrinsic::x86_sse41_ptestz:
15735 case Intrinsic::x86_avx_ptestz_256:
15737 X86CC = X86::COND_E;
15739 case Intrinsic::x86_avx_vtestc_ps:
15740 case Intrinsic::x86_avx_vtestc_pd:
15741 case Intrinsic::x86_avx_vtestc_ps_256:
15742 case Intrinsic::x86_avx_vtestc_pd_256:
15743 IsTestPacked = true; // Fallthrough
15744 case Intrinsic::x86_sse41_ptestc:
15745 case Intrinsic::x86_avx_ptestc_256:
15747 X86CC = X86::COND_B;
15749 case Intrinsic::x86_avx_vtestnzc_ps:
15750 case Intrinsic::x86_avx_vtestnzc_pd:
15751 case Intrinsic::x86_avx_vtestnzc_ps_256:
15752 case Intrinsic::x86_avx_vtestnzc_pd_256:
15753 IsTestPacked = true; // Fallthrough
15754 case Intrinsic::x86_sse41_ptestnzc:
15755 case Intrinsic::x86_avx_ptestnzc_256:
15757 X86CC = X86::COND_A;
15761 SDValue LHS = Op.getOperand(1);
15762 SDValue RHS = Op.getOperand(2);
15763 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
15764 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
15765 SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15766 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
15767 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15769 case Intrinsic::x86_avx512_kortestz_w:
15770 case Intrinsic::x86_avx512_kortestc_w: {
15771 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
15772 SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
15773 SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
15774 SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15775 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
15776 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
15777 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15780 case Intrinsic::x86_sse42_pcmpistria128:
15781 case Intrinsic::x86_sse42_pcmpestria128:
15782 case Intrinsic::x86_sse42_pcmpistric128:
15783 case Intrinsic::x86_sse42_pcmpestric128:
15784 case Intrinsic::x86_sse42_pcmpistrio128:
15785 case Intrinsic::x86_sse42_pcmpestrio128:
15786 case Intrinsic::x86_sse42_pcmpistris128:
15787 case Intrinsic::x86_sse42_pcmpestris128:
15788 case Intrinsic::x86_sse42_pcmpistriz128:
15789 case Intrinsic::x86_sse42_pcmpestriz128: {
15793 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
15794 case Intrinsic::x86_sse42_pcmpistria128:
15795 Opcode = X86ISD::PCMPISTRI;
15796 X86CC = X86::COND_A;
15798 case Intrinsic::x86_sse42_pcmpestria128:
15799 Opcode = X86ISD::PCMPESTRI;
15800 X86CC = X86::COND_A;
15802 case Intrinsic::x86_sse42_pcmpistric128:
15803 Opcode = X86ISD::PCMPISTRI;
15804 X86CC = X86::COND_B;
15806 case Intrinsic::x86_sse42_pcmpestric128:
15807 Opcode = X86ISD::PCMPESTRI;
15808 X86CC = X86::COND_B;
15810 case Intrinsic::x86_sse42_pcmpistrio128:
15811 Opcode = X86ISD::PCMPISTRI;
15812 X86CC = X86::COND_O;
15814 case Intrinsic::x86_sse42_pcmpestrio128:
15815 Opcode = X86ISD::PCMPESTRI;
15816 X86CC = X86::COND_O;
15818 case Intrinsic::x86_sse42_pcmpistris128:
15819 Opcode = X86ISD::PCMPISTRI;
15820 X86CC = X86::COND_S;
15822 case Intrinsic::x86_sse42_pcmpestris128:
15823 Opcode = X86ISD::PCMPESTRI;
15824 X86CC = X86::COND_S;
15826 case Intrinsic::x86_sse42_pcmpistriz128:
15827 Opcode = X86ISD::PCMPISTRI;
15828 X86CC = X86::COND_E;
15830 case Intrinsic::x86_sse42_pcmpestriz128:
15831 Opcode = X86ISD::PCMPESTRI;
15832 X86CC = X86::COND_E;
15835 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15836 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15837 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
15838 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15839 DAG.getConstant(X86CC, dl, MVT::i8),
15840 SDValue(PCMP.getNode(), 1));
15841 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15844 case Intrinsic::x86_sse42_pcmpistri128:
15845 case Intrinsic::x86_sse42_pcmpestri128: {
15847 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
15848 Opcode = X86ISD::PCMPISTRI;
15850 Opcode = X86ISD::PCMPESTRI;
15852 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15853 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15854 return DAG.getNode(Opcode, dl, VTs, NewOps);
15857 case Intrinsic::x86_seh_lsda: {
15858 // Compute the symbol for the LSDA. We know it'll get emitted later.
15859 MachineFunction &MF = DAG.getMachineFunction();
15860 SDValue Op1 = Op.getOperand(1);
15861 auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
15862 MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
15863 GlobalValue::getRealLinkageName(Fn->getName()));
15865 // Generate a simple absolute symbol reference. This intrinsic is only
15866 // supported on 32-bit Windows, which isn't PIC.
15867 SDValue Result = DAG.getMCSymbol(LSDASym, VT);
15868 return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
15871 case Intrinsic::x86_seh_recoverfp: {
15872 SDValue FnOp = Op.getOperand(1);
15873 SDValue IncomingFPOp = Op.getOperand(2);
15874 GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
15875 auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
15877 report_fatal_error(
15878 "llvm.x86.seh.recoverfp must take a function as the first argument");
15879 return recoverFramePointer(DAG, Fn, IncomingFPOp);
15882 case Intrinsic::localaddress: {
15883 // Returns one of the stack, base, or frame pointer registers, depending on
15884 // which is used to reference local variables.
15885 MachineFunction &MF = DAG.getMachineFunction();
15886 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15888 if (RegInfo->hasBasePointer(MF))
15889 Reg = RegInfo->getBaseRegister();
15890 else // This function handles the SP or FP case.
15891 Reg = RegInfo->getPtrSizedFrameRegister(MF);
15892 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
15897 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15898 SDValue Src, SDValue Mask, SDValue Base,
15899 SDValue Index, SDValue ScaleOp, SDValue Chain,
15900 const X86Subtarget * Subtarget) {
15902 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15904 llvm_unreachable("Invalid scale type");
15905 unsigned ScaleVal = C->getZExtValue();
15906 if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
15907 llvm_unreachable("Valid scale values are 1, 2, 4, 8");
15909 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15910 EVT MaskVT = MVT::getVectorVT(MVT::i1,
15911 Index.getSimpleValueType().getVectorNumElements());
15913 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15915 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15917 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15918 Mask.getValueType().getSizeInBits());
15920 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15921 // are extracted by EXTRACT_SUBVECTOR.
15922 MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15923 DAG.getBitcast(BitcastVT, Mask),
15924 DAG.getIntPtrConstant(0, dl));
15926 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
15927 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15928 SDValue Segment = DAG.getRegister(0, MVT::i32);
15929 if (Src.getOpcode() == ISD::UNDEF)
15930 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15931 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15932 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15933 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15934 return DAG.getMergeValues(RetOps, dl);
15937 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15938 SDValue Src, SDValue Mask, SDValue Base,
15939 SDValue Index, SDValue ScaleOp, SDValue Chain) {
15941 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15943 llvm_unreachable("Invalid scale type");
15944 unsigned ScaleVal = C->getZExtValue();
15945 if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
15946 llvm_unreachable("Valid scale values are 1, 2, 4, 8");
15948 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15949 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15950 SDValue Segment = DAG.getRegister(0, MVT::i32);
15951 EVT MaskVT = MVT::getVectorVT(MVT::i1,
15952 Index.getSimpleValueType().getVectorNumElements());
15954 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15956 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15958 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15959 Mask.getValueType().getSizeInBits());
15961 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15962 // are extracted by EXTRACT_SUBVECTOR.
15963 MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15964 DAG.getBitcast(BitcastVT, Mask),
15965 DAG.getIntPtrConstant(0, dl));
15967 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
15968 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
15969 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15970 return SDValue(Res, 1);
15973 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15974 SDValue Mask, SDValue Base, SDValue Index,
15975 SDValue ScaleOp, SDValue Chain) {
15977 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15978 assert(C && "Invalid scale type");
15979 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15980 SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15981 SDValue Segment = DAG.getRegister(0, MVT::i32);
15983 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
15985 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15987 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15989 MaskInReg = DAG.getBitcast(MaskVT, Mask);
15990 //SDVTList VTs = DAG.getVTList(MVT::Other);
15991 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15992 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
15993 return SDValue(Res, 0);
15996 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
15997 // read performance monitor counters (x86_rdpmc).
15998 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
15999 SelectionDAG &DAG, const X86Subtarget *Subtarget,
16000 SmallVectorImpl<SDValue> &Results) {
16001 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16002 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16005 // The ECX register is used to select the index of the performance counter
16007 SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
16009 SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
16011 // Reads the content of a 64-bit performance counter and returns it in the
16012 // registers EDX:EAX.
16013 if (Subtarget->is64Bit()) {
16014 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16015 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16018 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16019 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16022 Chain = HI.getValue(1);
16024 if (Subtarget->is64Bit()) {
16025 // The EAX register is loaded with the low-order 32 bits. The EDX register
16026 // is loaded with the supported high-order bits of the counter.
16027 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16028 DAG.getConstant(32, DL, MVT::i8));
16029 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16030 Results.push_back(Chain);
16034 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16035 SDValue Ops[] = { LO, HI };
16036 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16037 Results.push_back(Pair);
16038 Results.push_back(Chain);
16041 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
16042 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
16043 // also used to custom lower READCYCLECOUNTER nodes.
16044 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
16045 SelectionDAG &DAG, const X86Subtarget *Subtarget,
16046 SmallVectorImpl<SDValue> &Results) {
16047 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16048 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
16051 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
16052 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
16053 // and the EAX register is loaded with the low-order 32 bits.
16054 if (Subtarget->is64Bit()) {
16055 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16056 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16059 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16060 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16063 SDValue Chain = HI.getValue(1);
16065 if (Opcode == X86ISD::RDTSCP_DAG) {
16066 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16068 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
16069 // the ECX register. Add 'ecx' explicitly to the chain.
16070 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
16072 // Explicitly store the content of ECX at the location passed in input
16073 // to the 'rdtscp' intrinsic.
16074 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
16075 MachinePointerInfo(), false, false, 0);
16078 if (Subtarget->is64Bit()) {
16079 // The EDX register is loaded with the high-order 32 bits of the MSR, and
16080 // the EAX register is loaded with the low-order 32 bits.
16081 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16082 DAG.getConstant(32, DL, MVT::i8));
16083 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16084 Results.push_back(Chain);
16088 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16089 SDValue Ops[] = { LO, HI };
16090 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16091 Results.push_back(Pair);
16092 Results.push_back(Chain);
16095 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
16096 SelectionDAG &DAG) {
16097 SmallVector<SDValue, 2> Results;
16099 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
16101 return DAG.getMergeValues(Results, DL);
16104 static SDValue LowerSEHRESTOREFRAME(SDValue Op, const X86Subtarget *Subtarget,
16105 SelectionDAG &DAG) {
16106 MachineFunction &MF = DAG.getMachineFunction();
16107 const Function *Fn = MF.getFunction();
16109 SDValue Chain = Op.getOperand(0);
16111 assert(Subtarget->getFrameLowering()->hasFP(MF) &&
16112 "using llvm.x86.seh.restoreframe requires a frame pointer");
16114 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16115 MVT VT = TLI.getPointerTy(DAG.getDataLayout());
16117 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16118 unsigned FrameReg =
16119 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16120 unsigned SPReg = RegInfo->getStackRegister();
16121 unsigned SlotSize = RegInfo->getSlotSize();
16123 // Get incoming EBP.
16124 SDValue IncomingEBP =
16125 DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
16127 // SP is saved in the first field of every registration node, so load
16128 // [EBP-RegNodeSize] into SP.
16129 int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16130 SDValue SPAddr = DAG.getNode(ISD::ADD, dl, VT, IncomingEBP,
16131 DAG.getConstant(-RegNodeSize, dl, VT));
16133 DAG.getLoad(VT, dl, Chain, SPAddr, MachinePointerInfo(), false, false,
16134 false, VT.getScalarSizeInBits() / 8);
16135 Chain = DAG.getCopyToReg(Chain, dl, SPReg, NewSP);
16137 if (!RegInfo->needsStackRealignment(MF)) {
16138 // Adjust EBP to point back to the original frame position.
16139 SDValue NewFP = recoverFramePointer(DAG, Fn, IncomingEBP);
16140 Chain = DAG.getCopyToReg(Chain, dl, FrameReg, NewFP);
16142 assert(RegInfo->hasBasePointer(MF) &&
16143 "functions with Win32 EH must use frame or base pointer register");
16145 // Reload the base pointer (ESI) with the adjusted incoming EBP.
16146 SDValue NewBP = recoverFramePointer(DAG, Fn, IncomingEBP);
16147 Chain = DAG.getCopyToReg(Chain, dl, RegInfo->getBaseRegister(), NewBP);
16149 // Reload the spilled EBP value, now that the stack and base pointers are
16151 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
16152 X86FI->setHasSEHFramePtrSave(true);
16153 int FI = MF.getFrameInfo()->CreateSpillStackObject(SlotSize, SlotSize);
16154 X86FI->setSEHFramePtrSaveIndex(FI);
16155 SDValue NewFP = DAG.getLoad(VT, dl, Chain, DAG.getFrameIndex(FI, VT),
16156 MachinePointerInfo(), false, false, false,
16157 VT.getScalarSizeInBits() / 8);
16158 Chain = DAG.getCopyToReg(NewFP, dl, FrameReg, NewFP);
16164 /// \brief Lower intrinsics for TRUNCATE_TO_MEM case
16165 /// return truncate Store/MaskedStore Node
16166 static SDValue LowerINTRINSIC_TRUNCATE_TO_MEM(const SDValue & Op,
16170 SDValue Mask = Op.getOperand(4);
16171 SDValue DataToTruncate = Op.getOperand(3);
16172 SDValue Addr = Op.getOperand(2);
16173 SDValue Chain = Op.getOperand(0);
16175 EVT VT = DataToTruncate.getValueType();
16176 EVT SVT = EVT::getVectorVT(*DAG.getContext(),
16177 ElementType, VT.getVectorNumElements());
16179 if (isAllOnes(Mask)) // return just a truncate store
16180 return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr,
16181 MachinePointerInfo(), SVT, false, false,
16182 SVT.getScalarSizeInBits()/8);
16184 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
16185 MVT::i1, VT.getVectorNumElements());
16186 EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16187 Mask.getValueType().getSizeInBits());
16188 // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16189 // are extracted by EXTRACT_SUBVECTOR.
16190 SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16191 DAG.getBitcast(BitcastVT, Mask),
16192 DAG.getIntPtrConstant(0, dl));
16194 MachineMemOperand *MMO = DAG.getMachineFunction().
16195 getMachineMemOperand(MachinePointerInfo(),
16196 MachineMemOperand::MOStore, SVT.getStoreSize(),
16197 SVT.getScalarSizeInBits()/8);
16199 return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr,
16200 VMask, SVT, MMO, true);
16203 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16204 SelectionDAG &DAG) {
16205 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
16207 const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
16209 if (IntNo == llvm::Intrinsic::x86_seh_restoreframe)
16210 return LowerSEHRESTOREFRAME(Op, Subtarget, DAG);
16215 switch(IntrData->Type) {
16217 llvm_unreachable("Unknown Intrinsic Type");
16221 // Emit the node with the right value type.
16222 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
16223 SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16225 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
16226 // Otherwise return the value from Rand, which is always 0, casted to i32.
16227 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
16228 DAG.getConstant(1, dl, Op->getValueType(1)),
16229 DAG.getConstant(X86::COND_B, dl, MVT::i32),
16230 SDValue(Result.getNode(), 1) };
16231 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
16232 DAG.getVTList(Op->getValueType(1), MVT::Glue),
16235 // Return { result, isValid, chain }.
16236 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
16237 SDValue(Result.getNode(), 2));
16240 //gather(v1, mask, index, base, scale);
16241 SDValue Chain = Op.getOperand(0);
16242 SDValue Src = Op.getOperand(2);
16243 SDValue Base = Op.getOperand(3);
16244 SDValue Index = Op.getOperand(4);
16245 SDValue Mask = Op.getOperand(5);
16246 SDValue Scale = Op.getOperand(6);
16247 return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
16251 //scatter(base, mask, index, v1, scale);
16252 SDValue Chain = Op.getOperand(0);
16253 SDValue Base = Op.getOperand(2);
16254 SDValue Mask = Op.getOperand(3);
16255 SDValue Index = Op.getOperand(4);
16256 SDValue Src = Op.getOperand(5);
16257 SDValue Scale = Op.getOperand(6);
16258 return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
16262 SDValue Hint = Op.getOperand(6);
16263 unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
16264 assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
16265 unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
16266 SDValue Chain = Op.getOperand(0);
16267 SDValue Mask = Op.getOperand(2);
16268 SDValue Index = Op.getOperand(3);
16269 SDValue Base = Op.getOperand(4);
16270 SDValue Scale = Op.getOperand(5);
16271 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
16273 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
16275 SmallVector<SDValue, 2> Results;
16276 getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
16278 return DAG.getMergeValues(Results, dl);
16280 // Read Performance Monitoring Counters.
16282 SmallVector<SDValue, 2> Results;
16283 getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
16284 return DAG.getMergeValues(Results, dl);
16286 // XTEST intrinsics.
16288 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16289 SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16290 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16291 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
16293 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
16294 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
16295 Ret, SDValue(InTrans.getNode(), 1));
16299 SmallVector<SDValue, 2> Results;
16300 SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16301 SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
16302 SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
16303 DAG.getConstant(-1, dl, MVT::i8));
16304 SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
16305 Op.getOperand(4), GenCF.getValue(1));
16306 SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
16307 Op.getOperand(5), MachinePointerInfo(),
16309 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16310 DAG.getConstant(X86::COND_B, dl, MVT::i8),
16312 Results.push_back(SetCC);
16313 Results.push_back(Store);
16314 return DAG.getMergeValues(Results, dl);
16316 case COMPRESS_TO_MEM: {
16318 SDValue Mask = Op.getOperand(4);
16319 SDValue DataToCompress = Op.getOperand(3);
16320 SDValue Addr = Op.getOperand(2);
16321 SDValue Chain = Op.getOperand(0);
16323 EVT VT = DataToCompress.getValueType();
16324 if (isAllOnes(Mask)) // return just a store
16325 return DAG.getStore(Chain, dl, DataToCompress, Addr,
16326 MachinePointerInfo(), false, false,
16327 VT.getScalarSizeInBits()/8);
16329 SDValue Compressed =
16330 getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
16331 Mask, DAG.getUNDEF(VT), Subtarget, DAG);
16332 return DAG.getStore(Chain, dl, Compressed, Addr,
16333 MachinePointerInfo(), false, false,
16334 VT.getScalarSizeInBits()/8);
16336 case TRUNCATE_TO_MEM_VI8:
16337 return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i8);
16338 case TRUNCATE_TO_MEM_VI16:
16339 return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i16);
16340 case TRUNCATE_TO_MEM_VI32:
16341 return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i32);
16342 case EXPAND_FROM_MEM: {
16344 SDValue Mask = Op.getOperand(4);
16345 SDValue PassThru = Op.getOperand(3);
16346 SDValue Addr = Op.getOperand(2);
16347 SDValue Chain = Op.getOperand(0);
16348 EVT VT = Op.getValueType();
16350 if (isAllOnes(Mask)) // return just a load
16351 return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
16352 false, VT.getScalarSizeInBits()/8);
16354 SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
16355 false, false, false,
16356 VT.getScalarSizeInBits()/8);
16358 SDValue Results[] = {
16359 getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
16360 Mask, PassThru, Subtarget, DAG), Chain};
16361 return DAG.getMergeValues(Results, dl);
16366 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
16367 SelectionDAG &DAG) const {
16368 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
16369 MFI->setReturnAddressIsTaken(true);
16371 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
16374 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16376 EVT PtrVT = getPointerTy(DAG.getDataLayout());
16379 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
16380 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16381 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
16382 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16383 DAG.getNode(ISD::ADD, dl, PtrVT,
16384 FrameAddr, Offset),
16385 MachinePointerInfo(), false, false, false, 0);
16388 // Just load the return address.
16389 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
16390 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16391 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
16394 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
16395 MachineFunction &MF = DAG.getMachineFunction();
16396 MachineFrameInfo *MFI = MF.getFrameInfo();
16397 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
16398 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16399 EVT VT = Op.getValueType();
16401 MFI->setFrameAddressIsTaken(true);
16403 if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
16404 // Depth > 0 makes no sense on targets which use Windows unwind codes. It
16405 // is not possible to crawl up the stack without looking at the unwind codes
16407 int FrameAddrIndex = FuncInfo->getFAIndex();
16408 if (!FrameAddrIndex) {
16409 // Set up a frame object for the return address.
16410 unsigned SlotSize = RegInfo->getSlotSize();
16411 FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
16412 SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
16413 FuncInfo->setFAIndex(FrameAddrIndex);
16415 return DAG.getFrameIndex(FrameAddrIndex, VT);
16418 unsigned FrameReg =
16419 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16420 SDLoc dl(Op); // FIXME probably not meaningful
16421 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16422 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
16423 (FrameReg == X86::EBP && VT == MVT::i32)) &&
16424 "Invalid Frame Register!");
16425 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
16427 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
16428 MachinePointerInfo(),
16429 false, false, false, 0);
16433 // FIXME? Maybe this could be a TableGen attribute on some registers and
16434 // this table could be generated automatically from RegInfo.
16435 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
16436 SelectionDAG &DAG) const {
16437 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16438 const MachineFunction &MF = DAG.getMachineFunction();
16440 unsigned Reg = StringSwitch<unsigned>(RegName)
16441 .Case("esp", X86::ESP)
16442 .Case("rsp", X86::RSP)
16443 .Case("ebp", X86::EBP)
16444 .Case("rbp", X86::RBP)
16447 if (Reg == X86::EBP || Reg == X86::RBP) {
16448 if (!TFI.hasFP(MF))
16449 report_fatal_error("register " + StringRef(RegName) +
16450 " is allocatable: function has no frame pointer");
16453 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16454 unsigned FrameReg =
16455 RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16456 assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
16457 "Invalid Frame Register!");
16465 report_fatal_error("Invalid register name global variable");
16468 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
16469 SelectionDAG &DAG) const {
16470 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16471 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
16474 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
16475 SDValue Chain = Op.getOperand(0);
16476 SDValue Offset = Op.getOperand(1);
16477 SDValue Handler = Op.getOperand(2);
16480 EVT PtrVT = getPointerTy(DAG.getDataLayout());
16481 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16482 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
16483 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
16484 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
16485 "Invalid Frame Register!");
16486 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
16487 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
16489 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
16490 DAG.getIntPtrConstant(RegInfo->getSlotSize(),
16492 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
16493 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
16495 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
16497 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
16498 DAG.getRegister(StoreAddrReg, PtrVT));
16501 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
16502 SelectionDAG &DAG) const {
16504 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
16505 DAG.getVTList(MVT::i32, MVT::Other),
16506 Op.getOperand(0), Op.getOperand(1));
16509 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
16510 SelectionDAG &DAG) const {
16512 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
16513 Op.getOperand(0), Op.getOperand(1));
16516 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
16517 return Op.getOperand(0);
16520 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
16521 SelectionDAG &DAG) const {
16522 SDValue Root = Op.getOperand(0);
16523 SDValue Trmp = Op.getOperand(1); // trampoline
16524 SDValue FPtr = Op.getOperand(2); // nested function
16525 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
16528 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16529 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
16531 if (Subtarget->is64Bit()) {
16532 SDValue OutChains[6];
16534 // Large code-model.
16535 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
16536 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
16538 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
16539 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
16541 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
16543 // Load the pointer to the nested function into R11.
16544 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
16545 SDValue Addr = Trmp;
16546 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16547 Addr, MachinePointerInfo(TrmpAddr),
16550 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16551 DAG.getConstant(2, dl, MVT::i64));
16552 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
16553 MachinePointerInfo(TrmpAddr, 2),
16556 // Load the 'nest' parameter value into R10.
16557 // R10 is specified in X86CallingConv.td
16558 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
16559 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16560 DAG.getConstant(10, dl, MVT::i64));
16561 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16562 Addr, MachinePointerInfo(TrmpAddr, 10),
16565 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16566 DAG.getConstant(12, dl, MVT::i64));
16567 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
16568 MachinePointerInfo(TrmpAddr, 12),
16571 // Jump to the nested function.
16572 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
16573 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16574 DAG.getConstant(20, dl, MVT::i64));
16575 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16576 Addr, MachinePointerInfo(TrmpAddr, 20),
16579 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
16580 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16581 DAG.getConstant(22, dl, MVT::i64));
16582 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
16583 Addr, MachinePointerInfo(TrmpAddr, 22),
16586 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16588 const Function *Func =
16589 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
16590 CallingConv::ID CC = Func->getCallingConv();
16595 llvm_unreachable("Unsupported calling convention");
16596 case CallingConv::C:
16597 case CallingConv::X86_StdCall: {
16598 // Pass 'nest' parameter in ECX.
16599 // Must be kept in sync with X86CallingConv.td
16600 NestReg = X86::ECX;
16602 // Check that ECX wasn't needed by an 'inreg' parameter.
16603 FunctionType *FTy = Func->getFunctionType();
16604 const AttributeSet &Attrs = Func->getAttributes();
16606 if (!Attrs.isEmpty() && !Func->isVarArg()) {
16607 unsigned InRegCount = 0;
16610 for (FunctionType::param_iterator I = FTy->param_begin(),
16611 E = FTy->param_end(); I != E; ++I, ++Idx)
16612 if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
16613 auto &DL = DAG.getDataLayout();
16614 // FIXME: should only count parameters that are lowered to integers.
16615 InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
16618 if (InRegCount > 2) {
16619 report_fatal_error("Nest register in use - reduce number of inreg"
16625 case CallingConv::X86_FastCall:
16626 case CallingConv::X86_ThisCall:
16627 case CallingConv::Fast:
16628 // Pass 'nest' parameter in EAX.
16629 // Must be kept in sync with X86CallingConv.td
16630 NestReg = X86::EAX;
16634 SDValue OutChains[4];
16635 SDValue Addr, Disp;
16637 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16638 DAG.getConstant(10, dl, MVT::i32));
16639 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
16641 // This is storing the opcode for MOV32ri.
16642 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
16643 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
16644 OutChains[0] = DAG.getStore(Root, dl,
16645 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
16646 Trmp, MachinePointerInfo(TrmpAddr),
16649 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16650 DAG.getConstant(1, dl, MVT::i32));
16651 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
16652 MachinePointerInfo(TrmpAddr, 1),
16655 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
16656 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16657 DAG.getConstant(5, dl, MVT::i32));
16658 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
16659 Addr, MachinePointerInfo(TrmpAddr, 5),
16662 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16663 DAG.getConstant(6, dl, MVT::i32));
16664 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
16665 MachinePointerInfo(TrmpAddr, 6),
16668 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16672 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
16673 SelectionDAG &DAG) const {
16675 The rounding mode is in bits 11:10 of FPSR, and has the following
16677 00 Round to nearest
16682 FLT_ROUNDS, on the other hand, expects the following:
16689 To perform the conversion, we do:
16690 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
16693 MachineFunction &MF = DAG.getMachineFunction();
16694 const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16695 unsigned StackAlignment = TFI.getStackAlignment();
16696 MVT VT = Op.getSimpleValueType();
16699 // Save FP Control Word to stack slot
16700 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
16701 SDValue StackSlot =
16702 DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
16704 MachineMemOperand *MMO =
16705 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
16706 MachineMemOperand::MOStore, 2, 2);
16708 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
16709 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
16710 DAG.getVTList(MVT::Other),
16711 Ops, MVT::i16, MMO);
16713 // Load FP Control Word from stack slot
16714 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
16715 MachinePointerInfo(), false, false, false, 0);
16717 // Transform as necessary
16719 DAG.getNode(ISD::SRL, DL, MVT::i16,
16720 DAG.getNode(ISD::AND, DL, MVT::i16,
16721 CWD, DAG.getConstant(0x800, DL, MVT::i16)),
16722 DAG.getConstant(11, DL, MVT::i8));
16724 DAG.getNode(ISD::SRL, DL, MVT::i16,
16725 DAG.getNode(ISD::AND, DL, MVT::i16,
16726 CWD, DAG.getConstant(0x400, DL, MVT::i16)),
16727 DAG.getConstant(9, DL, MVT::i8));
16730 DAG.getNode(ISD::AND, DL, MVT::i16,
16731 DAG.getNode(ISD::ADD, DL, MVT::i16,
16732 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
16733 DAG.getConstant(1, DL, MVT::i16)),
16734 DAG.getConstant(3, DL, MVT::i16));
16736 return DAG.getNode((VT.getSizeInBits() < 16 ?
16737 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
16740 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
16741 MVT VT = Op.getSimpleValueType();
16743 unsigned NumBits = VT.getSizeInBits();
16746 Op = Op.getOperand(0);
16747 if (VT == MVT::i8) {
16748 // Zero extend to i32 since there is not an i8 bsr.
16750 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16753 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
16754 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16755 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16757 // If src is zero (i.e. bsr sets ZF), returns NumBits.
16760 DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
16761 DAG.getConstant(X86::COND_E, dl, MVT::i8),
16764 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
16766 // Finally xor with NumBits-1.
16767 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16768 DAG.getConstant(NumBits - 1, dl, OpVT));
16771 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16775 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
16776 MVT VT = Op.getSimpleValueType();
16778 unsigned NumBits = VT.getSizeInBits();
16781 Op = Op.getOperand(0);
16782 if (VT == MVT::i8) {
16783 // Zero extend to i32 since there is not an i8 bsr.
16785 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16788 // Issue a bsr (scan bits in reverse).
16789 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16790 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16792 // And xor with NumBits-1.
16793 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16794 DAG.getConstant(NumBits - 1, dl, OpVT));
16797 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16801 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
16802 MVT VT = Op.getSimpleValueType();
16803 unsigned NumBits = VT.getSizeInBits();
16805 Op = Op.getOperand(0);
16807 // Issue a bsf (scan bits forward) which also sets EFLAGS.
16808 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16809 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
16811 // If src is zero (i.e. bsf sets ZF), returns NumBits.
16814 DAG.getConstant(NumBits, dl, VT),
16815 DAG.getConstant(X86::COND_E, dl, MVT::i8),
16818 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
16821 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
16822 // ones, and then concatenate the result back.
16823 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
16824 MVT VT = Op.getSimpleValueType();
16826 assert(VT.is256BitVector() && VT.isInteger() &&
16827 "Unsupported value type for operation");
16829 unsigned NumElems = VT.getVectorNumElements();
16832 // Extract the LHS vectors
16833 SDValue LHS = Op.getOperand(0);
16834 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16835 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16837 // Extract the RHS vectors
16838 SDValue RHS = Op.getOperand(1);
16839 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
16840 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
16842 MVT EltVT = VT.getVectorElementType();
16843 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16845 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16846 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
16847 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
16850 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
16851 if (Op.getValueType() == MVT::i1)
16852 return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
16853 Op.getOperand(0), Op.getOperand(1));
16854 assert(Op.getSimpleValueType().is256BitVector() &&
16855 Op.getSimpleValueType().isInteger() &&
16856 "Only handle AVX 256-bit vector integer operation");
16857 return Lower256IntArith(Op, DAG);
16860 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
16861 if (Op.getValueType() == MVT::i1)
16862 return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
16863 Op.getOperand(0), Op.getOperand(1));
16864 assert(Op.getSimpleValueType().is256BitVector() &&
16865 Op.getSimpleValueType().isInteger() &&
16866 "Only handle AVX 256-bit vector integer operation");
16867 return Lower256IntArith(Op, DAG);
16870 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
16871 SelectionDAG &DAG) {
16873 MVT VT = Op.getSimpleValueType();
16876 return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
16878 // Decompose 256-bit ops into smaller 128-bit ops.
16879 if (VT.is256BitVector() && !Subtarget->hasInt256())
16880 return Lower256IntArith(Op, DAG);
16882 SDValue A = Op.getOperand(0);
16883 SDValue B = Op.getOperand(1);
16885 // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
16886 // pairs, multiply and truncate.
16887 if (VT == MVT::v16i8 || VT == MVT::v32i8) {
16888 if (Subtarget->hasInt256()) {
16889 if (VT == MVT::v32i8) {
16890 MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
16891 SDValue Lo = DAG.getIntPtrConstant(0, dl);
16892 SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
16893 SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
16894 SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
16895 SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
16896 SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
16897 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16898 DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
16899 DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
16902 MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
16903 return DAG.getNode(
16904 ISD::TRUNCATE, dl, VT,
16905 DAG.getNode(ISD::MUL, dl, ExVT,
16906 DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
16907 DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
16910 assert(VT == MVT::v16i8 &&
16911 "Pre-AVX2 support only supports v16i8 multiplication");
16912 MVT ExVT = MVT::v8i16;
16914 // Extract the lo parts and sign extend to i16
16916 if (Subtarget->hasSSE41()) {
16917 ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
16918 BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
16920 const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
16921 -1, 4, -1, 5, -1, 6, -1, 7};
16922 ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16923 BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16924 ALo = DAG.getBitcast(ExVT, ALo);
16925 BLo = DAG.getBitcast(ExVT, BLo);
16926 ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
16927 BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
16930 // Extract the hi parts and sign extend to i16
16932 if (Subtarget->hasSSE41()) {
16933 const int ShufMask[] = {8, 9, 10, 11, 12, 13, 14, 15,
16934 -1, -1, -1, -1, -1, -1, -1, -1};
16935 AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16936 BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16937 AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
16938 BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
16940 const int ShufMask[] = {-1, 8, -1, 9, -1, 10, -1, 11,
16941 -1, 12, -1, 13, -1, 14, -1, 15};
16942 AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16943 BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16944 AHi = DAG.getBitcast(ExVT, AHi);
16945 BHi = DAG.getBitcast(ExVT, BHi);
16946 AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
16947 BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
16950 // Multiply, mask the lower 8bits of the lo/hi results and pack
16951 SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
16952 SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
16953 RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
16954 RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
16955 return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
16958 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
16959 if (VT == MVT::v4i32) {
16960 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
16961 "Should not custom lower when pmuldq is available!");
16963 // Extract the odd parts.
16964 static const int UnpackMask[] = { 1, -1, 3, -1 };
16965 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
16966 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
16968 // Multiply the even parts.
16969 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
16970 // Now multiply odd parts.
16971 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
16973 Evens = DAG.getBitcast(VT, Evens);
16974 Odds = DAG.getBitcast(VT, Odds);
16976 // Merge the two vectors back together with a shuffle. This expands into 2
16978 static const int ShufMask[] = { 0, 4, 2, 6 };
16979 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
16982 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
16983 "Only know how to lower V2I64/V4I64/V8I64 multiply");
16985 // Ahi = psrlqi(a, 32);
16986 // Bhi = psrlqi(b, 32);
16988 // AloBlo = pmuludq(a, b);
16989 // AloBhi = pmuludq(a, Bhi);
16990 // AhiBlo = pmuludq(Ahi, b);
16992 // AloBhi = psllqi(AloBhi, 32);
16993 // AhiBlo = psllqi(AhiBlo, 32);
16994 // return AloBlo + AloBhi + AhiBlo;
16996 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
16997 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
16999 SDValue AhiBlo = Ahi;
17000 SDValue AloBhi = Bhi;
17001 // Bit cast to 32-bit vectors for MULUDQ
17002 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
17003 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
17004 A = DAG.getBitcast(MulVT, A);
17005 B = DAG.getBitcast(MulVT, B);
17006 Ahi = DAG.getBitcast(MulVT, Ahi);
17007 Bhi = DAG.getBitcast(MulVT, Bhi);
17009 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
17010 // After shifting right const values the result may be all-zero.
17011 if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
17012 AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
17013 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
17015 if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
17016 AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
17017 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
17020 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
17021 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
17024 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
17025 assert(Subtarget->isTargetWin64() && "Unexpected target");
17026 EVT VT = Op.getValueType();
17027 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
17028 "Unexpected return type for lowering");
17032 switch (Op->getOpcode()) {
17033 default: llvm_unreachable("Unexpected request for libcall!");
17034 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
17035 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
17036 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
17037 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
17038 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
17039 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
17043 SDValue InChain = DAG.getEntryNode();
17045 TargetLowering::ArgListTy Args;
17046 TargetLowering::ArgListEntry Entry;
17047 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
17048 EVT ArgVT = Op->getOperand(i).getValueType();
17049 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
17050 "Unexpected argument type for lowering");
17051 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
17052 Entry.Node = StackPtr;
17053 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
17055 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17056 Entry.Ty = PointerType::get(ArgTy,0);
17057 Entry.isSExt = false;
17058 Entry.isZExt = false;
17059 Args.push_back(Entry);
17062 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
17063 getPointerTy(DAG.getDataLayout()));
17065 TargetLowering::CallLoweringInfo CLI(DAG);
17066 CLI.setDebugLoc(dl).setChain(InChain)
17067 .setCallee(getLibcallCallingConv(LC),
17068 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
17069 Callee, std::move(Args), 0)
17070 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
17072 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
17073 return DAG.getBitcast(VT, CallInfo.first);
17076 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
17077 SelectionDAG &DAG) {
17078 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
17079 EVT VT = Op0.getValueType();
17082 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
17083 (VT == MVT::v8i32 && Subtarget->hasInt256()));
17085 // PMULxD operations multiply each even value (starting at 0) of LHS with
17086 // the related value of RHS and produce a widen result.
17087 // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17088 // => <2 x i64> <ae|cg>
17090 // In other word, to have all the results, we need to perform two PMULxD:
17091 // 1. one with the even values.
17092 // 2. one with the odd values.
17093 // To achieve #2, with need to place the odd values at an even position.
17095 // Place the odd value at an even position (basically, shift all values 1
17096 // step to the left):
17097 const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
17098 // <a|b|c|d> => <b|undef|d|undef>
17099 SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
17100 // <e|f|g|h> => <f|undef|h|undef>
17101 SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
17103 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
17105 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
17106 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
17108 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
17109 // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17110 // => <2 x i64> <ae|cg>
17111 SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
17112 // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
17113 // => <2 x i64> <bf|dh>
17114 SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
17116 // Shuffle it back into the right order.
17117 SDValue Highs, Lows;
17118 if (VT == MVT::v8i32) {
17119 const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
17120 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17121 const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
17122 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17124 const int HighMask[] = {1, 5, 3, 7};
17125 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17126 const int LowMask[] = {0, 4, 2, 6};
17127 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17130 // If we have a signed multiply but no PMULDQ fix up the high parts of a
17131 // unsigned multiply.
17132 if (IsSigned && !Subtarget->hasSSE41()) {
17133 SDValue ShAmt = DAG.getConstant(
17135 DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
17136 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
17137 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
17138 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
17139 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
17141 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
17142 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
17145 // The first result of MUL_LOHI is actually the low value, followed by the
17147 SDValue Ops[] = {Lows, Highs};
17148 return DAG.getMergeValues(Ops, dl);
17151 // Return true if the required (according to Opcode) shift-imm form is natively
17152 // supported by the Subtarget
17153 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
17155 if (VT.getScalarSizeInBits() < 16)
17158 if (VT.is512BitVector() &&
17159 (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
17162 bool LShift = VT.is128BitVector() ||
17163 (VT.is256BitVector() && Subtarget->hasInt256());
17165 bool AShift = LShift && (Subtarget->hasVLX() ||
17166 (VT != MVT::v2i64 && VT != MVT::v4i64));
17167 return (Opcode == ISD::SRA) ? AShift : LShift;
17170 // The shift amount is a variable, but it is the same for all vector lanes.
17171 // These instructions are defined together with shift-immediate.
17173 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
17175 return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
17178 // Return true if the required (according to Opcode) variable-shift form is
17179 // natively supported by the Subtarget
17180 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
17183 if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
17186 // vXi16 supported only on AVX-512, BWI
17187 if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
17190 if (VT.is512BitVector() || Subtarget->hasVLX())
17193 bool LShift = VT.is128BitVector() || VT.is256BitVector();
17194 bool AShift = LShift && VT != MVT::v2i64 && VT != MVT::v4i64;
17195 return (Opcode == ISD::SRA) ? AShift : LShift;
17198 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
17199 const X86Subtarget *Subtarget) {
17200 MVT VT = Op.getSimpleValueType();
17202 SDValue R = Op.getOperand(0);
17203 SDValue Amt = Op.getOperand(1);
17205 unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17206 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17208 auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
17209 assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
17210 MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
17211 SDValue Ex = DAG.getBitcast(ExVT, R);
17213 if (ShiftAmt >= 32) {
17214 // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
17216 getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
17217 SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17218 ShiftAmt - 32, DAG);
17219 if (VT == MVT::v2i64)
17220 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
17221 if (VT == MVT::v4i64)
17222 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17223 {9, 1, 11, 3, 13, 5, 15, 7});
17225 // SRA upper i32, SHL whole i64 and select lower i32.
17226 SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17229 getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
17230 Lower = DAG.getBitcast(ExVT, Lower);
17231 if (VT == MVT::v2i64)
17232 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
17233 if (VT == MVT::v4i64)
17234 Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17235 {8, 1, 10, 3, 12, 5, 14, 7});
17237 return DAG.getBitcast(VT, Ex);
17240 // Optimize shl/srl/sra with constant shift amount.
17241 if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
17242 if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
17243 uint64_t ShiftAmt = ShiftConst->getZExtValue();
17245 if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17246 return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17248 // i64 SRA needs to be performed as partial shifts.
17249 if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17250 Op.getOpcode() == ISD::SRA)
17251 return ArithmeticShiftRight64(ShiftAmt);
17253 if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
17254 unsigned NumElts = VT.getVectorNumElements();
17255 MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
17257 if (Op.getOpcode() == ISD::SHL) {
17258 // Simple i8 add case
17260 return DAG.getNode(ISD::ADD, dl, VT, R, R);
17262 // Make a large shift.
17263 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
17265 SHL = DAG.getBitcast(VT, SHL);
17266 // Zero out the rightmost bits.
17267 SmallVector<SDValue, 32> V(
17268 NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
17269 return DAG.getNode(ISD::AND, dl, VT, SHL,
17270 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17272 if (Op.getOpcode() == ISD::SRL) {
17273 // Make a large shift.
17274 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
17276 SRL = DAG.getBitcast(VT, SRL);
17277 // Zero out the leftmost bits.
17278 SmallVector<SDValue, 32> V(
17279 NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
17280 return DAG.getNode(ISD::AND, dl, VT, SRL,
17281 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17283 if (Op.getOpcode() == ISD::SRA) {
17284 if (ShiftAmt == 7) {
17285 // ashr(R, 7) === cmp_slt(R, 0)
17286 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17287 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
17290 // ashr(R, Amt) === sub(xor(lshr(R, Amt), Mask), Mask)
17291 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17292 SmallVector<SDValue, 32> V(NumElts,
17293 DAG.getConstant(128 >> ShiftAmt, dl,
17295 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
17296 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
17297 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
17300 llvm_unreachable("Unknown shift opcode.");
17305 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17306 if (!Subtarget->is64Bit() &&
17307 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64))) {
17309 // Peek through any splat that was introduced for i64 shift vectorization.
17310 int SplatIndex = -1;
17311 if (ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt.getNode()))
17312 if (SVN->isSplat()) {
17313 SplatIndex = SVN->getSplatIndex();
17314 Amt = Amt.getOperand(0);
17315 assert(SplatIndex < (int)VT.getVectorNumElements() &&
17316 "Splat shuffle referencing second operand");
17319 if (Amt.getOpcode() != ISD::BITCAST ||
17320 Amt.getOperand(0).getOpcode() != ISD::BUILD_VECTOR)
17323 Amt = Amt.getOperand(0);
17324 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17325 VT.getVectorNumElements();
17326 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
17327 uint64_t ShiftAmt = 0;
17328 unsigned BaseOp = (SplatIndex < 0 ? 0 : SplatIndex * Ratio);
17329 for (unsigned i = 0; i != Ratio; ++i) {
17330 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + BaseOp));
17334 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
17337 // Check remaining shift amounts (if not a splat).
17338 if (SplatIndex < 0) {
17339 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17340 uint64_t ShAmt = 0;
17341 for (unsigned j = 0; j != Ratio; ++j) {
17342 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
17346 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
17348 if (ShAmt != ShiftAmt)
17353 if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17354 return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17356 if (Op.getOpcode() == ISD::SRA)
17357 return ArithmeticShiftRight64(ShiftAmt);
17363 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
17364 const X86Subtarget* Subtarget) {
17365 MVT VT = Op.getSimpleValueType();
17367 SDValue R = Op.getOperand(0);
17368 SDValue Amt = Op.getOperand(1);
17370 unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17371 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17373 unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
17374 (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
17376 if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
17378 EVT EltVT = VT.getVectorElementType();
17380 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
17381 // Check if this build_vector node is doing a splat.
17382 // If so, then set BaseShAmt equal to the splat value.
17383 BaseShAmt = BV->getSplatValue();
17384 if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
17385 BaseShAmt = SDValue();
17387 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
17388 Amt = Amt.getOperand(0);
17390 ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
17391 if (SVN && SVN->isSplat()) {
17392 unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
17393 SDValue InVec = Amt.getOperand(0);
17394 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
17395 assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
17396 "Unexpected shuffle index found!");
17397 BaseShAmt = InVec.getOperand(SplatIdx);
17398 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
17399 if (ConstantSDNode *C =
17400 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
17401 if (C->getZExtValue() == SplatIdx)
17402 BaseShAmt = InVec.getOperand(1);
17407 // Avoid introducing an extract element from a shuffle.
17408 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
17409 DAG.getIntPtrConstant(SplatIdx, dl));
17413 if (BaseShAmt.getNode()) {
17414 assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
17415 if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
17416 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
17417 else if (EltVT.bitsLT(MVT::i32))
17418 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
17420 return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
17424 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17425 if (!Subtarget->is64Bit() && VT == MVT::v2i64 &&
17426 Amt.getOpcode() == ISD::BITCAST &&
17427 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
17428 Amt = Amt.getOperand(0);
17429 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17430 VT.getVectorNumElements();
17431 std::vector<SDValue> Vals(Ratio);
17432 for (unsigned i = 0; i != Ratio; ++i)
17433 Vals[i] = Amt.getOperand(i);
17434 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17435 for (unsigned j = 0; j != Ratio; ++j)
17436 if (Vals[j] != Amt.getOperand(i + j))
17440 if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
17441 return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
17446 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
17447 SelectionDAG &DAG) {
17448 MVT VT = Op.getSimpleValueType();
17450 SDValue R = Op.getOperand(0);
17451 SDValue Amt = Op.getOperand(1);
17453 assert(VT.isVector() && "Custom lowering only for vector shifts!");
17454 assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
17456 if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
17459 if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
17462 if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
17465 // 2i64 vector logical shifts can efficiently avoid scalarization - do the
17466 // shifts per-lane and then shuffle the partial results back together.
17467 if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
17468 // Splat the shift amounts so the scalar shifts above will catch it.
17469 SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
17470 SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
17471 SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
17472 SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
17473 return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
17476 // i64 vector arithmetic shift can be emulated with the transform:
17477 // M = lshr(SIGN_BIT, Amt)
17478 // ashr(R, Amt) === sub(xor(lshr(R, Amt), M), M)
17479 if ((VT == MVT::v2i64 || (VT == MVT::v4i64 && Subtarget->hasInt256())) &&
17480 Op.getOpcode() == ISD::SRA) {
17481 SDValue S = DAG.getConstant(APInt::getSignBit(64), dl, VT);
17482 SDValue M = DAG.getNode(ISD::SRL, dl, VT, S, Amt);
17483 R = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17484 R = DAG.getNode(ISD::XOR, dl, VT, R, M);
17485 R = DAG.getNode(ISD::SUB, dl, VT, R, M);
17489 // If possible, lower this packed shift into a vector multiply instead of
17490 // expanding it into a sequence of scalar shifts.
17491 // Do this only if the vector shift count is a constant build_vector.
17492 if (Op.getOpcode() == ISD::SHL &&
17493 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
17494 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
17495 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17496 SmallVector<SDValue, 8> Elts;
17497 EVT SVT = VT.getScalarType();
17498 unsigned SVTBits = SVT.getSizeInBits();
17499 const APInt &One = APInt(SVTBits, 1);
17500 unsigned NumElems = VT.getVectorNumElements();
17502 for (unsigned i=0; i !=NumElems; ++i) {
17503 SDValue Op = Amt->getOperand(i);
17504 if (Op->getOpcode() == ISD::UNDEF) {
17505 Elts.push_back(Op);
17509 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
17510 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
17511 uint64_t ShAmt = C.getZExtValue();
17512 if (ShAmt >= SVTBits) {
17513 Elts.push_back(DAG.getUNDEF(SVT));
17516 Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
17518 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
17519 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
17522 // Lower SHL with variable shift amount.
17523 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
17524 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
17526 Op = DAG.getNode(ISD::ADD, dl, VT, Op,
17527 DAG.getConstant(0x3f800000U, dl, VT));
17528 Op = DAG.getBitcast(MVT::v4f32, Op);
17529 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
17530 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
17533 // If possible, lower this shift as a sequence of two shifts by
17534 // constant plus a MOVSS/MOVSD instead of scalarizing it.
17536 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
17538 // Could be rewritten as:
17539 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
17541 // The advantage is that the two shifts from the example would be
17542 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
17543 // the vector shift into four scalar shifts plus four pairs of vector
17545 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
17546 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17547 unsigned TargetOpcode = X86ISD::MOVSS;
17548 bool CanBeSimplified;
17549 // The splat value for the first packed shift (the 'X' from the example).
17550 SDValue Amt1 = Amt->getOperand(0);
17551 // The splat value for the second packed shift (the 'Y' from the example).
17552 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
17553 Amt->getOperand(2);
17555 // See if it is possible to replace this node with a sequence of
17556 // two shifts followed by a MOVSS/MOVSD
17557 if (VT == MVT::v4i32) {
17558 // Check if it is legal to use a MOVSS.
17559 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
17560 Amt2 == Amt->getOperand(3);
17561 if (!CanBeSimplified) {
17562 // Otherwise, check if we can still simplify this node using a MOVSD.
17563 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
17564 Amt->getOperand(2) == Amt->getOperand(3);
17565 TargetOpcode = X86ISD::MOVSD;
17566 Amt2 = Amt->getOperand(2);
17569 // Do similar checks for the case where the machine value type
17571 CanBeSimplified = Amt1 == Amt->getOperand(1);
17572 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
17573 CanBeSimplified = Amt2 == Amt->getOperand(i);
17575 if (!CanBeSimplified) {
17576 TargetOpcode = X86ISD::MOVSD;
17577 CanBeSimplified = true;
17578 Amt2 = Amt->getOperand(4);
17579 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
17580 CanBeSimplified = Amt1 == Amt->getOperand(i);
17581 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
17582 CanBeSimplified = Amt2 == Amt->getOperand(j);
17586 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
17587 isa<ConstantSDNode>(Amt2)) {
17588 // Replace this node with two shifts followed by a MOVSS/MOVSD.
17589 EVT CastVT = MVT::v4i32;
17591 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
17592 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
17594 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
17595 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
17596 if (TargetOpcode == X86ISD::MOVSD)
17597 CastVT = MVT::v2i64;
17598 SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
17599 SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
17600 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
17602 return DAG.getBitcast(VT, Result);
17606 // v4i32 Non Uniform Shifts.
17607 // If the shift amount is constant we can shift each lane using the SSE2
17608 // immediate shifts, else we need to zero-extend each lane to the lower i64
17609 // and shift using the SSE2 variable shifts.
17610 // The separate results can then be blended together.
17611 if (VT == MVT::v4i32) {
17612 unsigned Opc = Op.getOpcode();
17613 SDValue Amt0, Amt1, Amt2, Amt3;
17614 if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17615 Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
17616 Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
17617 Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
17618 Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
17620 // ISD::SHL is handled above but we include it here for completeness.
17623 llvm_unreachable("Unknown target vector shift node");
17625 Opc = X86ISD::VSHL;
17628 Opc = X86ISD::VSRL;
17631 Opc = X86ISD::VSRA;
17634 // The SSE2 shifts use the lower i64 as the same shift amount for
17635 // all lanes and the upper i64 is ignored. These shuffle masks
17636 // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
17637 SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
17638 Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
17639 Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
17640 Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
17641 Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
17644 SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
17645 SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
17646 SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
17647 SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
17648 SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
17649 SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
17650 return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
17653 if (VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget->hasInt256())) {
17654 MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
17655 unsigned ShiftOpcode = Op->getOpcode();
17657 auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
17658 // On SSE41 targets we make use of the fact that VSELECT lowers
17659 // to PBLENDVB which selects bytes based just on the sign bit.
17660 if (Subtarget->hasSSE41()) {
17661 V0 = DAG.getBitcast(VT, V0);
17662 V1 = DAG.getBitcast(VT, V1);
17663 Sel = DAG.getBitcast(VT, Sel);
17664 return DAG.getBitcast(SelVT,
17665 DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
17667 // On pre-SSE41 targets we test for the sign bit by comparing to
17668 // zero - a negative value will set all bits of the lanes to true
17669 // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
17670 SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
17671 SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
17672 return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
17675 // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
17676 // We can safely do this using i16 shifts as we're only interested in
17677 // the 3 lower bits of each byte.
17678 Amt = DAG.getBitcast(ExtVT, Amt);
17679 Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
17680 Amt = DAG.getBitcast(VT, Amt);
17682 if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
17683 // r = VSELECT(r, shift(r, 4), a);
17685 DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
17686 R = SignBitSelect(VT, Amt, M, R);
17689 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17691 // r = VSELECT(r, shift(r, 2), a);
17692 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
17693 R = SignBitSelect(VT, Amt, M, R);
17696 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17698 // return VSELECT(r, shift(r, 1), a);
17699 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
17700 R = SignBitSelect(VT, Amt, M, R);
17704 if (Op->getOpcode() == ISD::SRA) {
17705 // For SRA we need to unpack each byte to the higher byte of a i16 vector
17706 // so we can correctly sign extend. We don't care what happens to the
17708 SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
17709 SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
17710 SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
17711 SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
17712 ALo = DAG.getBitcast(ExtVT, ALo);
17713 AHi = DAG.getBitcast(ExtVT, AHi);
17714 RLo = DAG.getBitcast(ExtVT, RLo);
17715 RHi = DAG.getBitcast(ExtVT, RHi);
17717 // r = VSELECT(r, shift(r, 4), a);
17718 SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17719 DAG.getConstant(4, dl, ExtVT));
17720 SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17721 DAG.getConstant(4, dl, ExtVT));
17722 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17723 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17726 ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17727 AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17729 // r = VSELECT(r, shift(r, 2), a);
17730 MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17731 DAG.getConstant(2, dl, ExtVT));
17732 MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17733 DAG.getConstant(2, dl, ExtVT));
17734 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17735 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17738 ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17739 AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17741 // r = VSELECT(r, shift(r, 1), a);
17742 MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17743 DAG.getConstant(1, dl, ExtVT));
17744 MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17745 DAG.getConstant(1, dl, ExtVT));
17746 RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17747 RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17749 // Logical shift the result back to the lower byte, leaving a zero upper
17751 // meaning that we can safely pack with PACKUSWB.
17753 DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
17755 DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
17756 return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17760 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
17761 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
17762 // solution better.
17763 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
17764 MVT ExtVT = MVT::v8i32;
17766 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
17767 R = DAG.getNode(ExtOpc, dl, ExtVT, R);
17768 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
17769 return DAG.getNode(ISD::TRUNCATE, dl, VT,
17770 DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
17773 if (Subtarget->hasInt256() && VT == MVT::v16i16) {
17774 MVT ExtVT = MVT::v8i32;
17775 SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
17776 SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
17777 SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
17778 SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
17779 SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
17780 ALo = DAG.getBitcast(ExtVT, ALo);
17781 AHi = DAG.getBitcast(ExtVT, AHi);
17782 RLo = DAG.getBitcast(ExtVT, RLo);
17783 RHi = DAG.getBitcast(ExtVT, RHi);
17784 SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
17785 SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
17786 Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
17787 Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
17788 return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
17791 if (VT == MVT::v8i16) {
17792 unsigned ShiftOpcode = Op->getOpcode();
17794 auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
17795 // On SSE41 targets we make use of the fact that VSELECT lowers
17796 // to PBLENDVB which selects bytes based just on the sign bit.
17797 if (Subtarget->hasSSE41()) {
17798 MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
17799 V0 = DAG.getBitcast(ExtVT, V0);
17800 V1 = DAG.getBitcast(ExtVT, V1);
17801 Sel = DAG.getBitcast(ExtVT, Sel);
17802 return DAG.getBitcast(
17803 VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
17805 // On pre-SSE41 targets we splat the sign bit - a negative value will
17806 // set all bits of the lanes to true and VSELECT uses that in
17807 // its OR(AND(V0,C),AND(V1,~C)) lowering.
17809 DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
17810 return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
17813 // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
17814 if (Subtarget->hasSSE41()) {
17815 // On SSE41 targets we need to replicate the shift mask in both
17816 // bytes for PBLENDVB.
17819 DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
17820 DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
17822 Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
17825 // r = VSELECT(r, shift(r, 8), a);
17826 SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
17827 R = SignBitSelect(Amt, M, R);
17830 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17832 // r = VSELECT(r, shift(r, 4), a);
17833 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
17834 R = SignBitSelect(Amt, M, R);
17837 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17839 // r = VSELECT(r, shift(r, 2), a);
17840 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
17841 R = SignBitSelect(Amt, M, R);
17844 Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17846 // return VSELECT(r, shift(r, 1), a);
17847 M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
17848 R = SignBitSelect(Amt, M, R);
17852 // Decompose 256-bit shifts into smaller 128-bit shifts.
17853 if (VT.is256BitVector()) {
17854 unsigned NumElems = VT.getVectorNumElements();
17855 MVT EltVT = VT.getVectorElementType();
17856 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17858 // Extract the two vectors
17859 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
17860 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
17862 // Recreate the shift amount vectors
17863 SDValue Amt1, Amt2;
17864 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
17865 // Constant shift amount
17866 SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
17867 ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
17868 ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
17870 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
17871 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
17873 // Variable shift amount
17874 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
17875 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
17878 // Issue new vector shifts for the smaller types
17879 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
17880 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
17882 // Concatenate the result back
17883 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
17889 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
17890 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
17891 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
17892 // looks for this combo and may remove the "setcc" instruction if the "setcc"
17893 // has only one use.
17894 SDNode *N = Op.getNode();
17895 SDValue LHS = N->getOperand(0);
17896 SDValue RHS = N->getOperand(1);
17897 unsigned BaseOp = 0;
17900 switch (Op.getOpcode()) {
17901 default: llvm_unreachable("Unknown ovf instruction!");
17903 // A subtract of one will be selected as a INC. Note that INC doesn't
17904 // set CF, so we can't do this for UADDO.
17905 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
17907 BaseOp = X86ISD::INC;
17908 Cond = X86::COND_O;
17911 BaseOp = X86ISD::ADD;
17912 Cond = X86::COND_O;
17915 BaseOp = X86ISD::ADD;
17916 Cond = X86::COND_B;
17919 // A subtract of one will be selected as a DEC. Note that DEC doesn't
17920 // set CF, so we can't do this for USUBO.
17921 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
17923 BaseOp = X86ISD::DEC;
17924 Cond = X86::COND_O;
17927 BaseOp = X86ISD::SUB;
17928 Cond = X86::COND_O;
17931 BaseOp = X86ISD::SUB;
17932 Cond = X86::COND_B;
17935 BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
17936 Cond = X86::COND_O;
17938 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
17939 if (N->getValueType(0) == MVT::i8) {
17940 BaseOp = X86ISD::UMUL8;
17941 Cond = X86::COND_O;
17944 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
17946 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
17949 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17950 DAG.getConstant(X86::COND_O, DL, MVT::i32),
17951 SDValue(Sum.getNode(), 2));
17953 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
17957 // Also sets EFLAGS.
17958 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
17959 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
17962 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
17963 DAG.getConstant(Cond, DL, MVT::i32),
17964 SDValue(Sum.getNode(), 1));
17966 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
17969 /// Returns true if the operand type is exactly twice the native width, and
17970 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
17971 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
17972 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
17973 bool X86TargetLowering::needsCmpXchgNb(Type *MemType) const {
17974 unsigned OpWidth = MemType->getPrimitiveSizeInBits();
17977 return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
17978 else if (OpWidth == 128)
17979 return Subtarget->hasCmpxchg16b();
17984 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
17985 return needsCmpXchgNb(SI->getValueOperand()->getType());
17988 // Note: this turns large loads into lock cmpxchg8b/16b.
17989 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
17990 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
17991 auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
17992 return needsCmpXchgNb(PTy->getElementType());
17995 TargetLoweringBase::AtomicRMWExpansionKind
17996 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
17997 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
17998 Type *MemType = AI->getType();
18000 // If the operand is too big, we must see if cmpxchg8/16b is available
18001 // and default to library calls otherwise.
18002 if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
18003 return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
18004 : AtomicRMWExpansionKind::None;
18007 AtomicRMWInst::BinOp Op = AI->getOperation();
18010 llvm_unreachable("Unknown atomic operation");
18011 case AtomicRMWInst::Xchg:
18012 case AtomicRMWInst::Add:
18013 case AtomicRMWInst::Sub:
18014 // It's better to use xadd, xsub or xchg for these in all cases.
18015 return AtomicRMWExpansionKind::None;
18016 case AtomicRMWInst::Or:
18017 case AtomicRMWInst::And:
18018 case AtomicRMWInst::Xor:
18019 // If the atomicrmw's result isn't actually used, we can just add a "lock"
18020 // prefix to a normal instruction for these operations.
18021 return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
18022 : AtomicRMWExpansionKind::None;
18023 case AtomicRMWInst::Nand:
18024 case AtomicRMWInst::Max:
18025 case AtomicRMWInst::Min:
18026 case AtomicRMWInst::UMax:
18027 case AtomicRMWInst::UMin:
18028 // These always require a non-trivial set of data operations on x86. We must
18029 // use a cmpxchg loop.
18030 return AtomicRMWExpansionKind::CmpXChg;
18034 static bool hasMFENCE(const X86Subtarget& Subtarget) {
18035 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
18036 // no-sse2). There isn't any reason to disable it if the target processor
18038 return Subtarget.hasSSE2() || Subtarget.is64Bit();
18042 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
18043 unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18044 Type *MemType = AI->getType();
18045 // Accesses larger than the native width are turned into cmpxchg/libcalls, so
18046 // there is no benefit in turning such RMWs into loads, and it is actually
18047 // harmful as it introduces a mfence.
18048 if (MemType->getPrimitiveSizeInBits() > NativeWidth)
18051 auto Builder = IRBuilder<>(AI);
18052 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18053 auto SynchScope = AI->getSynchScope();
18054 // We must restrict the ordering to avoid generating loads with Release or
18055 // ReleaseAcquire orderings.
18056 auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
18057 auto Ptr = AI->getPointerOperand();
18059 // Before the load we need a fence. Here is an example lifted from
18060 // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
18063 // x.store(1, relaxed);
18064 // r1 = y.fetch_add(0, release);
18066 // y.fetch_add(42, acquire);
18067 // r2 = x.load(relaxed);
18068 // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
18069 // lowered to just a load without a fence. A mfence flushes the store buffer,
18070 // making the optimization clearly correct.
18071 // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
18072 // otherwise, we might be able to be more aggressive on relaxed idempotent
18073 // rmw. In practice, they do not look useful, so we don't try to be
18074 // especially clever.
18075 if (SynchScope == SingleThread)
18076 // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
18077 // the IR level, so we must wrap it in an intrinsic.
18080 if (!hasMFENCE(*Subtarget))
18081 // FIXME: it might make sense to use a locked operation here but on a
18082 // different cache-line to prevent cache-line bouncing. In practice it
18083 // is probably a small win, and x86 processors without mfence are rare
18084 // enough that we do not bother.
18088 llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
18089 Builder.CreateCall(MFence, {});
18091 // Finally we can emit the atomic load.
18092 LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
18093 AI->getType()->getPrimitiveSizeInBits());
18094 Loaded->setAtomic(Order, SynchScope);
18095 AI->replaceAllUsesWith(Loaded);
18096 AI->eraseFromParent();
18100 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
18101 SelectionDAG &DAG) {
18103 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
18104 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
18105 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
18106 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
18108 // The only fence that needs an instruction is a sequentially-consistent
18109 // cross-thread fence.
18110 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
18111 if (hasMFENCE(*Subtarget))
18112 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
18114 SDValue Chain = Op.getOperand(0);
18115 SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
18117 DAG.getRegister(X86::ESP, MVT::i32), // Base
18118 DAG.getTargetConstant(1, dl, MVT::i8), // Scale
18119 DAG.getRegister(0, MVT::i32), // Index
18120 DAG.getTargetConstant(0, dl, MVT::i32), // Disp
18121 DAG.getRegister(0, MVT::i32), // Segment.
18125 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
18126 return SDValue(Res, 0);
18129 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
18130 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
18133 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
18134 SelectionDAG &DAG) {
18135 MVT T = Op.getSimpleValueType();
18139 switch(T.SimpleTy) {
18140 default: llvm_unreachable("Invalid value type!");
18141 case MVT::i8: Reg = X86::AL; size = 1; break;
18142 case MVT::i16: Reg = X86::AX; size = 2; break;
18143 case MVT::i32: Reg = X86::EAX; size = 4; break;
18145 assert(Subtarget->is64Bit() && "Node not type legal!");
18146 Reg = X86::RAX; size = 8;
18149 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
18150 Op.getOperand(2), SDValue());
18151 SDValue Ops[] = { cpIn.getValue(0),
18154 DAG.getTargetConstant(size, DL, MVT::i8),
18155 cpIn.getValue(1) };
18156 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18157 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
18158 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
18162 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
18163 SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
18164 MVT::i32, cpOut.getValue(2));
18165 SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
18166 DAG.getConstant(X86::COND_E, DL, MVT::i8),
18169 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
18170 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
18171 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
18175 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
18176 SelectionDAG &DAG) {
18177 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
18178 MVT DstVT = Op.getSimpleValueType();
18180 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
18181 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18182 if (DstVT != MVT::f64)
18183 // This conversion needs to be expanded.
18186 SDValue InVec = Op->getOperand(0);
18188 unsigned NumElts = SrcVT.getVectorNumElements();
18189 EVT SVT = SrcVT.getVectorElementType();
18191 // Widen the vector in input in the case of MVT::v2i32.
18192 // Example: from MVT::v2i32 to MVT::v4i32.
18193 SmallVector<SDValue, 16> Elts;
18194 for (unsigned i = 0, e = NumElts; i != e; ++i)
18195 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
18196 DAG.getIntPtrConstant(i, dl)));
18198 // Explicitly mark the extra elements as Undef.
18199 Elts.append(NumElts, DAG.getUNDEF(SVT));
18201 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18202 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
18203 SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
18204 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
18205 DAG.getIntPtrConstant(0, dl));
18208 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
18209 Subtarget->hasMMX() && "Unexpected custom BITCAST");
18210 assert((DstVT == MVT::i64 ||
18211 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
18212 "Unexpected custom BITCAST");
18213 // i64 <=> MMX conversions are Legal.
18214 if (SrcVT==MVT::i64 && DstVT.isVector())
18216 if (DstVT==MVT::i64 && SrcVT.isVector())
18218 // MMX <=> MMX conversions are Legal.
18219 if (SrcVT.isVector() && DstVT.isVector())
18221 // All other conversions need to be expanded.
18225 /// Compute the horizontal sum of bytes in V for the elements of VT.
18227 /// Requires V to be a byte vector and VT to be an integer vector type with
18228 /// wider elements than V's type. The width of the elements of VT determines
18229 /// how many bytes of V are summed horizontally to produce each element of the
18231 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
18232 const X86Subtarget *Subtarget,
18233 SelectionDAG &DAG) {
18235 MVT ByteVecVT = V.getSimpleValueType();
18236 MVT EltVT = VT.getVectorElementType();
18237 int NumElts = VT.getVectorNumElements();
18238 assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
18239 "Expected value to have byte element type.");
18240 assert(EltVT != MVT::i8 &&
18241 "Horizontal byte sum only makes sense for wider elements!");
18242 unsigned VecSize = VT.getSizeInBits();
18243 assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
18245 // PSADBW instruction horizontally add all bytes and leave the result in i64
18246 // chunks, thus directly computes the pop count for v2i64 and v4i64.
18247 if (EltVT == MVT::i64) {
18248 SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18249 V = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT, V, Zeros);
18250 return DAG.getBitcast(VT, V);
18253 if (EltVT == MVT::i32) {
18254 // We unpack the low half and high half into i32s interleaved with zeros so
18255 // that we can use PSADBW to horizontally sum them. The most useful part of
18256 // this is that it lines up the results of two PSADBW instructions to be
18257 // two v2i64 vectors which concatenated are the 4 population counts. We can
18258 // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
18259 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
18260 SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
18261 SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
18263 // Do the horizontal sums into two v2i64s.
18264 Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18265 Low = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18266 DAG.getBitcast(ByteVecVT, Low), Zeros);
18267 High = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18268 DAG.getBitcast(ByteVecVT, High), Zeros);
18270 // Merge them together.
18271 MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
18272 V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
18273 DAG.getBitcast(ShortVecVT, Low),
18274 DAG.getBitcast(ShortVecVT, High));
18276 return DAG.getBitcast(VT, V);
18279 // The only element type left is i16.
18280 assert(EltVT == MVT::i16 && "Unknown how to handle type");
18282 // To obtain pop count for each i16 element starting from the pop count for
18283 // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
18284 // right by 8. It is important to shift as i16s as i8 vector shift isn't
18285 // directly supported.
18286 SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
18287 SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
18288 SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18289 V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
18290 DAG.getBitcast(ByteVecVT, V));
18291 return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18294 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
18295 const X86Subtarget *Subtarget,
18296 SelectionDAG &DAG) {
18297 MVT VT = Op.getSimpleValueType();
18298 MVT EltVT = VT.getVectorElementType();
18299 unsigned VecSize = VT.getSizeInBits();
18301 // Implement a lookup table in register by using an algorithm based on:
18302 // http://wm.ite.pl/articles/sse-popcount.html
18304 // The general idea is that every lower byte nibble in the input vector is an
18305 // index into a in-register pre-computed pop count table. We then split up the
18306 // input vector in two new ones: (1) a vector with only the shifted-right
18307 // higher nibbles for each byte and (2) a vector with the lower nibbles (and
18308 // masked out higher ones) for each byte. PSHUB is used separately with both
18309 // to index the in-register table. Next, both are added and the result is a
18310 // i8 vector where each element contains the pop count for input byte.
18312 // To obtain the pop count for elements != i8, we follow up with the same
18313 // approach and use additional tricks as described below.
18315 const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
18316 /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
18317 /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
18318 /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
18320 int NumByteElts = VecSize / 8;
18321 MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
18322 SDValue In = DAG.getBitcast(ByteVecVT, Op);
18323 SmallVector<SDValue, 16> LUTVec;
18324 for (int i = 0; i < NumByteElts; ++i)
18325 LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
18326 SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
18327 SmallVector<SDValue, 16> Mask0F(NumByteElts,
18328 DAG.getConstant(0x0F, DL, MVT::i8));
18329 SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
18332 SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
18333 SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
18334 SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
18337 SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
18339 // The input vector is used as the shuffle mask that index elements into the
18340 // LUT. After counting low and high nibbles, add the vector to obtain the
18341 // final pop count per i8 element.
18342 SDValue HighPopCnt =
18343 DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
18344 SDValue LowPopCnt =
18345 DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
18346 SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
18348 if (EltVT == MVT::i8)
18351 return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
18354 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
18355 const X86Subtarget *Subtarget,
18356 SelectionDAG &DAG) {
18357 MVT VT = Op.getSimpleValueType();
18358 assert(VT.is128BitVector() &&
18359 "Only 128-bit vector bitmath lowering supported.");
18361 int VecSize = VT.getSizeInBits();
18362 MVT EltVT = VT.getVectorElementType();
18363 int Len = EltVT.getSizeInBits();
18365 // This is the vectorized version of the "best" algorithm from
18366 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
18367 // with a minor tweak to use a series of adds + shifts instead of vector
18368 // multiplications. Implemented for all integer vector types. We only use
18369 // this when we don't have SSSE3 which allows a LUT-based lowering that is
18370 // much faster, even faster than using native popcnt instructions.
18372 auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
18373 MVT VT = V.getSimpleValueType();
18374 SmallVector<SDValue, 32> Shifters(
18375 VT.getVectorNumElements(),
18376 DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
18377 return DAG.getNode(OpCode, DL, VT, V,
18378 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
18380 auto GetMask = [&](SDValue V, APInt Mask) {
18381 MVT VT = V.getSimpleValueType();
18382 SmallVector<SDValue, 32> Masks(
18383 VT.getVectorNumElements(),
18384 DAG.getConstant(Mask, DL, VT.getVectorElementType()));
18385 return DAG.getNode(ISD::AND, DL, VT, V,
18386 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
18389 // We don't want to incur the implicit masks required to SRL vNi8 vectors on
18390 // x86, so set the SRL type to have elements at least i16 wide. This is
18391 // correct because all of our SRLs are followed immediately by a mask anyways
18392 // that handles any bits that sneak into the high bits of the byte elements.
18393 MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
18397 // v = v - ((v >> 1) & 0x55555555...)
18399 DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
18400 SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
18401 V = DAG.getNode(ISD::SUB, DL, VT, V, And);
18403 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
18404 SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
18405 Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
18406 SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
18407 V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
18409 // v = (v + (v >> 4)) & 0x0F0F0F0F...
18410 Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
18411 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
18412 V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
18414 // At this point, V contains the byte-wise population count, and we are
18415 // merely doing a horizontal sum if necessary to get the wider element
18417 if (EltVT == MVT::i8)
18420 return LowerHorizontalByteSum(
18421 DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
18425 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18426 SelectionDAG &DAG) {
18427 MVT VT = Op.getSimpleValueType();
18428 // FIXME: Need to add AVX-512 support here!
18429 assert((VT.is256BitVector() || VT.is128BitVector()) &&
18430 "Unknown CTPOP type to handle");
18431 SDLoc DL(Op.getNode());
18432 SDValue Op0 = Op.getOperand(0);
18434 if (!Subtarget->hasSSSE3()) {
18435 // We can't use the fast LUT approach, so fall back on vectorized bitmath.
18436 assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
18437 return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
18440 if (VT.is256BitVector() && !Subtarget->hasInt256()) {
18441 unsigned NumElems = VT.getVectorNumElements();
18443 // Extract each 128-bit vector, compute pop count and concat the result.
18444 SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
18445 SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
18447 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
18448 LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
18449 LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
18452 return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
18455 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18456 SelectionDAG &DAG) {
18457 assert(Op.getValueType().isVector() &&
18458 "We only do custom lowering for vector population count.");
18459 return LowerVectorCTPOP(Op, Subtarget, DAG);
18462 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
18463 SDNode *Node = Op.getNode();
18465 EVT T = Node->getValueType(0);
18466 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
18467 DAG.getConstant(0, dl, T), Node->getOperand(2));
18468 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
18469 cast<AtomicSDNode>(Node)->getMemoryVT(),
18470 Node->getOperand(0),
18471 Node->getOperand(1), negOp,
18472 cast<AtomicSDNode>(Node)->getMemOperand(),
18473 cast<AtomicSDNode>(Node)->getOrdering(),
18474 cast<AtomicSDNode>(Node)->getSynchScope());
18477 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
18478 SDNode *Node = Op.getNode();
18480 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
18482 // Convert seq_cst store -> xchg
18483 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
18484 // FIXME: On 32-bit, store -> fist or movq would be more efficient
18485 // (The only way to get a 16-byte store is cmpxchg16b)
18486 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
18487 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
18488 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
18489 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
18490 cast<AtomicSDNode>(Node)->getMemoryVT(),
18491 Node->getOperand(0),
18492 Node->getOperand(1), Node->getOperand(2),
18493 cast<AtomicSDNode>(Node)->getMemOperand(),
18494 cast<AtomicSDNode>(Node)->getOrdering(),
18495 cast<AtomicSDNode>(Node)->getSynchScope());
18496 return Swap.getValue(1);
18498 // Other atomic stores have a simple pattern.
18502 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
18503 EVT VT = Op.getNode()->getSimpleValueType(0);
18505 // Let legalize expand this if it isn't a legal type yet.
18506 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
18509 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18512 bool ExtraOp = false;
18513 switch (Op.getOpcode()) {
18514 default: llvm_unreachable("Invalid code");
18515 case ISD::ADDC: Opc = X86ISD::ADD; break;
18516 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
18517 case ISD::SUBC: Opc = X86ISD::SUB; break;
18518 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
18522 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18524 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18525 Op.getOperand(1), Op.getOperand(2));
18528 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
18529 SelectionDAG &DAG) {
18530 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
18532 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
18533 // which returns the values as { float, float } (in XMM0) or
18534 // { double, double } (which is returned in XMM0, XMM1).
18536 SDValue Arg = Op.getOperand(0);
18537 EVT ArgVT = Arg.getValueType();
18538 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18540 TargetLowering::ArgListTy Args;
18541 TargetLowering::ArgListEntry Entry;
18545 Entry.isSExt = false;
18546 Entry.isZExt = false;
18547 Args.push_back(Entry);
18549 bool isF64 = ArgVT == MVT::f64;
18550 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
18551 // the small struct {f32, f32} is returned in (eax, edx). For f64,
18552 // the results are returned via SRet in memory.
18553 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
18554 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18556 DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
18558 Type *RetTy = isF64
18559 ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
18560 : (Type*)VectorType::get(ArgTy, 4);
18562 TargetLowering::CallLoweringInfo CLI(DAG);
18563 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
18564 .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
18566 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
18569 // Returned in xmm0 and xmm1.
18570 return CallResult.first;
18572 // Returned in bits 0:31 and 32:64 xmm0.
18573 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18574 CallResult.first, DAG.getIntPtrConstant(0, dl));
18575 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18576 CallResult.first, DAG.getIntPtrConstant(1, dl));
18577 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
18578 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
18581 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
18582 SelectionDAG &DAG) {
18583 assert(Subtarget->hasAVX512() &&
18584 "MGATHER/MSCATTER are supported on AVX-512 arch only");
18586 MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
18587 EVT VT = N->getValue().getValueType();
18588 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
18591 // X86 scatter kills mask register, so its type should be added to
18592 // the list of return values
18593 if (N->getNumValues() == 1) {
18594 SDValue Index = N->getIndex();
18595 if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18596 !Index.getValueType().is512BitVector())
18597 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18599 SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
18600 SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
18601 N->getOperand(3), Index };
18603 SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
18604 DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
18605 return SDValue(NewScatter.getNode(), 0);
18610 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
18611 SelectionDAG &DAG) {
18612 assert(Subtarget->hasAVX512() &&
18613 "MGATHER/MSCATTER are supported on AVX-512 arch only");
18615 MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
18616 EVT VT = Op.getValueType();
18617 assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
18620 SDValue Index = N->getIndex();
18621 if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18622 !Index.getValueType().is512BitVector()) {
18623 Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18624 SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
18625 N->getOperand(3), Index };
18626 DAG.UpdateNodeOperands(N, Ops);
18631 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
18632 SelectionDAG &DAG) const {
18633 // TODO: Eventually, the lowering of these nodes should be informed by or
18634 // deferred to the GC strategy for the function in which they appear. For
18635 // now, however, they must be lowered to something. Since they are logically
18636 // no-ops in the case of a null GC strategy (or a GC strategy which does not
18637 // require special handling for these nodes), lower them as literal NOOPs for
18639 SmallVector<SDValue, 2> Ops;
18641 Ops.push_back(Op.getOperand(0));
18642 if (Op->getGluedNode())
18643 Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18646 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18647 SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18652 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
18653 SelectionDAG &DAG) const {
18654 // TODO: Eventually, the lowering of these nodes should be informed by or
18655 // deferred to the GC strategy for the function in which they appear. For
18656 // now, however, they must be lowered to something. Since they are logically
18657 // no-ops in the case of a null GC strategy (or a GC strategy which does not
18658 // require special handling for these nodes), lower them as literal NOOPs for
18660 SmallVector<SDValue, 2> Ops;
18662 Ops.push_back(Op.getOperand(0));
18663 if (Op->getGluedNode())
18664 Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18667 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18668 SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18673 /// LowerOperation - Provide custom lowering hooks for some operations.
18675 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
18676 switch (Op.getOpcode()) {
18677 default: llvm_unreachable("Should not custom lower this!");
18678 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
18679 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
18680 return LowerCMP_SWAP(Op, Subtarget, DAG);
18681 case ISD::CTPOP: return LowerCTPOP(Op, Subtarget, DAG);
18682 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
18683 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
18684 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
18685 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
18686 case ISD::VECTOR_SHUFFLE: return lowerVectorShuffle(Op, Subtarget, DAG);
18687 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
18688 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
18689 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
18690 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
18691 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
18692 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
18693 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
18694 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
18695 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
18696 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
18697 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
18698 case ISD::SHL_PARTS:
18699 case ISD::SRA_PARTS:
18700 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
18701 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
18702 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
18703 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
18704 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
18705 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
18706 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
18707 case ISD::SIGN_EXTEND_VECTOR_INREG:
18708 return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
18709 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
18710 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
18711 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
18712 case ISD::LOAD: return LowerExtendedLoad(Op, Subtarget, DAG);
18714 case ISD::FNEG: return LowerFABSorFNEG(Op, DAG);
18715 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
18716 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
18717 case ISD::SETCC: return LowerSETCC(Op, DAG);
18718 case ISD::SELECT: return LowerSELECT(Op, DAG);
18719 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
18720 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
18721 case ISD::VASTART: return LowerVASTART(Op, DAG);
18722 case ISD::VAARG: return LowerVAARG(Op, DAG);
18723 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
18724 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
18725 case ISD::INTRINSIC_VOID:
18726 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
18727 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
18728 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
18729 case ISD::FRAME_TO_ARGS_OFFSET:
18730 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
18731 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
18732 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
18733 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
18734 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
18735 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
18736 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
18737 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
18738 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
18739 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
18740 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
18741 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
18742 case ISD::UMUL_LOHI:
18743 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
18746 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
18752 case ISD::UMULO: return LowerXALUO(Op, DAG);
18753 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
18754 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
18758 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
18759 case ISD::ADD: return LowerADD(Op, DAG);
18760 case ISD::SUB: return LowerSUB(Op, DAG);
18761 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
18762 case ISD::MGATHER: return LowerMGATHER(Op, Subtarget, DAG);
18763 case ISD::MSCATTER: return LowerMSCATTER(Op, Subtarget, DAG);
18764 case ISD::GC_TRANSITION_START:
18765 return LowerGC_TRANSITION_START(Op, DAG);
18766 case ISD::GC_TRANSITION_END: return LowerGC_TRANSITION_END(Op, DAG);
18770 /// ReplaceNodeResults - Replace a node with an illegal result type
18771 /// with a new node built out of custom code.
18772 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
18773 SmallVectorImpl<SDValue>&Results,
18774 SelectionDAG &DAG) const {
18776 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18777 switch (N->getOpcode()) {
18779 llvm_unreachable("Do not know how to custom type legalize this operation!");
18780 // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
18781 case X86ISD::FMINC:
18783 case X86ISD::FMAXC:
18784 case X86ISD::FMAX: {
18785 EVT VT = N->getValueType(0);
18786 if (VT != MVT::v2f32)
18787 llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
18788 SDValue UNDEF = DAG.getUNDEF(VT);
18789 SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
18790 N->getOperand(0), UNDEF);
18791 SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
18792 N->getOperand(1), UNDEF);
18793 Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
18796 case ISD::SIGN_EXTEND_INREG:
18801 // We don't want to expand or promote these.
18808 case ISD::UDIVREM: {
18809 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
18810 Results.push_back(V);
18813 case ISD::FP_TO_SINT:
18814 // FP_TO_INT*_IN_MEM is not legal for f16 inputs. Do not convert
18815 // (FP_TO_SINT (load f16)) to FP_TO_INT*.
18816 if (N->getOperand(0).getValueType() == MVT::f16)
18819 case ISD::FP_TO_UINT: {
18820 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
18822 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
18825 std::pair<SDValue,SDValue> Vals =
18826 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
18827 SDValue FIST = Vals.first, StackSlot = Vals.second;
18828 if (FIST.getNode()) {
18829 EVT VT = N->getValueType(0);
18830 // Return a load from the stack slot.
18831 if (StackSlot.getNode())
18832 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
18833 MachinePointerInfo(),
18834 false, false, false, 0));
18836 Results.push_back(FIST);
18840 case ISD::UINT_TO_FP: {
18841 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18842 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
18843 N->getValueType(0) != MVT::v2f32)
18845 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
18847 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
18849 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
18850 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
18851 DAG.getBitcast(MVT::v2i64, VBias));
18852 Or = DAG.getBitcast(MVT::v2f64, Or);
18853 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
18854 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
18857 case ISD::FP_ROUND: {
18858 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
18860 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
18861 Results.push_back(V);
18864 case ISD::FP_EXTEND: {
18865 // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
18866 // No other ValueType for FP_EXTEND should reach this point.
18867 assert(N->getValueType(0) == MVT::v2f32 &&
18868 "Do not know how to legalize this Node");
18871 case ISD::INTRINSIC_W_CHAIN: {
18872 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
18874 default : llvm_unreachable("Do not know how to custom type "
18875 "legalize this intrinsic operation!");
18876 case Intrinsic::x86_rdtsc:
18877 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
18879 case Intrinsic::x86_rdtscp:
18880 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
18882 case Intrinsic::x86_rdpmc:
18883 return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
18886 case ISD::READCYCLECOUNTER: {
18887 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
18890 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
18891 EVT T = N->getValueType(0);
18892 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
18893 bool Regs64bit = T == MVT::i128;
18894 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
18895 SDValue cpInL, cpInH;
18896 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
18897 DAG.getConstant(0, dl, HalfT));
18898 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
18899 DAG.getConstant(1, dl, HalfT));
18900 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
18901 Regs64bit ? X86::RAX : X86::EAX,
18903 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
18904 Regs64bit ? X86::RDX : X86::EDX,
18905 cpInH, cpInL.getValue(1));
18906 SDValue swapInL, swapInH;
18907 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
18908 DAG.getConstant(0, dl, HalfT));
18909 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
18910 DAG.getConstant(1, dl, HalfT));
18911 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
18912 Regs64bit ? X86::RBX : X86::EBX,
18913 swapInL, cpInH.getValue(1));
18914 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
18915 Regs64bit ? X86::RCX : X86::ECX,
18916 swapInH, swapInL.getValue(1));
18917 SDValue Ops[] = { swapInH.getValue(0),
18919 swapInH.getValue(1) };
18920 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18921 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
18922 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
18923 X86ISD::LCMPXCHG8_DAG;
18924 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
18925 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
18926 Regs64bit ? X86::RAX : X86::EAX,
18927 HalfT, Result.getValue(1));
18928 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
18929 Regs64bit ? X86::RDX : X86::EDX,
18930 HalfT, cpOutL.getValue(2));
18931 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
18933 SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
18934 MVT::i32, cpOutH.getValue(2));
18936 DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
18937 DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
18938 Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
18940 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
18941 Results.push_back(Success);
18942 Results.push_back(EFLAGS.getValue(1));
18945 case ISD::ATOMIC_SWAP:
18946 case ISD::ATOMIC_LOAD_ADD:
18947 case ISD::ATOMIC_LOAD_SUB:
18948 case ISD::ATOMIC_LOAD_AND:
18949 case ISD::ATOMIC_LOAD_OR:
18950 case ISD::ATOMIC_LOAD_XOR:
18951 case ISD::ATOMIC_LOAD_NAND:
18952 case ISD::ATOMIC_LOAD_MIN:
18953 case ISD::ATOMIC_LOAD_MAX:
18954 case ISD::ATOMIC_LOAD_UMIN:
18955 case ISD::ATOMIC_LOAD_UMAX:
18956 case ISD::ATOMIC_LOAD: {
18957 // Delegate to generic TypeLegalization. Situations we can really handle
18958 // should have already been dealt with by AtomicExpandPass.cpp.
18961 case ISD::BITCAST: {
18962 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18963 EVT DstVT = N->getValueType(0);
18964 EVT SrcVT = N->getOperand(0)->getValueType(0);
18966 if (SrcVT != MVT::f64 ||
18967 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
18970 unsigned NumElts = DstVT.getVectorNumElements();
18971 EVT SVT = DstVT.getVectorElementType();
18972 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18973 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
18974 MVT::v2f64, N->getOperand(0));
18975 SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
18977 if (ExperimentalVectorWideningLegalization) {
18978 // If we are legalizing vectors by widening, we already have the desired
18979 // legal vector type, just return it.
18980 Results.push_back(ToVecInt);
18984 SmallVector<SDValue, 8> Elts;
18985 for (unsigned i = 0, e = NumElts; i != e; ++i)
18986 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
18987 ToVecInt, DAG.getIntPtrConstant(i, dl)));
18989 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
18994 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
18995 switch ((X86ISD::NodeType)Opcode) {
18996 case X86ISD::FIRST_NUMBER: break;
18997 case X86ISD::BSF: return "X86ISD::BSF";
18998 case X86ISD::BSR: return "X86ISD::BSR";
18999 case X86ISD::SHLD: return "X86ISD::SHLD";
19000 case X86ISD::SHRD: return "X86ISD::SHRD";
19001 case X86ISD::FAND: return "X86ISD::FAND";
19002 case X86ISD::FANDN: return "X86ISD::FANDN";
19003 case X86ISD::FOR: return "X86ISD::FOR";
19004 case X86ISD::FXOR: return "X86ISD::FXOR";
19005 case X86ISD::FILD: return "X86ISD::FILD";
19006 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
19007 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
19008 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
19009 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
19010 case X86ISD::FLD: return "X86ISD::FLD";
19011 case X86ISD::FST: return "X86ISD::FST";
19012 case X86ISD::CALL: return "X86ISD::CALL";
19013 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
19014 case X86ISD::RDTSCP_DAG: return "X86ISD::RDTSCP_DAG";
19015 case X86ISD::RDPMC_DAG: return "X86ISD::RDPMC_DAG";
19016 case X86ISD::BT: return "X86ISD::BT";
19017 case X86ISD::CMP: return "X86ISD::CMP";
19018 case X86ISD::COMI: return "X86ISD::COMI";
19019 case X86ISD::UCOMI: return "X86ISD::UCOMI";
19020 case X86ISD::CMPM: return "X86ISD::CMPM";
19021 case X86ISD::CMPMU: return "X86ISD::CMPMU";
19022 case X86ISD::CMPM_RND: return "X86ISD::CMPM_RND";
19023 case X86ISD::SETCC: return "X86ISD::SETCC";
19024 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
19025 case X86ISD::FSETCC: return "X86ISD::FSETCC";
19026 case X86ISD::FGETSIGNx86: return "X86ISD::FGETSIGNx86";
19027 case X86ISD::CMOV: return "X86ISD::CMOV";
19028 case X86ISD::BRCOND: return "X86ISD::BRCOND";
19029 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
19030 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
19031 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
19032 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
19033 case X86ISD::Wrapper: return "X86ISD::Wrapper";
19034 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
19035 case X86ISD::MOVDQ2Q: return "X86ISD::MOVDQ2Q";
19036 case X86ISD::MMX_MOVD2W: return "X86ISD::MMX_MOVD2W";
19037 case X86ISD::MMX_MOVW2D: return "X86ISD::MMX_MOVW2D";
19038 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
19039 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
19040 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
19041 case X86ISD::PINSRB: return "X86ISD::PINSRB";
19042 case X86ISD::PINSRW: return "X86ISD::PINSRW";
19043 case X86ISD::MMX_PINSRW: return "X86ISD::MMX_PINSRW";
19044 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
19045 case X86ISD::ANDNP: return "X86ISD::ANDNP";
19046 case X86ISD::PSIGN: return "X86ISD::PSIGN";
19047 case X86ISD::BLENDI: return "X86ISD::BLENDI";
19048 case X86ISD::SHRUNKBLEND: return "X86ISD::SHRUNKBLEND";
19049 case X86ISD::ADDUS: return "X86ISD::ADDUS";
19050 case X86ISD::SUBUS: return "X86ISD::SUBUS";
19051 case X86ISD::HADD: return "X86ISD::HADD";
19052 case X86ISD::HSUB: return "X86ISD::HSUB";
19053 case X86ISD::FHADD: return "X86ISD::FHADD";
19054 case X86ISD::FHSUB: return "X86ISD::FHSUB";
19055 case X86ISD::ABS: return "X86ISD::ABS";
19056 case X86ISD::FMAX: return "X86ISD::FMAX";
19057 case X86ISD::FMAX_RND: return "X86ISD::FMAX_RND";
19058 case X86ISD::FMIN: return "X86ISD::FMIN";
19059 case X86ISD::FMIN_RND: return "X86ISD::FMIN_RND";
19060 case X86ISD::FMAXC: return "X86ISD::FMAXC";
19061 case X86ISD::FMINC: return "X86ISD::FMINC";
19062 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
19063 case X86ISD::FRCP: return "X86ISD::FRCP";
19064 case X86ISD::EXTRQI: return "X86ISD::EXTRQI";
19065 case X86ISD::INSERTQI: return "X86ISD::INSERTQI";
19066 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
19067 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
19068 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
19069 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
19070 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
19071 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
19072 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
19073 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
19074 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
19075 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
19076 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
19077 case X86ISD::LCMPXCHG16_DAG: return "X86ISD::LCMPXCHG16_DAG";
19078 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
19079 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
19080 case X86ISD::VZEXT: return "X86ISD::VZEXT";
19081 case X86ISD::VSEXT: return "X86ISD::VSEXT";
19082 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
19083 case X86ISD::VTRUNCS: return "X86ISD::VTRUNCS";
19084 case X86ISD::VTRUNCUS: return "X86ISD::VTRUNCUS";
19085 case X86ISD::VINSERT: return "X86ISD::VINSERT";
19086 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
19087 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
19088 case X86ISD::CVTDQ2PD: return "X86ISD::CVTDQ2PD";
19089 case X86ISD::CVTUDQ2PD: return "X86ISD::CVTUDQ2PD";
19090 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
19091 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
19092 case X86ISD::VSHL: return "X86ISD::VSHL";
19093 case X86ISD::VSRL: return "X86ISD::VSRL";
19094 case X86ISD::VSRA: return "X86ISD::VSRA";
19095 case X86ISD::VSHLI: return "X86ISD::VSHLI";
19096 case X86ISD::VSRLI: return "X86ISD::VSRLI";
19097 case X86ISD::VSRAI: return "X86ISD::VSRAI";
19098 case X86ISD::CMPP: return "X86ISD::CMPP";
19099 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
19100 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
19101 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
19102 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
19103 case X86ISD::ADD: return "X86ISD::ADD";
19104 case X86ISD::SUB: return "X86ISD::SUB";
19105 case X86ISD::ADC: return "X86ISD::ADC";
19106 case X86ISD::SBB: return "X86ISD::SBB";
19107 case X86ISD::SMUL: return "X86ISD::SMUL";
19108 case X86ISD::UMUL: return "X86ISD::UMUL";
19109 case X86ISD::SMUL8: return "X86ISD::SMUL8";
19110 case X86ISD::UMUL8: return "X86ISD::UMUL8";
19111 case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
19112 case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
19113 case X86ISD::INC: return "X86ISD::INC";
19114 case X86ISD::DEC: return "X86ISD::DEC";
19115 case X86ISD::OR: return "X86ISD::OR";
19116 case X86ISD::XOR: return "X86ISD::XOR";
19117 case X86ISD::AND: return "X86ISD::AND";
19118 case X86ISD::BEXTR: return "X86ISD::BEXTR";
19119 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
19120 case X86ISD::PTEST: return "X86ISD::PTEST";
19121 case X86ISD::TESTP: return "X86ISD::TESTP";
19122 case X86ISD::TESTM: return "X86ISD::TESTM";
19123 case X86ISD::TESTNM: return "X86ISD::TESTNM";
19124 case X86ISD::KORTEST: return "X86ISD::KORTEST";
19125 case X86ISD::PACKSS: return "X86ISD::PACKSS";
19126 case X86ISD::PACKUS: return "X86ISD::PACKUS";
19127 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
19128 case X86ISD::VALIGN: return "X86ISD::VALIGN";
19129 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
19130 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
19131 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
19132 case X86ISD::SHUFP: return "X86ISD::SHUFP";
19133 case X86ISD::SHUF128: return "X86ISD::SHUF128";
19134 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
19135 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
19136 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
19137 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
19138 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
19139 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
19140 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
19141 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
19142 case X86ISD::MOVSD: return "X86ISD::MOVSD";
19143 case X86ISD::MOVSS: return "X86ISD::MOVSS";
19144 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
19145 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
19146 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
19147 case X86ISD::SUBV_BROADCAST: return "X86ISD::SUBV_BROADCAST";
19148 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
19149 case X86ISD::VPERMILPV: return "X86ISD::VPERMILPV";
19150 case X86ISD::VPERMILPI: return "X86ISD::VPERMILPI";
19151 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
19152 case X86ISD::VPERMV: return "X86ISD::VPERMV";
19153 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
19154 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
19155 case X86ISD::VPERMI: return "X86ISD::VPERMI";
19156 case X86ISD::VFIXUPIMM: return "X86ISD::VFIXUPIMM";
19157 case X86ISD::VRANGE: return "X86ISD::VRANGE";
19158 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
19159 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
19160 case X86ISD::PSADBW: return "X86ISD::PSADBW";
19161 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
19162 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
19163 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
19164 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
19165 case X86ISD::MFENCE: return "X86ISD::MFENCE";
19166 case X86ISD::SFENCE: return "X86ISD::SFENCE";
19167 case X86ISD::LFENCE: return "X86ISD::LFENCE";
19168 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
19169 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
19170 case X86ISD::SAHF: return "X86ISD::SAHF";
19171 case X86ISD::RDRAND: return "X86ISD::RDRAND";
19172 case X86ISD::RDSEED: return "X86ISD::RDSEED";
19173 case X86ISD::VPMADDUBSW: return "X86ISD::VPMADDUBSW";
19174 case X86ISD::VPMADDWD: return "X86ISD::VPMADDWD";
19175 case X86ISD::FMADD: return "X86ISD::FMADD";
19176 case X86ISD::FMSUB: return "X86ISD::FMSUB";
19177 case X86ISD::FNMADD: return "X86ISD::FNMADD";
19178 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
19179 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
19180 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
19181 case X86ISD::FMADD_RND: return "X86ISD::FMADD_RND";
19182 case X86ISD::FNMADD_RND: return "X86ISD::FNMADD_RND";
19183 case X86ISD::FMSUB_RND: return "X86ISD::FMSUB_RND";
19184 case X86ISD::FNMSUB_RND: return "X86ISD::FNMSUB_RND";
19185 case X86ISD::FMADDSUB_RND: return "X86ISD::FMADDSUB_RND";
19186 case X86ISD::FMSUBADD_RND: return "X86ISD::FMSUBADD_RND";
19187 case X86ISD::VRNDSCALE: return "X86ISD::VRNDSCALE";
19188 case X86ISD::VREDUCE: return "X86ISD::VREDUCE";
19189 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
19190 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
19191 case X86ISD::XTEST: return "X86ISD::XTEST";
19192 case X86ISD::COMPRESS: return "X86ISD::COMPRESS";
19193 case X86ISD::EXPAND: return "X86ISD::EXPAND";
19194 case X86ISD::SELECT: return "X86ISD::SELECT";
19195 case X86ISD::ADDSUB: return "X86ISD::ADDSUB";
19196 case X86ISD::RCP28: return "X86ISD::RCP28";
19197 case X86ISD::EXP2: return "X86ISD::EXP2";
19198 case X86ISD::RSQRT28: return "X86ISD::RSQRT28";
19199 case X86ISD::FADD_RND: return "X86ISD::FADD_RND";
19200 case X86ISD::FSUB_RND: return "X86ISD::FSUB_RND";
19201 case X86ISD::FMUL_RND: return "X86ISD::FMUL_RND";
19202 case X86ISD::FDIV_RND: return "X86ISD::FDIV_RND";
19203 case X86ISD::FSQRT_RND: return "X86ISD::FSQRT_RND";
19204 case X86ISD::FGETEXP_RND: return "X86ISD::FGETEXP_RND";
19205 case X86ISD::SCALEF: return "X86ISD::SCALEF";
19206 case X86ISD::ADDS: return "X86ISD::ADDS";
19207 case X86ISD::SUBS: return "X86ISD::SUBS";
19208 case X86ISD::AVG: return "X86ISD::AVG";
19209 case X86ISD::MULHRS: return "X86ISD::MULHRS";
19210 case X86ISD::SINT_TO_FP_RND: return "X86ISD::SINT_TO_FP_RND";
19211 case X86ISD::UINT_TO_FP_RND: return "X86ISD::UINT_TO_FP_RND";
19212 case X86ISD::FP_TO_SINT_RND: return "X86ISD::FP_TO_SINT_RND";
19213 case X86ISD::FP_TO_UINT_RND: return "X86ISD::FP_TO_UINT_RND";
19218 // isLegalAddressingMode - Return true if the addressing mode represented
19219 // by AM is legal for this target, for a load/store of the specified type.
19220 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
19221 const AddrMode &AM, Type *Ty,
19222 unsigned AS) const {
19223 // X86 supports extremely general addressing modes.
19224 CodeModel::Model M = getTargetMachine().getCodeModel();
19225 Reloc::Model R = getTargetMachine().getRelocationModel();
19227 // X86 allows a sign-extended 32-bit immediate field as a displacement.
19228 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
19233 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
19235 // If a reference to this global requires an extra load, we can't fold it.
19236 if (isGlobalStubReference(GVFlags))
19239 // If BaseGV requires a register for the PIC base, we cannot also have a
19240 // BaseReg specified.
19241 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
19244 // If lower 4G is not available, then we must use rip-relative addressing.
19245 if ((M != CodeModel::Small || R != Reloc::Static) &&
19246 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
19250 switch (AM.Scale) {
19256 // These scales always work.
19261 // These scales are formed with basereg+scalereg. Only accept if there is
19266 default: // Other stuff never works.
19273 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
19274 unsigned Bits = Ty->getScalarSizeInBits();
19276 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
19277 // particularly cheaper than those without.
19281 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
19282 // variable shifts just as cheap as scalar ones.
19283 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
19286 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
19287 // fully general vector.
19291 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
19292 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19294 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
19295 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
19296 return NumBits1 > NumBits2;
19299 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
19300 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19303 if (!isTypeLegal(EVT::getEVT(Ty1)))
19306 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
19308 // Assuming the caller doesn't have a zeroext or signext return parameter,
19309 // truncation all the way down to i1 is valid.
19313 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
19314 return isInt<32>(Imm);
19317 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
19318 // Can also use sub to handle negated immediates.
19319 return isInt<32>(Imm);
19322 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
19323 if (!VT1.isInteger() || !VT2.isInteger())
19325 unsigned NumBits1 = VT1.getSizeInBits();
19326 unsigned NumBits2 = VT2.getSizeInBits();
19327 return NumBits1 > NumBits2;
19330 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
19331 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19332 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
19335 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
19336 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19337 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
19340 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
19341 EVT VT1 = Val.getValueType();
19342 if (isZExtFree(VT1, VT2))
19345 if (Val.getOpcode() != ISD::LOAD)
19348 if (!VT1.isSimple() || !VT1.isInteger() ||
19349 !VT2.isSimple() || !VT2.isInteger())
19352 switch (VT1.getSimpleVT().SimpleTy) {
19357 // X86 has 8, 16, and 32-bit zero-extending loads.
19364 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
19367 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
19368 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()))
19371 VT = VT.getScalarType();
19373 if (!VT.isSimple())
19376 switch (VT.getSimpleVT().SimpleTy) {
19387 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
19388 // i16 instructions are longer (0x66 prefix) and potentially slower.
19389 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
19392 /// isShuffleMaskLegal - Targets can use this to indicate that they only
19393 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
19394 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
19395 /// are assumed to be legal.
19397 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
19399 if (!VT.isSimple())
19402 // Not for i1 vectors
19403 if (VT.getScalarType() == MVT::i1)
19406 // Very little shuffling can be done for 64-bit vectors right now.
19407 if (VT.getSizeInBits() == 64)
19410 // We only care that the types being shuffled are legal. The lowering can
19411 // handle any possible shuffle mask that results.
19412 return isTypeLegal(VT.getSimpleVT());
19416 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
19418 // Just delegate to the generic legality, clear masks aren't special.
19419 return isShuffleMaskLegal(Mask, VT);
19422 //===----------------------------------------------------------------------===//
19423 // X86 Scheduler Hooks
19424 //===----------------------------------------------------------------------===//
19426 /// Utility function to emit xbegin specifying the start of an RTM region.
19427 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
19428 const TargetInstrInfo *TII) {
19429 DebugLoc DL = MI->getDebugLoc();
19431 const BasicBlock *BB = MBB->getBasicBlock();
19432 MachineFunction::iterator I = MBB;
19435 // For the v = xbegin(), we generate
19446 MachineBasicBlock *thisMBB = MBB;
19447 MachineFunction *MF = MBB->getParent();
19448 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19449 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19450 MF->insert(I, mainMBB);
19451 MF->insert(I, sinkMBB);
19453 // Transfer the remainder of BB and its successor edges to sinkMBB.
19454 sinkMBB->splice(sinkMBB->begin(), MBB,
19455 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19456 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19460 // # fallthrough to mainMBB
19461 // # abortion to sinkMBB
19462 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
19463 thisMBB->addSuccessor(mainMBB);
19464 thisMBB->addSuccessor(sinkMBB);
19468 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
19469 mainMBB->addSuccessor(sinkMBB);
19472 // EAX is live into the sinkMBB
19473 sinkMBB->addLiveIn(X86::EAX);
19474 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19475 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19478 MI->eraseFromParent();
19482 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
19483 // or XMM0_V32I8 in AVX all of this code can be replaced with that
19484 // in the .td file.
19485 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
19486 const TargetInstrInfo *TII) {
19488 switch (MI->getOpcode()) {
19489 default: llvm_unreachable("illegal opcode!");
19490 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
19491 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
19492 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
19493 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
19494 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
19495 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
19496 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
19497 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
19500 DebugLoc dl = MI->getDebugLoc();
19501 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19503 unsigned NumArgs = MI->getNumOperands();
19504 for (unsigned i = 1; i < NumArgs; ++i) {
19505 MachineOperand &Op = MI->getOperand(i);
19506 if (!(Op.isReg() && Op.isImplicit()))
19507 MIB.addOperand(Op);
19509 if (MI->hasOneMemOperand())
19510 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19512 BuildMI(*BB, MI, dl,
19513 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19514 .addReg(X86::XMM0);
19516 MI->eraseFromParent();
19520 // FIXME: Custom handling because TableGen doesn't support multiple implicit
19521 // defs in an instruction pattern
19522 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
19523 const TargetInstrInfo *TII) {
19525 switch (MI->getOpcode()) {
19526 default: llvm_unreachable("illegal opcode!");
19527 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
19528 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
19529 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
19530 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
19531 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
19532 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
19533 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
19534 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
19537 DebugLoc dl = MI->getDebugLoc();
19538 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19540 unsigned NumArgs = MI->getNumOperands(); // remove the results
19541 for (unsigned i = 1; i < NumArgs; ++i) {
19542 MachineOperand &Op = MI->getOperand(i);
19543 if (!(Op.isReg() && Op.isImplicit()))
19544 MIB.addOperand(Op);
19546 if (MI->hasOneMemOperand())
19547 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19549 BuildMI(*BB, MI, dl,
19550 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19553 MI->eraseFromParent();
19557 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
19558 const X86Subtarget *Subtarget) {
19559 DebugLoc dl = MI->getDebugLoc();
19560 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19561 // Address into RAX/EAX, other two args into ECX, EDX.
19562 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
19563 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
19564 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
19565 for (int i = 0; i < X86::AddrNumOperands; ++i)
19566 MIB.addOperand(MI->getOperand(i));
19568 unsigned ValOps = X86::AddrNumOperands;
19569 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
19570 .addReg(MI->getOperand(ValOps).getReg());
19571 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
19572 .addReg(MI->getOperand(ValOps+1).getReg());
19574 // The instruction doesn't actually take any operands though.
19575 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
19577 MI->eraseFromParent(); // The pseudo is gone now.
19581 MachineBasicBlock *
19582 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
19583 MachineBasicBlock *MBB) const {
19584 // Emit va_arg instruction on X86-64.
19586 // Operands to this pseudo-instruction:
19587 // 0 ) Output : destination address (reg)
19588 // 1-5) Input : va_list address (addr, i64mem)
19589 // 6 ) ArgSize : Size (in bytes) of vararg type
19590 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
19591 // 8 ) Align : Alignment of type
19592 // 9 ) EFLAGS (implicit-def)
19594 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
19595 static_assert(X86::AddrNumOperands == 5,
19596 "VAARG_64 assumes 5 address operands");
19598 unsigned DestReg = MI->getOperand(0).getReg();
19599 MachineOperand &Base = MI->getOperand(1);
19600 MachineOperand &Scale = MI->getOperand(2);
19601 MachineOperand &Index = MI->getOperand(3);
19602 MachineOperand &Disp = MI->getOperand(4);
19603 MachineOperand &Segment = MI->getOperand(5);
19604 unsigned ArgSize = MI->getOperand(6).getImm();
19605 unsigned ArgMode = MI->getOperand(7).getImm();
19606 unsigned Align = MI->getOperand(8).getImm();
19608 // Memory Reference
19609 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
19610 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19611 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19613 // Machine Information
19614 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19615 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
19616 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
19617 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
19618 DebugLoc DL = MI->getDebugLoc();
19620 // struct va_list {
19623 // i64 overflow_area (address)
19624 // i64 reg_save_area (address)
19626 // sizeof(va_list) = 24
19627 // alignment(va_list) = 8
19629 unsigned TotalNumIntRegs = 6;
19630 unsigned TotalNumXMMRegs = 8;
19631 bool UseGPOffset = (ArgMode == 1);
19632 bool UseFPOffset = (ArgMode == 2);
19633 unsigned MaxOffset = TotalNumIntRegs * 8 +
19634 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
19636 /* Align ArgSize to a multiple of 8 */
19637 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
19638 bool NeedsAlign = (Align > 8);
19640 MachineBasicBlock *thisMBB = MBB;
19641 MachineBasicBlock *overflowMBB;
19642 MachineBasicBlock *offsetMBB;
19643 MachineBasicBlock *endMBB;
19645 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
19646 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
19647 unsigned OffsetReg = 0;
19649 if (!UseGPOffset && !UseFPOffset) {
19650 // If we only pull from the overflow region, we don't create a branch.
19651 // We don't need to alter control flow.
19652 OffsetDestReg = 0; // unused
19653 OverflowDestReg = DestReg;
19655 offsetMBB = nullptr;
19656 overflowMBB = thisMBB;
19659 // First emit code to check if gp_offset (or fp_offset) is below the bound.
19660 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
19661 // If not, pull from overflow_area. (branch to overflowMBB)
19666 // offsetMBB overflowMBB
19671 // Registers for the PHI in endMBB
19672 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
19673 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
19675 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19676 MachineFunction *MF = MBB->getParent();
19677 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19678 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19679 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19681 MachineFunction::iterator MBBIter = MBB;
19684 // Insert the new basic blocks
19685 MF->insert(MBBIter, offsetMBB);
19686 MF->insert(MBBIter, overflowMBB);
19687 MF->insert(MBBIter, endMBB);
19689 // Transfer the remainder of MBB and its successor edges to endMBB.
19690 endMBB->splice(endMBB->begin(), thisMBB,
19691 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
19692 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
19694 // Make offsetMBB and overflowMBB successors of thisMBB
19695 thisMBB->addSuccessor(offsetMBB);
19696 thisMBB->addSuccessor(overflowMBB);
19698 // endMBB is a successor of both offsetMBB and overflowMBB
19699 offsetMBB->addSuccessor(endMBB);
19700 overflowMBB->addSuccessor(endMBB);
19702 // Load the offset value into a register
19703 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19704 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
19708 .addDisp(Disp, UseFPOffset ? 4 : 0)
19709 .addOperand(Segment)
19710 .setMemRefs(MMOBegin, MMOEnd);
19712 // Check if there is enough room left to pull this argument.
19713 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
19715 .addImm(MaxOffset + 8 - ArgSizeA8);
19717 // Branch to "overflowMBB" if offset >= max
19718 // Fall through to "offsetMBB" otherwise
19719 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
19720 .addMBB(overflowMBB);
19723 // In offsetMBB, emit code to use the reg_save_area.
19725 assert(OffsetReg != 0);
19727 // Read the reg_save_area address.
19728 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
19729 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
19734 .addOperand(Segment)
19735 .setMemRefs(MMOBegin, MMOEnd);
19737 // Zero-extend the offset
19738 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
19739 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
19742 .addImm(X86::sub_32bit);
19744 // Add the offset to the reg_save_area to get the final address.
19745 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
19746 .addReg(OffsetReg64)
19747 .addReg(RegSaveReg);
19749 // Compute the offset for the next argument
19750 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19751 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
19753 .addImm(UseFPOffset ? 16 : 8);
19755 // Store it back into the va_list.
19756 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
19760 .addDisp(Disp, UseFPOffset ? 4 : 0)
19761 .addOperand(Segment)
19762 .addReg(NextOffsetReg)
19763 .setMemRefs(MMOBegin, MMOEnd);
19766 BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
19771 // Emit code to use overflow area
19774 // Load the overflow_area address into a register.
19775 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
19776 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
19781 .addOperand(Segment)
19782 .setMemRefs(MMOBegin, MMOEnd);
19784 // If we need to align it, do so. Otherwise, just copy the address
19785 // to OverflowDestReg.
19787 // Align the overflow address
19788 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
19789 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
19791 // aligned_addr = (addr + (align-1)) & ~(align-1)
19792 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
19793 .addReg(OverflowAddrReg)
19796 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
19798 .addImm(~(uint64_t)(Align-1));
19800 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
19801 .addReg(OverflowAddrReg);
19804 // Compute the next overflow address after this argument.
19805 // (the overflow address should be kept 8-byte aligned)
19806 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
19807 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
19808 .addReg(OverflowDestReg)
19809 .addImm(ArgSizeA8);
19811 // Store the new overflow address.
19812 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
19817 .addOperand(Segment)
19818 .addReg(NextAddrReg)
19819 .setMemRefs(MMOBegin, MMOEnd);
19821 // If we branched, emit the PHI to the front of endMBB.
19823 BuildMI(*endMBB, endMBB->begin(), DL,
19824 TII->get(X86::PHI), DestReg)
19825 .addReg(OffsetDestReg).addMBB(offsetMBB)
19826 .addReg(OverflowDestReg).addMBB(overflowMBB);
19829 // Erase the pseudo instruction
19830 MI->eraseFromParent();
19835 MachineBasicBlock *
19836 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
19838 MachineBasicBlock *MBB) const {
19839 // Emit code to save XMM registers to the stack. The ABI says that the
19840 // number of registers to save is given in %al, so it's theoretically
19841 // possible to do an indirect jump trick to avoid saving all of them,
19842 // however this code takes a simpler approach and just executes all
19843 // of the stores if %al is non-zero. It's less code, and it's probably
19844 // easier on the hardware branch predictor, and stores aren't all that
19845 // expensive anyway.
19847 // Create the new basic blocks. One block contains all the XMM stores,
19848 // and one block is the final destination regardless of whether any
19849 // stores were performed.
19850 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19851 MachineFunction *F = MBB->getParent();
19852 MachineFunction::iterator MBBIter = MBB;
19854 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
19855 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
19856 F->insert(MBBIter, XMMSaveMBB);
19857 F->insert(MBBIter, EndMBB);
19859 // Transfer the remainder of MBB and its successor edges to EndMBB.
19860 EndMBB->splice(EndMBB->begin(), MBB,
19861 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19862 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
19864 // The original block will now fall through to the XMM save block.
19865 MBB->addSuccessor(XMMSaveMBB);
19866 // The XMMSaveMBB will fall through to the end block.
19867 XMMSaveMBB->addSuccessor(EndMBB);
19869 // Now add the instructions.
19870 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19871 DebugLoc DL = MI->getDebugLoc();
19873 unsigned CountReg = MI->getOperand(0).getReg();
19874 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
19875 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
19877 if (!Subtarget->isTargetWin64()) {
19878 // If %al is 0, branch around the XMM save block.
19879 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
19880 BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
19881 MBB->addSuccessor(EndMBB);
19884 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
19885 // that was just emitted, but clearly shouldn't be "saved".
19886 assert((MI->getNumOperands() <= 3 ||
19887 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
19888 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
19889 && "Expected last argument to be EFLAGS");
19890 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
19891 // In the XMM save block, save all the XMM argument registers.
19892 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
19893 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
19894 MachineMemOperand *MMO =
19895 F->getMachineMemOperand(
19896 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
19897 MachineMemOperand::MOStore,
19898 /*Size=*/16, /*Align=*/16);
19899 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
19900 .addFrameIndex(RegSaveFrameIndex)
19901 .addImm(/*Scale=*/1)
19902 .addReg(/*IndexReg=*/0)
19903 .addImm(/*Disp=*/Offset)
19904 .addReg(/*Segment=*/0)
19905 .addReg(MI->getOperand(i).getReg())
19906 .addMemOperand(MMO);
19909 MI->eraseFromParent(); // The pseudo instruction is gone now.
19914 // The EFLAGS operand of SelectItr might be missing a kill marker
19915 // because there were multiple uses of EFLAGS, and ISel didn't know
19916 // which to mark. Figure out whether SelectItr should have had a
19917 // kill marker, and set it if it should. Returns the correct kill
19919 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
19920 MachineBasicBlock* BB,
19921 const TargetRegisterInfo* TRI) {
19922 // Scan forward through BB for a use/def of EFLAGS.
19923 MachineBasicBlock::iterator miI(std::next(SelectItr));
19924 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
19925 const MachineInstr& mi = *miI;
19926 if (mi.readsRegister(X86::EFLAGS))
19928 if (mi.definesRegister(X86::EFLAGS))
19929 break; // Should have kill-flag - update below.
19932 // If we hit the end of the block, check whether EFLAGS is live into a
19934 if (miI == BB->end()) {
19935 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
19936 sEnd = BB->succ_end();
19937 sItr != sEnd; ++sItr) {
19938 MachineBasicBlock* succ = *sItr;
19939 if (succ->isLiveIn(X86::EFLAGS))
19944 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
19945 // out. SelectMI should have a kill flag on EFLAGS.
19946 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
19950 // Return true if it is OK for this CMOV pseudo-opcode to be cascaded
19951 // together with other CMOV pseudo-opcodes into a single basic-block with
19952 // conditional jump around it.
19953 static bool isCMOVPseudo(MachineInstr *MI) {
19954 switch (MI->getOpcode()) {
19955 case X86::CMOV_FR32:
19956 case X86::CMOV_FR64:
19957 case X86::CMOV_GR8:
19958 case X86::CMOV_GR16:
19959 case X86::CMOV_GR32:
19960 case X86::CMOV_RFP32:
19961 case X86::CMOV_RFP64:
19962 case X86::CMOV_RFP80:
19963 case X86::CMOV_V2F64:
19964 case X86::CMOV_V2I64:
19965 case X86::CMOV_V4F32:
19966 case X86::CMOV_V4F64:
19967 case X86::CMOV_V4I64:
19968 case X86::CMOV_V16F32:
19969 case X86::CMOV_V8F32:
19970 case X86::CMOV_V8F64:
19971 case X86::CMOV_V8I64:
19972 case X86::CMOV_V8I1:
19973 case X86::CMOV_V16I1:
19974 case X86::CMOV_V32I1:
19975 case X86::CMOV_V64I1:
19983 MachineBasicBlock *
19984 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
19985 MachineBasicBlock *BB) const {
19986 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19987 DebugLoc DL = MI->getDebugLoc();
19989 // To "insert" a SELECT_CC instruction, we actually have to insert the
19990 // diamond control-flow pattern. The incoming instruction knows the
19991 // destination vreg to set, the condition code register to branch on, the
19992 // true/false values to select between, and a branch opcode to use.
19993 const BasicBlock *LLVM_BB = BB->getBasicBlock();
19994 MachineFunction::iterator It = BB;
20000 // cmpTY ccX, r1, r2
20002 // fallthrough --> copy0MBB
20003 MachineBasicBlock *thisMBB = BB;
20004 MachineFunction *F = BB->getParent();
20006 // This code lowers all pseudo-CMOV instructions. Generally it lowers these
20007 // as described above, by inserting a BB, and then making a PHI at the join
20008 // point to select the true and false operands of the CMOV in the PHI.
20010 // The code also handles two different cases of multiple CMOV opcodes
20014 // In this case, there are multiple CMOVs in a row, all which are based on
20015 // the same condition setting (or the exact opposite condition setting).
20016 // In this case we can lower all the CMOVs using a single inserted BB, and
20017 // then make a number of PHIs at the join point to model the CMOVs. The only
20018 // trickiness here, is that in a case like:
20020 // t2 = CMOV cond1 t1, f1
20021 // t3 = CMOV cond1 t2, f2
20023 // when rewriting this into PHIs, we have to perform some renaming on the
20024 // temps since you cannot have a PHI operand refer to a PHI result earlier
20025 // in the same block. The "simple" but wrong lowering would be:
20027 // t2 = PHI t1(BB1), f1(BB2)
20028 // t3 = PHI t2(BB1), f2(BB2)
20030 // but clearly t2 is not defined in BB1, so that is incorrect. The proper
20031 // renaming is to note that on the path through BB1, t2 is really just a
20032 // copy of t1, and do that renaming, properly generating:
20034 // t2 = PHI t1(BB1), f1(BB2)
20035 // t3 = PHI t1(BB1), f2(BB2)
20037 // Case 2, we lower cascaded CMOVs such as
20039 // (CMOV (CMOV F, T, cc1), T, cc2)
20041 // to two successives branches. For that, we look for another CMOV as the
20042 // following instruction.
20044 // Without this, we would add a PHI between the two jumps, which ends up
20045 // creating a few copies all around. For instance, for
20047 // (sitofp (zext (fcmp une)))
20049 // we would generate:
20051 // ucomiss %xmm1, %xmm0
20052 // movss <1.0f>, %xmm0
20053 // movaps %xmm0, %xmm1
20055 // xorps %xmm1, %xmm1
20058 // movaps %xmm1, %xmm0
20062 // because this custom-inserter would have generated:
20074 // A: X = ...; Y = ...
20076 // C: Z = PHI [X, A], [Y, B]
20078 // E: PHI [X, C], [Z, D]
20080 // If we lower both CMOVs in a single step, we can instead generate:
20092 // A: X = ...; Y = ...
20094 // E: PHI [X, A], [X, C], [Y, D]
20096 // Which, in our sitofp/fcmp example, gives us something like:
20098 // ucomiss %xmm1, %xmm0
20099 // movss <1.0f>, %xmm0
20102 // xorps %xmm0, %xmm0
20106 MachineInstr *CascadedCMOV = nullptr;
20107 MachineInstr *LastCMOV = MI;
20108 X86::CondCode CC = X86::CondCode(MI->getOperand(3).getImm());
20109 X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
20110 MachineBasicBlock::iterator NextMIIt =
20111 std::next(MachineBasicBlock::iterator(MI));
20113 // Check for case 1, where there are multiple CMOVs with the same condition
20114 // first. Of the two cases of multiple CMOV lowerings, case 1 reduces the
20115 // number of jumps the most.
20117 if (isCMOVPseudo(MI)) {
20118 // See if we have a string of CMOVS with the same condition.
20119 while (NextMIIt != BB->end() &&
20120 isCMOVPseudo(NextMIIt) &&
20121 (NextMIIt->getOperand(3).getImm() == CC ||
20122 NextMIIt->getOperand(3).getImm() == OppCC)) {
20123 LastCMOV = &*NextMIIt;
20128 // This checks for case 2, but only do this if we didn't already find
20129 // case 1, as indicated by LastCMOV == MI.
20130 if (LastCMOV == MI &&
20131 NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
20132 NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
20133 NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg()) {
20134 CascadedCMOV = &*NextMIIt;
20137 MachineBasicBlock *jcc1MBB = nullptr;
20139 // If we have a cascaded CMOV, we lower it to two successive branches to
20140 // the same block. EFLAGS is used by both, so mark it as live in the second.
20141 if (CascadedCMOV) {
20142 jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
20143 F->insert(It, jcc1MBB);
20144 jcc1MBB->addLiveIn(X86::EFLAGS);
20147 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
20148 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
20149 F->insert(It, copy0MBB);
20150 F->insert(It, sinkMBB);
20152 // If the EFLAGS register isn't dead in the terminator, then claim that it's
20153 // live into the sink and copy blocks.
20154 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
20156 MachineInstr *LastEFLAGSUser = CascadedCMOV ? CascadedCMOV : LastCMOV;
20157 if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
20158 !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
20159 copy0MBB->addLiveIn(X86::EFLAGS);
20160 sinkMBB->addLiveIn(X86::EFLAGS);
20163 // Transfer the remainder of BB and its successor edges to sinkMBB.
20164 sinkMBB->splice(sinkMBB->begin(), BB,
20165 std::next(MachineBasicBlock::iterator(LastCMOV)), BB->end());
20166 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
20168 // Add the true and fallthrough blocks as its successors.
20169 if (CascadedCMOV) {
20170 // The fallthrough block may be jcc1MBB, if we have a cascaded CMOV.
20171 BB->addSuccessor(jcc1MBB);
20173 // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
20174 // jump to the sinkMBB.
20175 jcc1MBB->addSuccessor(copy0MBB);
20176 jcc1MBB->addSuccessor(sinkMBB);
20178 BB->addSuccessor(copy0MBB);
20181 // The true block target of the first (or only) branch is always sinkMBB.
20182 BB->addSuccessor(sinkMBB);
20184 // Create the conditional branch instruction.
20185 unsigned Opc = X86::GetCondBranchFromCond(CC);
20186 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
20188 if (CascadedCMOV) {
20189 unsigned Opc2 = X86::GetCondBranchFromCond(
20190 (X86::CondCode)CascadedCMOV->getOperand(3).getImm());
20191 BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
20195 // %FalseValue = ...
20196 // # fallthrough to sinkMBB
20197 copy0MBB->addSuccessor(sinkMBB);
20200 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
20202 MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
20203 MachineBasicBlock::iterator MIItEnd =
20204 std::next(MachineBasicBlock::iterator(LastCMOV));
20205 MachineBasicBlock::iterator SinkInsertionPoint = sinkMBB->begin();
20206 DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
20207 MachineInstrBuilder MIB;
20209 // As we are creating the PHIs, we have to be careful if there is more than
20210 // one. Later CMOVs may reference the results of earlier CMOVs, but later
20211 // PHIs have to reference the individual true/false inputs from earlier PHIs.
20212 // That also means that PHI construction must work forward from earlier to
20213 // later, and that the code must maintain a mapping from earlier PHI's
20214 // destination registers, and the registers that went into the PHI.
20216 for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
20217 unsigned DestReg = MIIt->getOperand(0).getReg();
20218 unsigned Op1Reg = MIIt->getOperand(1).getReg();
20219 unsigned Op2Reg = MIIt->getOperand(2).getReg();
20221 // If this CMOV we are generating is the opposite condition from
20222 // the jump we generated, then we have to swap the operands for the
20223 // PHI that is going to be generated.
20224 if (MIIt->getOperand(3).getImm() == OppCC)
20225 std::swap(Op1Reg, Op2Reg);
20227 if (RegRewriteTable.find(Op1Reg) != RegRewriteTable.end())
20228 Op1Reg = RegRewriteTable[Op1Reg].first;
20230 if (RegRewriteTable.find(Op2Reg) != RegRewriteTable.end())
20231 Op2Reg = RegRewriteTable[Op2Reg].second;
20233 MIB = BuildMI(*sinkMBB, SinkInsertionPoint, DL,
20234 TII->get(X86::PHI), DestReg)
20235 .addReg(Op1Reg).addMBB(copy0MBB)
20236 .addReg(Op2Reg).addMBB(thisMBB);
20238 // Add this PHI to the rewrite table.
20239 RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
20242 // If we have a cascaded CMOV, the second Jcc provides the same incoming
20243 // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
20244 if (CascadedCMOV) {
20245 MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
20246 // Copy the PHI result to the register defined by the second CMOV.
20247 BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
20248 DL, TII->get(TargetOpcode::COPY),
20249 CascadedCMOV->getOperand(0).getReg())
20250 .addReg(MI->getOperand(0).getReg());
20251 CascadedCMOV->eraseFromParent();
20254 // Now remove the CMOV(s).
20255 for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; )
20256 (MIIt++)->eraseFromParent();
20261 MachineBasicBlock *
20262 X86TargetLowering::EmitLoweredAtomicFP(MachineInstr *MI,
20263 MachineBasicBlock *BB) const {
20264 // Combine the following atomic floating-point modification pattern:
20265 // a.store(reg OP a.load(acquire), release)
20266 // Transform them into:
20267 // OPss (%gpr), %xmm
20268 // movss %xmm, (%gpr)
20269 // Or sd equivalent for 64-bit operations.
20271 switch (MI->getOpcode()) {
20272 default: llvm_unreachable("unexpected instr type for EmitLoweredAtomicFP");
20273 case X86::RELEASE_FADD32mr: MOp = X86::MOVSSmr; FOp = X86::ADDSSrm; break;
20274 case X86::RELEASE_FADD64mr: MOp = X86::MOVSDmr; FOp = X86::ADDSDrm; break;
20276 const X86InstrInfo *TII = Subtarget->getInstrInfo();
20277 DebugLoc DL = MI->getDebugLoc();
20278 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
20279 unsigned MSrc = MI->getOperand(0).getReg();
20280 unsigned VSrc = MI->getOperand(5).getReg();
20281 MachineInstrBuilder MIM = BuildMI(*BB, MI, DL, TII->get(MOp))
20282 .addReg(/*Base=*/MSrc)
20283 .addImm(/*Scale=*/1)
20284 .addReg(/*Index=*/0)
20287 MachineInstr *MIO = BuildMI(*BB, (MachineInstr *)MIM, DL, TII->get(FOp),
20288 MRI.createVirtualRegister(MRI.getRegClass(VSrc)))
20290 .addReg(/*Base=*/MSrc)
20291 .addImm(/*Scale=*/1)
20292 .addReg(/*Index=*/0)
20293 .addImm(/*Disp=*/0)
20294 .addReg(/*Segment=*/0);
20295 MIM.addReg(MIO->getOperand(0).getReg(), RegState::Kill);
20296 MI->eraseFromParent(); // The pseudo instruction is gone now.
20300 MachineBasicBlock *
20301 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
20302 MachineBasicBlock *BB) const {
20303 MachineFunction *MF = BB->getParent();
20304 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20305 DebugLoc DL = MI->getDebugLoc();
20306 const BasicBlock *LLVM_BB = BB->getBasicBlock();
20308 assert(MF->shouldSplitStack());
20310 const bool Is64Bit = Subtarget->is64Bit();
20311 const bool IsLP64 = Subtarget->isTarget64BitLP64();
20313 const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
20314 const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
20317 // ... [Till the alloca]
20318 // If stacklet is not large enough, jump to mallocMBB
20321 // Allocate by subtracting from RSP
20322 // Jump to continueMBB
20325 // Allocate by call to runtime
20329 // [rest of original BB]
20332 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20333 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20334 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20336 MachineRegisterInfo &MRI = MF->getRegInfo();
20337 const TargetRegisterClass *AddrRegClass =
20338 getRegClassFor(getPointerTy(MF->getDataLayout()));
20340 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20341 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20342 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
20343 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
20344 sizeVReg = MI->getOperand(1).getReg(),
20345 physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
20347 MachineFunction::iterator MBBIter = BB;
20350 MF->insert(MBBIter, bumpMBB);
20351 MF->insert(MBBIter, mallocMBB);
20352 MF->insert(MBBIter, continueMBB);
20354 continueMBB->splice(continueMBB->begin(), BB,
20355 std::next(MachineBasicBlock::iterator(MI)), BB->end());
20356 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
20358 // Add code to the main basic block to check if the stack limit has been hit,
20359 // and if so, jump to mallocMBB otherwise to bumpMBB.
20360 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
20361 BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
20362 .addReg(tmpSPVReg).addReg(sizeVReg);
20363 BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
20364 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
20365 .addReg(SPLimitVReg);
20366 BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
20368 // bumpMBB simply decreases the stack pointer, since we know the current
20369 // stacklet has enough space.
20370 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
20371 .addReg(SPLimitVReg);
20372 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
20373 .addReg(SPLimitVReg);
20374 BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20376 // Calls into a routine in libgcc to allocate more space from the heap.
20377 const uint32_t *RegMask =
20378 Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
20380 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
20382 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20383 .addExternalSymbol("__morestack_allocate_stack_space")
20384 .addRegMask(RegMask)
20385 .addReg(X86::RDI, RegState::Implicit)
20386 .addReg(X86::RAX, RegState::ImplicitDefine);
20387 } else if (Is64Bit) {
20388 BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
20390 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20391 .addExternalSymbol("__morestack_allocate_stack_space")
20392 .addRegMask(RegMask)
20393 .addReg(X86::EDI, RegState::Implicit)
20394 .addReg(X86::EAX, RegState::ImplicitDefine);
20396 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
20398 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
20399 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
20400 .addExternalSymbol("__morestack_allocate_stack_space")
20401 .addRegMask(RegMask)
20402 .addReg(X86::EAX, RegState::ImplicitDefine);
20406 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
20409 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
20410 .addReg(IsLP64 ? X86::RAX : X86::EAX);
20411 BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20413 // Set up the CFG correctly.
20414 BB->addSuccessor(bumpMBB);
20415 BB->addSuccessor(mallocMBB);
20416 mallocMBB->addSuccessor(continueMBB);
20417 bumpMBB->addSuccessor(continueMBB);
20419 // Take care of the PHI nodes.
20420 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
20421 MI->getOperand(0).getReg())
20422 .addReg(mallocPtrVReg).addMBB(mallocMBB)
20423 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
20425 // Delete the original pseudo instruction.
20426 MI->eraseFromParent();
20429 return continueMBB;
20432 MachineBasicBlock *
20433 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
20434 MachineBasicBlock *BB) const {
20435 DebugLoc DL = MI->getDebugLoc();
20437 assert(!Subtarget->isTargetMachO());
20439 Subtarget->getFrameLowering()->emitStackProbeCall(*BB->getParent(), *BB, MI,
20442 MI->eraseFromParent(); // The pseudo instruction is gone now.
20446 MachineBasicBlock *
20447 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
20448 MachineBasicBlock *BB) const {
20449 // This is pretty easy. We're taking the value that we received from
20450 // our load from the relocation, sticking it in either RDI (x86-64)
20451 // or EAX and doing an indirect call. The return value will then
20452 // be in the normal return register.
20453 MachineFunction *F = BB->getParent();
20454 const X86InstrInfo *TII = Subtarget->getInstrInfo();
20455 DebugLoc DL = MI->getDebugLoc();
20457 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
20458 assert(MI->getOperand(3).isGlobal() && "This should be a global");
20460 // Get a register mask for the lowered call.
20461 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
20462 // proper register mask.
20463 const uint32_t *RegMask =
20464 Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
20465 if (Subtarget->is64Bit()) {
20466 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20467 TII->get(X86::MOV64rm), X86::RDI)
20469 .addImm(0).addReg(0)
20470 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20471 MI->getOperand(3).getTargetFlags())
20473 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
20474 addDirectMem(MIB, X86::RDI);
20475 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
20476 } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
20477 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20478 TII->get(X86::MOV32rm), X86::EAX)
20480 .addImm(0).addReg(0)
20481 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20482 MI->getOperand(3).getTargetFlags())
20484 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20485 addDirectMem(MIB, X86::EAX);
20486 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20488 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20489 TII->get(X86::MOV32rm), X86::EAX)
20490 .addReg(TII->getGlobalBaseReg(F))
20491 .addImm(0).addReg(0)
20492 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20493 MI->getOperand(3).getTargetFlags())
20495 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20496 addDirectMem(MIB, X86::EAX);
20497 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20500 MI->eraseFromParent(); // The pseudo instruction is gone now.
20504 MachineBasicBlock *
20505 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
20506 MachineBasicBlock *MBB) const {
20507 DebugLoc DL = MI->getDebugLoc();
20508 MachineFunction *MF = MBB->getParent();
20509 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20510 MachineRegisterInfo &MRI = MF->getRegInfo();
20512 const BasicBlock *BB = MBB->getBasicBlock();
20513 MachineFunction::iterator I = MBB;
20516 // Memory Reference
20517 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20518 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20521 unsigned MemOpndSlot = 0;
20523 unsigned CurOp = 0;
20525 DstReg = MI->getOperand(CurOp++).getReg();
20526 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
20527 assert(RC->hasType(MVT::i32) && "Invalid destination!");
20528 unsigned mainDstReg = MRI.createVirtualRegister(RC);
20529 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
20531 MemOpndSlot = CurOp;
20533 MVT PVT = getPointerTy(MF->getDataLayout());
20534 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20535 "Invalid Pointer Size!");
20537 // For v = setjmp(buf), we generate
20540 // buf[LabelOffset] = restoreMBB
20541 // SjLjSetup restoreMBB
20547 // v = phi(main, restore)
20550 // if base pointer being used, load it from frame
20553 MachineBasicBlock *thisMBB = MBB;
20554 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20555 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20556 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
20557 MF->insert(I, mainMBB);
20558 MF->insert(I, sinkMBB);
20559 MF->push_back(restoreMBB);
20561 MachineInstrBuilder MIB;
20563 // Transfer the remainder of BB and its successor edges to sinkMBB.
20564 sinkMBB->splice(sinkMBB->begin(), MBB,
20565 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20566 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20569 unsigned PtrStoreOpc = 0;
20570 unsigned LabelReg = 0;
20571 const int64_t LabelOffset = 1 * PVT.getStoreSize();
20572 Reloc::Model RM = MF->getTarget().getRelocationModel();
20573 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
20574 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
20576 // Prepare IP either in reg or imm.
20577 if (!UseImmLabel) {
20578 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
20579 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
20580 LabelReg = MRI.createVirtualRegister(PtrRC);
20581 if (Subtarget->is64Bit()) {
20582 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
20586 .addMBB(restoreMBB)
20589 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
20590 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
20591 .addReg(XII->getGlobalBaseReg(MF))
20594 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
20598 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
20600 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
20601 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20602 if (i == X86::AddrDisp)
20603 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
20605 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
20608 MIB.addReg(LabelReg);
20610 MIB.addMBB(restoreMBB);
20611 MIB.setMemRefs(MMOBegin, MMOEnd);
20613 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
20614 .addMBB(restoreMBB);
20616 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20617 MIB.addRegMask(RegInfo->getNoPreservedMask());
20618 thisMBB->addSuccessor(mainMBB);
20619 thisMBB->addSuccessor(restoreMBB);
20623 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
20624 mainMBB->addSuccessor(sinkMBB);
20627 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20628 TII->get(X86::PHI), DstReg)
20629 .addReg(mainDstReg).addMBB(mainMBB)
20630 .addReg(restoreDstReg).addMBB(restoreMBB);
20633 if (RegInfo->hasBasePointer(*MF)) {
20634 const bool Uses64BitFramePtr =
20635 Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
20636 X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
20637 X86FI->setRestoreBasePointer(MF);
20638 unsigned FramePtr = RegInfo->getFrameRegister(*MF);
20639 unsigned BasePtr = RegInfo->getBaseRegister();
20640 unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
20641 addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
20642 FramePtr, true, X86FI->getRestoreBasePointerOffset())
20643 .setMIFlag(MachineInstr::FrameSetup);
20645 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
20646 BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
20647 restoreMBB->addSuccessor(sinkMBB);
20649 MI->eraseFromParent();
20653 MachineBasicBlock *
20654 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
20655 MachineBasicBlock *MBB) const {
20656 DebugLoc DL = MI->getDebugLoc();
20657 MachineFunction *MF = MBB->getParent();
20658 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20659 MachineRegisterInfo &MRI = MF->getRegInfo();
20661 // Memory Reference
20662 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20663 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20665 MVT PVT = getPointerTy(MF->getDataLayout());
20666 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20667 "Invalid Pointer Size!");
20669 const TargetRegisterClass *RC =
20670 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
20671 unsigned Tmp = MRI.createVirtualRegister(RC);
20672 // Since FP is only updated here but NOT referenced, it's treated as GPR.
20673 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20674 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
20675 unsigned SP = RegInfo->getStackRegister();
20677 MachineInstrBuilder MIB;
20679 const int64_t LabelOffset = 1 * PVT.getStoreSize();
20680 const int64_t SPOffset = 2 * PVT.getStoreSize();
20682 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
20683 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
20686 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
20687 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
20688 MIB.addOperand(MI->getOperand(i));
20689 MIB.setMemRefs(MMOBegin, MMOEnd);
20691 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
20692 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20693 if (i == X86::AddrDisp)
20694 MIB.addDisp(MI->getOperand(i), LabelOffset);
20696 MIB.addOperand(MI->getOperand(i));
20698 MIB.setMemRefs(MMOBegin, MMOEnd);
20700 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
20701 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20702 if (i == X86::AddrDisp)
20703 MIB.addDisp(MI->getOperand(i), SPOffset);
20705 MIB.addOperand(MI->getOperand(i));
20707 MIB.setMemRefs(MMOBegin, MMOEnd);
20709 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
20711 MI->eraseFromParent();
20715 // Replace 213-type (isel default) FMA3 instructions with 231-type for
20716 // accumulator loops. Writing back to the accumulator allows the coalescer
20717 // to remove extra copies in the loop.
20718 // FIXME: Do this on AVX512. We don't support 231 variants yet (PR23937).
20719 MachineBasicBlock *
20720 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
20721 MachineBasicBlock *MBB) const {
20722 MachineOperand &AddendOp = MI->getOperand(3);
20724 // Bail out early if the addend isn't a register - we can't switch these.
20725 if (!AddendOp.isReg())
20728 MachineFunction &MF = *MBB->getParent();
20729 MachineRegisterInfo &MRI = MF.getRegInfo();
20731 // Check whether the addend is defined by a PHI:
20732 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
20733 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
20734 if (!AddendDef.isPHI())
20737 // Look for the following pattern:
20739 // %addend = phi [%entry, 0], [%loop, %result]
20741 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
20745 // %addend = phi [%entry, 0], [%loop, %result]
20747 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
20749 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
20750 assert(AddendDef.getOperand(i).isReg());
20751 MachineOperand PHISrcOp = AddendDef.getOperand(i);
20752 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
20753 if (&PHISrcInst == MI) {
20754 // Found a matching instruction.
20755 unsigned NewFMAOpc = 0;
20756 switch (MI->getOpcode()) {
20757 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
20758 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
20759 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
20760 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
20761 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
20762 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
20763 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
20764 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
20765 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
20766 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
20767 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
20768 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
20769 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
20770 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
20771 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
20772 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
20773 case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
20774 case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
20775 case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
20776 case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
20778 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
20779 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
20780 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
20781 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
20782 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
20783 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
20784 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
20785 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
20786 case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
20787 case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
20788 case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
20789 case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
20790 default: llvm_unreachable("Unrecognized FMA variant.");
20793 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
20794 MachineInstrBuilder MIB =
20795 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
20796 .addOperand(MI->getOperand(0))
20797 .addOperand(MI->getOperand(3))
20798 .addOperand(MI->getOperand(2))
20799 .addOperand(MI->getOperand(1));
20800 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
20801 MI->eraseFromParent();
20808 MachineBasicBlock *
20809 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
20810 MachineBasicBlock *BB) const {
20811 switch (MI->getOpcode()) {
20812 default: llvm_unreachable("Unexpected instr type to insert");
20813 case X86::TAILJMPd64:
20814 case X86::TAILJMPr64:
20815 case X86::TAILJMPm64:
20816 case X86::TAILJMPd64_REX:
20817 case X86::TAILJMPr64_REX:
20818 case X86::TAILJMPm64_REX:
20819 llvm_unreachable("TAILJMP64 would not be touched here.");
20820 case X86::TCRETURNdi64:
20821 case X86::TCRETURNri64:
20822 case X86::TCRETURNmi64:
20824 case X86::WIN_ALLOCA:
20825 return EmitLoweredWinAlloca(MI, BB);
20826 case X86::SEG_ALLOCA_32:
20827 case X86::SEG_ALLOCA_64:
20828 return EmitLoweredSegAlloca(MI, BB);
20829 case X86::TLSCall_32:
20830 case X86::TLSCall_64:
20831 return EmitLoweredTLSCall(MI, BB);
20832 case X86::CMOV_FR32:
20833 case X86::CMOV_FR64:
20834 case X86::CMOV_GR8:
20835 case X86::CMOV_GR16:
20836 case X86::CMOV_GR32:
20837 case X86::CMOV_RFP32:
20838 case X86::CMOV_RFP64:
20839 case X86::CMOV_RFP80:
20840 case X86::CMOV_V2F64:
20841 case X86::CMOV_V2I64:
20842 case X86::CMOV_V4F32:
20843 case X86::CMOV_V4F64:
20844 case X86::CMOV_V4I64:
20845 case X86::CMOV_V16F32:
20846 case X86::CMOV_V8F32:
20847 case X86::CMOV_V8F64:
20848 case X86::CMOV_V8I64:
20849 case X86::CMOV_V8I1:
20850 case X86::CMOV_V16I1:
20851 case X86::CMOV_V32I1:
20852 case X86::CMOV_V64I1:
20853 return EmitLoweredSelect(MI, BB);
20855 case X86::RELEASE_FADD32mr:
20856 case X86::RELEASE_FADD64mr:
20857 return EmitLoweredAtomicFP(MI, BB);
20859 case X86::FP32_TO_INT16_IN_MEM:
20860 case X86::FP32_TO_INT32_IN_MEM:
20861 case X86::FP32_TO_INT64_IN_MEM:
20862 case X86::FP64_TO_INT16_IN_MEM:
20863 case X86::FP64_TO_INT32_IN_MEM:
20864 case X86::FP64_TO_INT64_IN_MEM:
20865 case X86::FP80_TO_INT16_IN_MEM:
20866 case X86::FP80_TO_INT32_IN_MEM:
20867 case X86::FP80_TO_INT64_IN_MEM: {
20868 MachineFunction *F = BB->getParent();
20869 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20870 DebugLoc DL = MI->getDebugLoc();
20872 // Change the floating point control register to use "round towards zero"
20873 // mode when truncating to an integer value.
20874 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
20875 addFrameReference(BuildMI(*BB, MI, DL,
20876 TII->get(X86::FNSTCW16m)), CWFrameIdx);
20878 // Load the old value of the high byte of the control word...
20880 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
20881 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
20884 // Set the high part to be round to zero...
20885 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
20888 // Reload the modified control word now...
20889 addFrameReference(BuildMI(*BB, MI, DL,
20890 TII->get(X86::FLDCW16m)), CWFrameIdx);
20892 // Restore the memory image of control word to original value
20893 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
20896 // Get the X86 opcode to use.
20898 switch (MI->getOpcode()) {
20899 default: llvm_unreachable("illegal opcode!");
20900 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
20901 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
20902 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
20903 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
20904 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
20905 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
20906 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
20907 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
20908 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
20912 MachineOperand &Op = MI->getOperand(0);
20914 AM.BaseType = X86AddressMode::RegBase;
20915 AM.Base.Reg = Op.getReg();
20917 AM.BaseType = X86AddressMode::FrameIndexBase;
20918 AM.Base.FrameIndex = Op.getIndex();
20920 Op = MI->getOperand(1);
20922 AM.Scale = Op.getImm();
20923 Op = MI->getOperand(2);
20925 AM.IndexReg = Op.getImm();
20926 Op = MI->getOperand(3);
20927 if (Op.isGlobal()) {
20928 AM.GV = Op.getGlobal();
20930 AM.Disp = Op.getImm();
20932 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
20933 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
20935 // Reload the original control word now.
20936 addFrameReference(BuildMI(*BB, MI, DL,
20937 TII->get(X86::FLDCW16m)), CWFrameIdx);
20939 MI->eraseFromParent(); // The pseudo instruction is gone now.
20942 // String/text processing lowering.
20943 case X86::PCMPISTRM128REG:
20944 case X86::VPCMPISTRM128REG:
20945 case X86::PCMPISTRM128MEM:
20946 case X86::VPCMPISTRM128MEM:
20947 case X86::PCMPESTRM128REG:
20948 case X86::VPCMPESTRM128REG:
20949 case X86::PCMPESTRM128MEM:
20950 case X86::VPCMPESTRM128MEM:
20951 assert(Subtarget->hasSSE42() &&
20952 "Target must have SSE4.2 or AVX features enabled");
20953 return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
20955 // String/text processing lowering.
20956 case X86::PCMPISTRIREG:
20957 case X86::VPCMPISTRIREG:
20958 case X86::PCMPISTRIMEM:
20959 case X86::VPCMPISTRIMEM:
20960 case X86::PCMPESTRIREG:
20961 case X86::VPCMPESTRIREG:
20962 case X86::PCMPESTRIMEM:
20963 case X86::VPCMPESTRIMEM:
20964 assert(Subtarget->hasSSE42() &&
20965 "Target must have SSE4.2 or AVX features enabled");
20966 return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
20968 // Thread synchronization.
20970 return EmitMonitor(MI, BB, Subtarget);
20974 return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
20976 case X86::VASTART_SAVE_XMM_REGS:
20977 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
20979 case X86::VAARG_64:
20980 return EmitVAARG64WithCustomInserter(MI, BB);
20982 case X86::EH_SjLj_SetJmp32:
20983 case X86::EH_SjLj_SetJmp64:
20984 return emitEHSjLjSetJmp(MI, BB);
20986 case X86::EH_SjLj_LongJmp32:
20987 case X86::EH_SjLj_LongJmp64:
20988 return emitEHSjLjLongJmp(MI, BB);
20990 case TargetOpcode::STATEPOINT:
20991 // As an implementation detail, STATEPOINT shares the STACKMAP format at
20992 // this point in the process. We diverge later.
20993 return emitPatchPoint(MI, BB);
20995 case TargetOpcode::STACKMAP:
20996 case TargetOpcode::PATCHPOINT:
20997 return emitPatchPoint(MI, BB);
20999 case X86::VFMADDPDr213r:
21000 case X86::VFMADDPSr213r:
21001 case X86::VFMADDSDr213r:
21002 case X86::VFMADDSSr213r:
21003 case X86::VFMSUBPDr213r:
21004 case X86::VFMSUBPSr213r:
21005 case X86::VFMSUBSDr213r:
21006 case X86::VFMSUBSSr213r:
21007 case X86::VFNMADDPDr213r:
21008 case X86::VFNMADDPSr213r:
21009 case X86::VFNMADDSDr213r:
21010 case X86::VFNMADDSSr213r:
21011 case X86::VFNMSUBPDr213r:
21012 case X86::VFNMSUBPSr213r:
21013 case X86::VFNMSUBSDr213r:
21014 case X86::VFNMSUBSSr213r:
21015 case X86::VFMADDSUBPDr213r:
21016 case X86::VFMADDSUBPSr213r:
21017 case X86::VFMSUBADDPDr213r:
21018 case X86::VFMSUBADDPSr213r:
21019 case X86::VFMADDPDr213rY:
21020 case X86::VFMADDPSr213rY:
21021 case X86::VFMSUBPDr213rY:
21022 case X86::VFMSUBPSr213rY:
21023 case X86::VFNMADDPDr213rY:
21024 case X86::VFNMADDPSr213rY:
21025 case X86::VFNMSUBPDr213rY:
21026 case X86::VFNMSUBPSr213rY:
21027 case X86::VFMADDSUBPDr213rY:
21028 case X86::VFMADDSUBPSr213rY:
21029 case X86::VFMSUBADDPDr213rY:
21030 case X86::VFMSUBADDPSr213rY:
21031 return emitFMA3Instr(MI, BB);
21035 //===----------------------------------------------------------------------===//
21036 // X86 Optimization Hooks
21037 //===----------------------------------------------------------------------===//
21039 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
21042 const SelectionDAG &DAG,
21043 unsigned Depth) const {
21044 unsigned BitWidth = KnownZero.getBitWidth();
21045 unsigned Opc = Op.getOpcode();
21046 assert((Opc >= ISD::BUILTIN_OP_END ||
21047 Opc == ISD::INTRINSIC_WO_CHAIN ||
21048 Opc == ISD::INTRINSIC_W_CHAIN ||
21049 Opc == ISD::INTRINSIC_VOID) &&
21050 "Should use MaskedValueIsZero if you don't know whether Op"
21051 " is a target node!");
21053 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
21067 // These nodes' second result is a boolean.
21068 if (Op.getResNo() == 0)
21071 case X86ISD::SETCC:
21072 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
21074 case ISD::INTRINSIC_WO_CHAIN: {
21075 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
21076 unsigned NumLoBits = 0;
21079 case Intrinsic::x86_sse_movmsk_ps:
21080 case Intrinsic::x86_avx_movmsk_ps_256:
21081 case Intrinsic::x86_sse2_movmsk_pd:
21082 case Intrinsic::x86_avx_movmsk_pd_256:
21083 case Intrinsic::x86_mmx_pmovmskb:
21084 case Intrinsic::x86_sse2_pmovmskb_128:
21085 case Intrinsic::x86_avx2_pmovmskb: {
21086 // High bits of movmskp{s|d}, pmovmskb are known zero.
21088 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
21089 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
21090 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
21091 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
21092 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
21093 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
21094 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
21095 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
21097 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
21106 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
21108 const SelectionDAG &,
21109 unsigned Depth) const {
21110 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
21111 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
21112 return Op.getValueType().getScalarType().getSizeInBits();
21118 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
21119 /// node is a GlobalAddress + offset.
21120 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
21121 const GlobalValue* &GA,
21122 int64_t &Offset) const {
21123 if (N->getOpcode() == X86ISD::Wrapper) {
21124 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
21125 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
21126 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
21130 return TargetLowering::isGAPlusOffset(N, GA, Offset);
21133 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
21134 /// same as extracting the high 128-bit part of 256-bit vector and then
21135 /// inserting the result into the low part of a new 256-bit vector
21136 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
21137 EVT VT = SVOp->getValueType(0);
21138 unsigned NumElems = VT.getVectorNumElements();
21140 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21141 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
21142 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21143 SVOp->getMaskElt(j) >= 0)
21149 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
21150 /// same as extracting the low 128-bit part of 256-bit vector and then
21151 /// inserting the result into the high part of a new 256-bit vector
21152 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
21153 EVT VT = SVOp->getValueType(0);
21154 unsigned NumElems = VT.getVectorNumElements();
21156 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21157 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
21158 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
21159 SVOp->getMaskElt(j) >= 0)
21165 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
21166 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
21167 TargetLowering::DAGCombinerInfo &DCI,
21168 const X86Subtarget* Subtarget) {
21170 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
21171 SDValue V1 = SVOp->getOperand(0);
21172 SDValue V2 = SVOp->getOperand(1);
21173 EVT VT = SVOp->getValueType(0);
21174 unsigned NumElems = VT.getVectorNumElements();
21176 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
21177 V2.getOpcode() == ISD::CONCAT_VECTORS) {
21181 // V UNDEF BUILD_VECTOR UNDEF
21183 // CONCAT_VECTOR CONCAT_VECTOR
21186 // RESULT: V + zero extended
21188 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
21189 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
21190 V1.getOperand(1).getOpcode() != ISD::UNDEF)
21193 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
21196 // To match the shuffle mask, the first half of the mask should
21197 // be exactly the first vector, and all the rest a splat with the
21198 // first element of the second one.
21199 for (unsigned i = 0; i != NumElems/2; ++i)
21200 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
21201 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
21204 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
21205 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
21206 if (Ld->hasNUsesOfValue(1, 0)) {
21207 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
21208 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
21210 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
21212 Ld->getPointerInfo(),
21213 Ld->getAlignment(),
21214 false/*isVolatile*/, true/*ReadMem*/,
21215 false/*WriteMem*/);
21217 // Make sure the newly-created LOAD is in the same position as Ld in
21218 // terms of dependency. We create a TokenFactor for Ld and ResNode,
21219 // and update uses of Ld's output chain to use the TokenFactor.
21220 if (Ld->hasAnyUseOfValue(1)) {
21221 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21222 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
21223 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
21224 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
21225 SDValue(ResNode.getNode(), 1));
21228 return DAG.getBitcast(VT, ResNode);
21232 // Emit a zeroed vector and insert the desired subvector on its
21234 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
21235 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
21236 return DCI.CombineTo(N, InsV);
21239 //===--------------------------------------------------------------------===//
21240 // Combine some shuffles into subvector extracts and inserts:
21243 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21244 if (isShuffleHigh128VectorInsertLow(SVOp)) {
21245 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
21246 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
21247 return DCI.CombineTo(N, InsV);
21250 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21251 if (isShuffleLow128VectorInsertHigh(SVOp)) {
21252 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
21253 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
21254 return DCI.CombineTo(N, InsV);
21260 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
21263 /// This is the leaf of the recursive combinine below. When we have found some
21264 /// chain of single-use x86 shuffle instructions and accumulated the combined
21265 /// shuffle mask represented by them, this will try to pattern match that mask
21266 /// into either a single instruction if there is a special purpose instruction
21267 /// for this operation, or into a PSHUFB instruction which is a fully general
21268 /// instruction but should only be used to replace chains over a certain depth.
21269 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
21270 int Depth, bool HasPSHUFB, SelectionDAG &DAG,
21271 TargetLowering::DAGCombinerInfo &DCI,
21272 const X86Subtarget *Subtarget) {
21273 assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
21275 // Find the operand that enters the chain. Note that multiple uses are OK
21276 // here, we're not going to remove the operand we find.
21277 SDValue Input = Op.getOperand(0);
21278 while (Input.getOpcode() == ISD::BITCAST)
21279 Input = Input.getOperand(0);
21281 MVT VT = Input.getSimpleValueType();
21282 MVT RootVT = Root.getSimpleValueType();
21285 // Just remove no-op shuffle masks.
21286 if (Mask.size() == 1) {
21287 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
21292 // Use the float domain if the operand type is a floating point type.
21293 bool FloatDomain = VT.isFloatingPoint();
21295 // For floating point shuffles, we don't have free copies in the shuffle
21296 // instructions or the ability to load as part of the instruction, so
21297 // canonicalize their shuffles to UNPCK or MOV variants.
21299 // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
21300 // vectors because it can have a load folded into it that UNPCK cannot. This
21301 // doesn't preclude something switching to the shorter encoding post-RA.
21303 // FIXME: Should teach these routines about AVX vector widths.
21304 if (FloatDomain && VT.getSizeInBits() == 128) {
21305 if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
21306 bool Lo = Mask.equals({0, 0});
21309 // Check if we have SSE3 which will let us use MOVDDUP. That instruction
21310 // is no slower than UNPCKLPD but has the option to fold the input operand
21311 // into even an unaligned memory load.
21312 if (Lo && Subtarget->hasSSE3()) {
21313 Shuffle = X86ISD::MOVDDUP;
21314 ShuffleVT = MVT::v2f64;
21316 // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
21317 // than the UNPCK variants.
21318 Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
21319 ShuffleVT = MVT::v4f32;
21321 if (Depth == 1 && Root->getOpcode() == Shuffle)
21322 return false; // Nothing to do!
21323 Op = DAG.getBitcast(ShuffleVT, Input);
21324 DCI.AddToWorklist(Op.getNode());
21325 if (Shuffle == X86ISD::MOVDDUP)
21326 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21328 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21329 DCI.AddToWorklist(Op.getNode());
21330 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21334 if (Subtarget->hasSSE3() &&
21335 (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
21336 bool Lo = Mask.equals({0, 0, 2, 2});
21337 unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
21338 MVT ShuffleVT = MVT::v4f32;
21339 if (Depth == 1 && Root->getOpcode() == Shuffle)
21340 return false; // Nothing to do!
21341 Op = DAG.getBitcast(ShuffleVT, Input);
21342 DCI.AddToWorklist(Op.getNode());
21343 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21344 DCI.AddToWorklist(Op.getNode());
21345 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21349 if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
21350 bool Lo = Mask.equals({0, 0, 1, 1});
21351 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21352 MVT ShuffleVT = MVT::v4f32;
21353 if (Depth == 1 && Root->getOpcode() == Shuffle)
21354 return false; // Nothing to do!
21355 Op = DAG.getBitcast(ShuffleVT, Input);
21356 DCI.AddToWorklist(Op.getNode());
21357 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21358 DCI.AddToWorklist(Op.getNode());
21359 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21365 // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
21366 // variants as none of these have single-instruction variants that are
21367 // superior to the UNPCK formulation.
21368 if (!FloatDomain && VT.getSizeInBits() == 128 &&
21369 (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21370 Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
21371 Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
21373 {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
21374 bool Lo = Mask[0] == 0;
21375 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21376 if (Depth == 1 && Root->getOpcode() == Shuffle)
21377 return false; // Nothing to do!
21379 switch (Mask.size()) {
21381 ShuffleVT = MVT::v8i16;
21384 ShuffleVT = MVT::v16i8;
21387 llvm_unreachable("Impossible mask size!");
21389 Op = DAG.getBitcast(ShuffleVT, Input);
21390 DCI.AddToWorklist(Op.getNode());
21391 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21392 DCI.AddToWorklist(Op.getNode());
21393 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21398 // Don't try to re-form single instruction chains under any circumstances now
21399 // that we've done encoding canonicalization for them.
21403 // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
21404 // can replace them with a single PSHUFB instruction profitably. Intel's
21405 // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
21406 // in practice PSHUFB tends to be *very* fast so we're more aggressive.
21407 if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
21408 SmallVector<SDValue, 16> PSHUFBMask;
21409 int NumBytes = VT.getSizeInBits() / 8;
21410 int Ratio = NumBytes / Mask.size();
21411 for (int i = 0; i < NumBytes; ++i) {
21412 if (Mask[i / Ratio] == SM_SentinelUndef) {
21413 PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
21416 int M = Mask[i / Ratio] != SM_SentinelZero
21417 ? Ratio * Mask[i / Ratio] + i % Ratio
21419 PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
21421 MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
21422 Op = DAG.getBitcast(ByteVT, Input);
21423 DCI.AddToWorklist(Op.getNode());
21424 SDValue PSHUFBMaskOp =
21425 DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
21426 DCI.AddToWorklist(PSHUFBMaskOp.getNode());
21427 Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
21428 DCI.AddToWorklist(Op.getNode());
21429 DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21434 // Failed to find any combines.
21438 /// \brief Fully generic combining of x86 shuffle instructions.
21440 /// This should be the last combine run over the x86 shuffle instructions. Once
21441 /// they have been fully optimized, this will recursively consider all chains
21442 /// of single-use shuffle instructions, build a generic model of the cumulative
21443 /// shuffle operation, and check for simpler instructions which implement this
21444 /// operation. We use this primarily for two purposes:
21446 /// 1) Collapse generic shuffles to specialized single instructions when
21447 /// equivalent. In most cases, this is just an encoding size win, but
21448 /// sometimes we will collapse multiple generic shuffles into a single
21449 /// special-purpose shuffle.
21450 /// 2) Look for sequences of shuffle instructions with 3 or more total
21451 /// instructions, and replace them with the slightly more expensive SSSE3
21452 /// PSHUFB instruction if available. We do this as the last combining step
21453 /// to ensure we avoid using PSHUFB if we can implement the shuffle with
21454 /// a suitable short sequence of other instructions. The PHUFB will either
21455 /// use a register or have to read from memory and so is slightly (but only
21456 /// slightly) more expensive than the other shuffle instructions.
21458 /// Because this is inherently a quadratic operation (for each shuffle in
21459 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
21460 /// This should never be an issue in practice as the shuffle lowering doesn't
21461 /// produce sequences of more than 8 instructions.
21463 /// FIXME: We will currently miss some cases where the redundant shuffling
21464 /// would simplify under the threshold for PSHUFB formation because of
21465 /// combine-ordering. To fix this, we should do the redundant instruction
21466 /// combining in this recursive walk.
21467 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
21468 ArrayRef<int> RootMask,
21469 int Depth, bool HasPSHUFB,
21471 TargetLowering::DAGCombinerInfo &DCI,
21472 const X86Subtarget *Subtarget) {
21473 // Bound the depth of our recursive combine because this is ultimately
21474 // quadratic in nature.
21478 // Directly rip through bitcasts to find the underlying operand.
21479 while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
21480 Op = Op.getOperand(0);
21482 MVT VT = Op.getSimpleValueType();
21483 if (!VT.isVector())
21484 return false; // Bail if we hit a non-vector.
21486 assert(Root.getSimpleValueType().isVector() &&
21487 "Shuffles operate on vector types!");
21488 assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
21489 "Can only combine shuffles of the same vector register size.");
21491 if (!isTargetShuffle(Op.getOpcode()))
21493 SmallVector<int, 16> OpMask;
21495 bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
21496 // We only can combine unary shuffles which we can decode the mask for.
21497 if (!HaveMask || !IsUnary)
21500 assert(VT.getVectorNumElements() == OpMask.size() &&
21501 "Different mask size from vector size!");
21502 assert(((RootMask.size() > OpMask.size() &&
21503 RootMask.size() % OpMask.size() == 0) ||
21504 (OpMask.size() > RootMask.size() &&
21505 OpMask.size() % RootMask.size() == 0) ||
21506 OpMask.size() == RootMask.size()) &&
21507 "The smaller number of elements must divide the larger.");
21508 int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
21509 int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
21510 assert(((RootRatio == 1 && OpRatio == 1) ||
21511 (RootRatio == 1) != (OpRatio == 1)) &&
21512 "Must not have a ratio for both incoming and op masks!");
21514 SmallVector<int, 16> Mask;
21515 Mask.reserve(std::max(OpMask.size(), RootMask.size()));
21517 // Merge this shuffle operation's mask into our accumulated mask. Note that
21518 // this shuffle's mask will be the first applied to the input, followed by the
21519 // root mask to get us all the way to the root value arrangement. The reason
21520 // for this order is that we are recursing up the operation chain.
21521 for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
21522 int RootIdx = i / RootRatio;
21523 if (RootMask[RootIdx] < 0) {
21524 // This is a zero or undef lane, we're done.
21525 Mask.push_back(RootMask[RootIdx]);
21529 int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
21530 int OpIdx = RootMaskedIdx / OpRatio;
21531 if (OpMask[OpIdx] < 0) {
21532 // The incoming lanes are zero or undef, it doesn't matter which ones we
21534 Mask.push_back(OpMask[OpIdx]);
21538 // Ok, we have non-zero lanes, map them through.
21539 Mask.push_back(OpMask[OpIdx] * OpRatio +
21540 RootMaskedIdx % OpRatio);
21543 // See if we can recurse into the operand to combine more things.
21544 switch (Op.getOpcode()) {
21545 case X86ISD::PSHUFB:
21547 case X86ISD::PSHUFD:
21548 case X86ISD::PSHUFHW:
21549 case X86ISD::PSHUFLW:
21550 if (Op.getOperand(0).hasOneUse() &&
21551 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21552 HasPSHUFB, DAG, DCI, Subtarget))
21556 case X86ISD::UNPCKL:
21557 case X86ISD::UNPCKH:
21558 assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
21559 // We can't check for single use, we have to check that this shuffle is the only user.
21560 if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
21561 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21562 HasPSHUFB, DAG, DCI, Subtarget))
21567 // Minor canonicalization of the accumulated shuffle mask to make it easier
21568 // to match below. All this does is detect masks with squential pairs of
21569 // elements, and shrink them to the half-width mask. It does this in a loop
21570 // so it will reduce the size of the mask to the minimal width mask which
21571 // performs an equivalent shuffle.
21572 SmallVector<int, 16> WidenedMask;
21573 while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
21574 Mask = std::move(WidenedMask);
21575 WidenedMask.clear();
21578 return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
21582 /// \brief Get the PSHUF-style mask from PSHUF node.
21584 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
21585 /// PSHUF-style masks that can be reused with such instructions.
21586 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
21587 MVT VT = N.getSimpleValueType();
21588 SmallVector<int, 4> Mask;
21590 bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
21594 // If we have more than 128-bits, only the low 128-bits of shuffle mask
21595 // matter. Check that the upper masks are repeats and remove them.
21596 if (VT.getSizeInBits() > 128) {
21597 int LaneElts = 128 / VT.getScalarSizeInBits();
21599 for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
21600 for (int j = 0; j < LaneElts; ++j)
21601 assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
21602 "Mask doesn't repeat in high 128-bit lanes!");
21604 Mask.resize(LaneElts);
21607 switch (N.getOpcode()) {
21608 case X86ISD::PSHUFD:
21610 case X86ISD::PSHUFLW:
21613 case X86ISD::PSHUFHW:
21614 Mask.erase(Mask.begin(), Mask.begin() + 4);
21615 for (int &M : Mask)
21619 llvm_unreachable("No valid shuffle instruction found!");
21623 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
21625 /// We walk up the chain and look for a combinable shuffle, skipping over
21626 /// shuffles that we could hoist this shuffle's transformation past without
21627 /// altering anything.
21629 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
21631 TargetLowering::DAGCombinerInfo &DCI) {
21632 assert(N.getOpcode() == X86ISD::PSHUFD &&
21633 "Called with something other than an x86 128-bit half shuffle!");
21636 // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
21637 // of the shuffles in the chain so that we can form a fresh chain to replace
21639 SmallVector<SDValue, 8> Chain;
21640 SDValue V = N.getOperand(0);
21641 for (; V.hasOneUse(); V = V.getOperand(0)) {
21642 switch (V.getOpcode()) {
21644 return SDValue(); // Nothing combined!
21647 // Skip bitcasts as we always know the type for the target specific
21651 case X86ISD::PSHUFD:
21652 // Found another dword shuffle.
21655 case X86ISD::PSHUFLW:
21656 // Check that the low words (being shuffled) are the identity in the
21657 // dword shuffle, and the high words are self-contained.
21658 if (Mask[0] != 0 || Mask[1] != 1 ||
21659 !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
21662 Chain.push_back(V);
21665 case X86ISD::PSHUFHW:
21666 // Check that the high words (being shuffled) are the identity in the
21667 // dword shuffle, and the low words are self-contained.
21668 if (Mask[2] != 2 || Mask[3] != 3 ||
21669 !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
21672 Chain.push_back(V);
21675 case X86ISD::UNPCKL:
21676 case X86ISD::UNPCKH:
21677 // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
21678 // shuffle into a preceding word shuffle.
21679 if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
21680 V.getSimpleValueType().getScalarType() != MVT::i16)
21683 // Search for a half-shuffle which we can combine with.
21684 unsigned CombineOp =
21685 V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
21686 if (V.getOperand(0) != V.getOperand(1) ||
21687 !V->isOnlyUserOf(V.getOperand(0).getNode()))
21689 Chain.push_back(V);
21690 V = V.getOperand(0);
21692 switch (V.getOpcode()) {
21694 return SDValue(); // Nothing to combine.
21696 case X86ISD::PSHUFLW:
21697 case X86ISD::PSHUFHW:
21698 if (V.getOpcode() == CombineOp)
21701 Chain.push_back(V);
21705 V = V.getOperand(0);
21709 } while (V.hasOneUse());
21712 // Break out of the loop if we break out of the switch.
21716 if (!V.hasOneUse())
21717 // We fell out of the loop without finding a viable combining instruction.
21720 // Merge this node's mask and our incoming mask.
21721 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21722 for (int &M : Mask)
21724 V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
21725 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
21727 // Rebuild the chain around this new shuffle.
21728 while (!Chain.empty()) {
21729 SDValue W = Chain.pop_back_val();
21731 if (V.getValueType() != W.getOperand(0).getValueType())
21732 V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
21734 switch (W.getOpcode()) {
21736 llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
21738 case X86ISD::UNPCKL:
21739 case X86ISD::UNPCKH:
21740 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
21743 case X86ISD::PSHUFD:
21744 case X86ISD::PSHUFLW:
21745 case X86ISD::PSHUFHW:
21746 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
21750 if (V.getValueType() != N.getValueType())
21751 V = DAG.getBitcast(N.getValueType(), V);
21753 // Return the new chain to replace N.
21757 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
21759 /// We walk up the chain, skipping shuffles of the other half and looking
21760 /// through shuffles which switch halves trying to find a shuffle of the same
21761 /// pair of dwords.
21762 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
21764 TargetLowering::DAGCombinerInfo &DCI) {
21766 (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
21767 "Called with something other than an x86 128-bit half shuffle!");
21769 unsigned CombineOpcode = N.getOpcode();
21771 // Walk up a single-use chain looking for a combinable shuffle.
21772 SDValue V = N.getOperand(0);
21773 for (; V.hasOneUse(); V = V.getOperand(0)) {
21774 switch (V.getOpcode()) {
21776 return false; // Nothing combined!
21779 // Skip bitcasts as we always know the type for the target specific
21783 case X86ISD::PSHUFLW:
21784 case X86ISD::PSHUFHW:
21785 if (V.getOpcode() == CombineOpcode)
21788 // Other-half shuffles are no-ops.
21791 // Break out of the loop if we break out of the switch.
21795 if (!V.hasOneUse())
21796 // We fell out of the loop without finding a viable combining instruction.
21799 // Combine away the bottom node as its shuffle will be accumulated into
21800 // a preceding shuffle.
21801 DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
21803 // Record the old value.
21806 // Merge this node's mask and our incoming mask (adjusted to account for all
21807 // the pshufd instructions encountered).
21808 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21809 for (int &M : Mask)
21811 V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
21812 getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
21814 // Check that the shuffles didn't cancel each other out. If not, we need to
21815 // combine to the new one.
21817 // Replace the combinable shuffle with the combined one, updating all users
21818 // so that we re-evaluate the chain here.
21819 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
21824 /// \brief Try to combine x86 target specific shuffles.
21825 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
21826 TargetLowering::DAGCombinerInfo &DCI,
21827 const X86Subtarget *Subtarget) {
21829 MVT VT = N.getSimpleValueType();
21830 SmallVector<int, 4> Mask;
21832 switch (N.getOpcode()) {
21833 case X86ISD::PSHUFD:
21834 case X86ISD::PSHUFLW:
21835 case X86ISD::PSHUFHW:
21836 Mask = getPSHUFShuffleMask(N);
21837 assert(Mask.size() == 4);
21843 // Nuke no-op shuffles that show up after combining.
21844 if (isNoopShuffleMask(Mask))
21845 return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
21847 // Look for simplifications involving one or two shuffle instructions.
21848 SDValue V = N.getOperand(0);
21849 switch (N.getOpcode()) {
21852 case X86ISD::PSHUFLW:
21853 case X86ISD::PSHUFHW:
21854 assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
21856 if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
21857 return SDValue(); // We combined away this shuffle, so we're done.
21859 // See if this reduces to a PSHUFD which is no more expensive and can
21860 // combine with more operations. Note that it has to at least flip the
21861 // dwords as otherwise it would have been removed as a no-op.
21862 if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
21863 int DMask[] = {0, 1, 2, 3};
21864 int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
21865 DMask[DOffset + 0] = DOffset + 1;
21866 DMask[DOffset + 1] = DOffset + 0;
21867 MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
21868 V = DAG.getBitcast(DVT, V);
21869 DCI.AddToWorklist(V.getNode());
21870 V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
21871 getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
21872 DCI.AddToWorklist(V.getNode());
21873 return DAG.getBitcast(VT, V);
21876 // Look for shuffle patterns which can be implemented as a single unpack.
21877 // FIXME: This doesn't handle the location of the PSHUFD generically, and
21878 // only works when we have a PSHUFD followed by two half-shuffles.
21879 if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
21880 (V.getOpcode() == X86ISD::PSHUFLW ||
21881 V.getOpcode() == X86ISD::PSHUFHW) &&
21882 V.getOpcode() != N.getOpcode() &&
21884 SDValue D = V.getOperand(0);
21885 while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
21886 D = D.getOperand(0);
21887 if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
21888 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21889 SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
21890 int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
21891 int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
21893 for (int i = 0; i < 4; ++i) {
21894 WordMask[i + NOffset] = Mask[i] + NOffset;
21895 WordMask[i + VOffset] = VMask[i] + VOffset;
21897 // Map the word mask through the DWord mask.
21899 for (int i = 0; i < 8; ++i)
21900 MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
21901 if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21902 makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
21903 // We can replace all three shuffles with an unpack.
21904 V = DAG.getBitcast(VT, D.getOperand(0));
21905 DCI.AddToWorklist(V.getNode());
21906 return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
21915 case X86ISD::PSHUFD:
21916 if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
21925 /// \brief Try to combine a shuffle into a target-specific add-sub node.
21927 /// We combine this directly on the abstract vector shuffle nodes so it is
21928 /// easier to generically match. We also insert dummy vector shuffle nodes for
21929 /// the operands which explicitly discard the lanes which are unused by this
21930 /// operation to try to flow through the rest of the combiner the fact that
21931 /// they're unused.
21932 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
21934 EVT VT = N->getValueType(0);
21936 // We only handle target-independent shuffles.
21937 // FIXME: It would be easy and harmless to use the target shuffle mask
21938 // extraction tool to support more.
21939 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
21942 auto *SVN = cast<ShuffleVectorSDNode>(N);
21943 ArrayRef<int> Mask = SVN->getMask();
21944 SDValue V1 = N->getOperand(0);
21945 SDValue V2 = N->getOperand(1);
21947 // We require the first shuffle operand to be the SUB node, and the second to
21948 // be the ADD node.
21949 // FIXME: We should support the commuted patterns.
21950 if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
21953 // If there are other uses of these operations we can't fold them.
21954 if (!V1->hasOneUse() || !V2->hasOneUse())
21957 // Ensure that both operations have the same operands. Note that we can
21958 // commute the FADD operands.
21959 SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
21960 if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
21961 (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
21964 // We're looking for blends between FADD and FSUB nodes. We insist on these
21965 // nodes being lined up in a specific expected pattern.
21966 if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
21967 isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
21968 isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
21971 // Only specific types are legal at this point, assert so we notice if and
21972 // when these change.
21973 assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
21974 VT == MVT::v4f64) &&
21975 "Unknown vector type encountered!");
21977 return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
21980 /// PerformShuffleCombine - Performs several different shuffle combines.
21981 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
21982 TargetLowering::DAGCombinerInfo &DCI,
21983 const X86Subtarget *Subtarget) {
21985 SDValue N0 = N->getOperand(0);
21986 SDValue N1 = N->getOperand(1);
21987 EVT VT = N->getValueType(0);
21989 // Don't create instructions with illegal types after legalize types has run.
21990 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21991 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
21994 // If we have legalized the vector types, look for blends of FADD and FSUB
21995 // nodes that we can fuse into an ADDSUB node.
21996 if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
21997 if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
22000 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
22001 if (Subtarget->hasFp256() && VT.is256BitVector() &&
22002 N->getOpcode() == ISD::VECTOR_SHUFFLE)
22003 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
22005 // During Type Legalization, when promoting illegal vector types,
22006 // the backend might introduce new shuffle dag nodes and bitcasts.
22008 // This code performs the following transformation:
22009 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
22010 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
22012 // We do this only if both the bitcast and the BINOP dag nodes have
22013 // one use. Also, perform this transformation only if the new binary
22014 // operation is legal. This is to avoid introducing dag nodes that
22015 // potentially need to be further expanded (or custom lowered) into a
22016 // less optimal sequence of dag nodes.
22017 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
22018 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
22019 N0.getOpcode() == ISD::BITCAST) {
22020 SDValue BC0 = N0.getOperand(0);
22021 EVT SVT = BC0.getValueType();
22022 unsigned Opcode = BC0.getOpcode();
22023 unsigned NumElts = VT.getVectorNumElements();
22025 if (BC0.hasOneUse() && SVT.isVector() &&
22026 SVT.getVectorNumElements() * 2 == NumElts &&
22027 TLI.isOperationLegal(Opcode, VT)) {
22028 bool CanFold = false;
22040 unsigned SVTNumElts = SVT.getVectorNumElements();
22041 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
22042 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
22043 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
22044 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
22045 CanFold = SVOp->getMaskElt(i) < 0;
22048 SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
22049 SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
22050 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
22051 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
22056 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
22057 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
22058 // consecutive, non-overlapping, and in the right order.
22059 SmallVector<SDValue, 16> Elts;
22060 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
22061 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
22063 if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
22066 if (isTargetShuffle(N->getOpcode())) {
22068 PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
22069 if (Shuffle.getNode())
22072 // Try recursively combining arbitrary sequences of x86 shuffle
22073 // instructions into higher-order shuffles. We do this after combining
22074 // specific PSHUF instruction sequences into their minimal form so that we
22075 // can evaluate how many specialized shuffle instructions are involved in
22076 // a particular chain.
22077 SmallVector<int, 1> NonceMask; // Just a placeholder.
22078 NonceMask.push_back(0);
22079 if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
22080 /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
22082 return SDValue(); // This routine will use CombineTo to replace N.
22088 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
22089 /// specific shuffle of a load can be folded into a single element load.
22090 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
22091 /// shuffles have been custom lowered so we need to handle those here.
22092 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
22093 TargetLowering::DAGCombinerInfo &DCI) {
22094 if (DCI.isBeforeLegalizeOps())
22097 SDValue InVec = N->getOperand(0);
22098 SDValue EltNo = N->getOperand(1);
22100 if (!isa<ConstantSDNode>(EltNo))
22103 EVT OriginalVT = InVec.getValueType();
22105 if (InVec.getOpcode() == ISD::BITCAST) {
22106 // Don't duplicate a load with other uses.
22107 if (!InVec.hasOneUse())
22109 EVT BCVT = InVec.getOperand(0).getValueType();
22110 if (!BCVT.isVector() ||
22111 BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
22113 InVec = InVec.getOperand(0);
22116 EVT CurrentVT = InVec.getValueType();
22118 if (!isTargetShuffle(InVec.getOpcode()))
22121 // Don't duplicate a load with other uses.
22122 if (!InVec.hasOneUse())
22125 SmallVector<int, 16> ShuffleMask;
22127 if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
22128 ShuffleMask, UnaryShuffle))
22131 // Select the input vector, guarding against out of range extract vector.
22132 unsigned NumElems = CurrentVT.getVectorNumElements();
22133 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
22134 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
22135 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
22136 : InVec.getOperand(1);
22138 // If inputs to shuffle are the same for both ops, then allow 2 uses
22139 unsigned AllowedUses = InVec.getNumOperands() > 1 &&
22140 InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
22142 if (LdNode.getOpcode() == ISD::BITCAST) {
22143 // Don't duplicate a load with other uses.
22144 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
22147 AllowedUses = 1; // only allow 1 load use if we have a bitcast
22148 LdNode = LdNode.getOperand(0);
22151 if (!ISD::isNormalLoad(LdNode.getNode()))
22154 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
22156 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
22159 EVT EltVT = N->getValueType(0);
22160 // If there's a bitcast before the shuffle, check if the load type and
22161 // alignment is valid.
22162 unsigned Align = LN0->getAlignment();
22163 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22164 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
22165 EltVT.getTypeForEVT(*DAG.getContext()));
22167 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
22170 // All checks match so transform back to vector_shuffle so that DAG combiner
22171 // can finish the job
22174 // Create shuffle node taking into account the case that its a unary shuffle
22175 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
22176 : InVec.getOperand(1);
22177 Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
22178 InVec.getOperand(0), Shuffle,
22180 Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
22181 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
22185 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
22186 /// special and don't usually play with other vector types, it's better to
22187 /// handle them early to be sure we emit efficient code by avoiding
22188 /// store-load conversions.
22189 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
22190 if (N->getValueType(0) != MVT::x86mmx ||
22191 N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
22192 N->getOperand(0)->getValueType(0) != MVT::v2i32)
22195 SDValue V = N->getOperand(0);
22196 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
22197 if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
22198 return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
22199 N->getValueType(0), V.getOperand(0));
22204 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
22205 /// generation and convert it from being a bunch of shuffles and extracts
22206 /// into a somewhat faster sequence. For i686, the best sequence is apparently
22207 /// storing the value and loading scalars back, while for x64 we should
22208 /// use 64-bit extracts and shifts.
22209 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
22210 TargetLowering::DAGCombinerInfo &DCI) {
22211 if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
22214 SDValue InputVector = N->getOperand(0);
22215 SDLoc dl(InputVector);
22216 // Detect mmx to i32 conversion through a v2i32 elt extract.
22217 if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
22218 N->getValueType(0) == MVT::i32 &&
22219 InputVector.getValueType() == MVT::v2i32) {
22221 // The bitcast source is a direct mmx result.
22222 SDValue MMXSrc = InputVector.getNode()->getOperand(0);
22223 if (MMXSrc.getValueType() == MVT::x86mmx)
22224 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22225 N->getValueType(0),
22226 InputVector.getNode()->getOperand(0));
22228 // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
22229 SDValue MMXSrcOp = MMXSrc.getOperand(0);
22230 if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
22231 MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
22232 MMXSrcOp.getOpcode() == ISD::BITCAST &&
22233 MMXSrcOp.getValueType() == MVT::v1i64 &&
22234 MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
22235 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22236 N->getValueType(0),
22237 MMXSrcOp.getOperand(0));
22240 EVT VT = N->getValueType(0);
22242 if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
22243 InputVector.getOpcode() == ISD::BITCAST &&
22244 dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
22245 uint64_t ExtractedElt =
22246 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
22247 uint64_t InputValue =
22248 cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
22249 uint64_t Res = (InputValue >> ExtractedElt) & 1;
22250 return DAG.getConstant(Res, dl, MVT::i1);
22252 // Only operate on vectors of 4 elements, where the alternative shuffling
22253 // gets to be more expensive.
22254 if (InputVector.getValueType() != MVT::v4i32)
22257 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
22258 // single use which is a sign-extend or zero-extend, and all elements are
22260 SmallVector<SDNode *, 4> Uses;
22261 unsigned ExtractedElements = 0;
22262 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
22263 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
22264 if (UI.getUse().getResNo() != InputVector.getResNo())
22267 SDNode *Extract = *UI;
22268 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
22271 if (Extract->getValueType(0) != MVT::i32)
22273 if (!Extract->hasOneUse())
22275 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
22276 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
22278 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
22281 // Record which element was extracted.
22282 ExtractedElements |=
22283 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
22285 Uses.push_back(Extract);
22288 // If not all the elements were used, this may not be worthwhile.
22289 if (ExtractedElements != 15)
22292 // Ok, we've now decided to do the transformation.
22293 // If 64-bit shifts are legal, use the extract-shift sequence,
22294 // otherwise bounce the vector off the cache.
22295 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22298 if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
22299 SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
22300 auto &DL = DAG.getDataLayout();
22301 EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
22302 SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22303 DAG.getConstant(0, dl, VecIdxTy));
22304 SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22305 DAG.getConstant(1, dl, VecIdxTy));
22307 SDValue ShAmt = DAG.getConstant(
22308 32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
22309 Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
22310 Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22311 DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
22312 Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
22313 Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22314 DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
22316 // Store the value to a temporary stack slot.
22317 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
22318 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
22319 MachinePointerInfo(), false, false, 0);
22321 EVT ElementType = InputVector.getValueType().getVectorElementType();
22322 unsigned EltSize = ElementType.getSizeInBits() / 8;
22324 // Replace each use (extract) with a load of the appropriate element.
22325 for (unsigned i = 0; i < 4; ++i) {
22326 uint64_t Offset = EltSize * i;
22327 auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
22328 SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
22330 SDValue ScalarAddr =
22331 DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
22333 // Load the scalar.
22334 Vals[i] = DAG.getLoad(ElementType, dl, Ch,
22335 ScalarAddr, MachinePointerInfo(),
22336 false, false, false, 0);
22341 // Replace the extracts
22342 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
22343 UE = Uses.end(); UI != UE; ++UI) {
22344 SDNode *Extract = *UI;
22346 SDValue Idx = Extract->getOperand(1);
22347 uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
22348 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
22351 // The replacement was made in place; don't return anything.
22355 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
22356 static std::pair<unsigned, bool>
22357 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
22358 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
22359 if (!VT.isVector())
22360 return std::make_pair(0, false);
22362 bool NeedSplit = false;
22363 switch (VT.getSimpleVT().SimpleTy) {
22364 default: return std::make_pair(0, false);
22367 if (!Subtarget->hasVLX())
22368 return std::make_pair(0, false);
22372 if (!Subtarget->hasBWI())
22373 return std::make_pair(0, false);
22377 if (!Subtarget->hasAVX512())
22378 return std::make_pair(0, false);
22383 if (!Subtarget->hasAVX2())
22385 if (!Subtarget->hasAVX())
22386 return std::make_pair(0, false);
22391 if (!Subtarget->hasSSE2())
22392 return std::make_pair(0, false);
22395 // SSE2 has only a small subset of the operations.
22396 bool hasUnsigned = Subtarget->hasSSE41() ||
22397 (Subtarget->hasSSE2() && VT == MVT::v16i8);
22398 bool hasSigned = Subtarget->hasSSE41() ||
22399 (Subtarget->hasSSE2() && VT == MVT::v8i16);
22401 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22404 // Check for x CC y ? x : y.
22405 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22406 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22411 Opc = hasUnsigned ? ISD::UMIN : 0; break;
22414 Opc = hasUnsigned ? ISD::UMAX : 0; break;
22417 Opc = hasSigned ? ISD::SMIN : 0; break;
22420 Opc = hasSigned ? ISD::SMAX : 0; break;
22422 // Check for x CC y ? y : x -- a min/max with reversed arms.
22423 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22424 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22429 Opc = hasUnsigned ? ISD::UMAX : 0; break;
22432 Opc = hasUnsigned ? ISD::UMIN : 0; break;
22435 Opc = hasSigned ? ISD::SMAX : 0; break;
22438 Opc = hasSigned ? ISD::SMIN : 0; break;
22442 return std::make_pair(Opc, NeedSplit);
22446 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
22447 const X86Subtarget *Subtarget) {
22449 SDValue Cond = N->getOperand(0);
22450 SDValue LHS = N->getOperand(1);
22451 SDValue RHS = N->getOperand(2);
22453 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
22454 SDValue CondSrc = Cond->getOperand(0);
22455 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
22456 Cond = CondSrc->getOperand(0);
22459 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
22462 // A vselect where all conditions and data are constants can be optimized into
22463 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
22464 if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
22465 ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
22468 unsigned MaskValue = 0;
22469 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
22472 MVT VT = N->getSimpleValueType(0);
22473 unsigned NumElems = VT.getVectorNumElements();
22474 SmallVector<int, 8> ShuffleMask(NumElems, -1);
22475 for (unsigned i = 0; i < NumElems; ++i) {
22476 // Be sure we emit undef where we can.
22477 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
22478 ShuffleMask[i] = -1;
22480 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
22483 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22484 if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
22486 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
22489 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
22491 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
22492 TargetLowering::DAGCombinerInfo &DCI,
22493 const X86Subtarget *Subtarget) {
22495 SDValue Cond = N->getOperand(0);
22496 // Get the LHS/RHS of the select.
22497 SDValue LHS = N->getOperand(1);
22498 SDValue RHS = N->getOperand(2);
22499 EVT VT = LHS.getValueType();
22500 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22502 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
22503 // instructions match the semantics of the common C idiom x<y?x:y but not
22504 // x<=y?x:y, because of how they handle negative zero (which can be
22505 // ignored in unsafe-math mode).
22506 // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
22507 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
22508 VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
22509 (Subtarget->hasSSE2() ||
22510 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
22511 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22513 unsigned Opcode = 0;
22514 // Check for x CC y ? x : y.
22515 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22516 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22520 // Converting this to a min would handle NaNs incorrectly, and swapping
22521 // the operands would cause it to handle comparisons between positive
22522 // and negative zero incorrectly.
22523 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22524 if (!DAG.getTarget().Options.UnsafeFPMath &&
22525 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22527 std::swap(LHS, RHS);
22529 Opcode = X86ISD::FMIN;
22532 // Converting this to a min would handle comparisons between positive
22533 // and negative zero incorrectly.
22534 if (!DAG.getTarget().Options.UnsafeFPMath &&
22535 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22537 Opcode = X86ISD::FMIN;
22540 // Converting this to a min would handle both negative zeros and NaNs
22541 // incorrectly, but we can swap the operands to fix both.
22542 std::swap(LHS, RHS);
22546 Opcode = X86ISD::FMIN;
22550 // Converting this to a max would handle comparisons between positive
22551 // and negative zero incorrectly.
22552 if (!DAG.getTarget().Options.UnsafeFPMath &&
22553 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22555 Opcode = X86ISD::FMAX;
22558 // Converting this to a max would handle NaNs incorrectly, and swapping
22559 // the operands would cause it to handle comparisons between positive
22560 // and negative zero incorrectly.
22561 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22562 if (!DAG.getTarget().Options.UnsafeFPMath &&
22563 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22565 std::swap(LHS, RHS);
22567 Opcode = X86ISD::FMAX;
22570 // Converting this to a max would handle both negative zeros and NaNs
22571 // incorrectly, but we can swap the operands to fix both.
22572 std::swap(LHS, RHS);
22576 Opcode = X86ISD::FMAX;
22579 // Check for x CC y ? y : x -- a min/max with reversed arms.
22580 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22581 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22585 // Converting this to a min would handle comparisons between positive
22586 // and negative zero incorrectly, and swapping the operands would
22587 // cause it to handle NaNs incorrectly.
22588 if (!DAG.getTarget().Options.UnsafeFPMath &&
22589 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
22590 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22592 std::swap(LHS, RHS);
22594 Opcode = X86ISD::FMIN;
22597 // Converting this to a min would handle NaNs incorrectly.
22598 if (!DAG.getTarget().Options.UnsafeFPMath &&
22599 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
22601 Opcode = X86ISD::FMIN;
22604 // Converting this to a min would handle both negative zeros and NaNs
22605 // incorrectly, but we can swap the operands to fix both.
22606 std::swap(LHS, RHS);
22610 Opcode = X86ISD::FMIN;
22614 // Converting this to a max would handle NaNs incorrectly.
22615 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22617 Opcode = X86ISD::FMAX;
22620 // Converting this to a max would handle comparisons between positive
22621 // and negative zero incorrectly, and swapping the operands would
22622 // cause it to handle NaNs incorrectly.
22623 if (!DAG.getTarget().Options.UnsafeFPMath &&
22624 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
22625 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22627 std::swap(LHS, RHS);
22629 Opcode = X86ISD::FMAX;
22632 // Converting this to a max would handle both negative zeros and NaNs
22633 // incorrectly, but we can swap the operands to fix both.
22634 std::swap(LHS, RHS);
22638 Opcode = X86ISD::FMAX;
22644 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
22647 EVT CondVT = Cond.getValueType();
22648 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
22649 CondVT.getVectorElementType() == MVT::i1) {
22650 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
22651 // lowering on KNL. In this case we convert it to
22652 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
22653 // The same situation for all 128 and 256-bit vectors of i8 and i16.
22654 // Since SKX these selects have a proper lowering.
22655 EVT OpVT = LHS.getValueType();
22656 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
22657 (OpVT.getVectorElementType() == MVT::i8 ||
22658 OpVT.getVectorElementType() == MVT::i16) &&
22659 !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
22660 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
22661 DCI.AddToWorklist(Cond.getNode());
22662 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
22665 // If this is a select between two integer constants, try to do some
22667 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
22668 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
22669 // Don't do this for crazy integer types.
22670 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
22671 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
22672 // so that TrueC (the true value) is larger than FalseC.
22673 bool NeedsCondInvert = false;
22675 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
22676 // Efficiently invertible.
22677 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
22678 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
22679 isa<ConstantSDNode>(Cond.getOperand(1))))) {
22680 NeedsCondInvert = true;
22681 std::swap(TrueC, FalseC);
22684 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
22685 if (FalseC->getAPIntValue() == 0 &&
22686 TrueC->getAPIntValue().isPowerOf2()) {
22687 if (NeedsCondInvert) // Invert the condition if needed.
22688 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22689 DAG.getConstant(1, DL, Cond.getValueType()));
22691 // Zero extend the condition if needed.
22692 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
22694 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
22695 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
22696 DAG.getConstant(ShAmt, DL, MVT::i8));
22699 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
22700 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
22701 if (NeedsCondInvert) // Invert the condition if needed.
22702 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22703 DAG.getConstant(1, DL, Cond.getValueType()));
22705 // Zero extend the condition if needed.
22706 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
22707 FalseC->getValueType(0), Cond);
22708 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22709 SDValue(FalseC, 0));
22712 // Optimize cases that will turn into an LEA instruction. This requires
22713 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
22714 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
22715 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
22716 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
22718 bool isFastMultiplier = false;
22720 switch ((unsigned char)Diff) {
22722 case 1: // result = add base, cond
22723 case 2: // result = lea base( , cond*2)
22724 case 3: // result = lea base(cond, cond*2)
22725 case 4: // result = lea base( , cond*4)
22726 case 5: // result = lea base(cond, cond*4)
22727 case 8: // result = lea base( , cond*8)
22728 case 9: // result = lea base(cond, cond*8)
22729 isFastMultiplier = true;
22734 if (isFastMultiplier) {
22735 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
22736 if (NeedsCondInvert) // Invert the condition if needed.
22737 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22738 DAG.getConstant(1, DL, Cond.getValueType()));
22740 // Zero extend the condition if needed.
22741 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
22743 // Scale the condition by the difference.
22745 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
22746 DAG.getConstant(Diff, DL,
22747 Cond.getValueType()));
22749 // Add the base if non-zero.
22750 if (FalseC->getAPIntValue() != 0)
22751 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22752 SDValue(FalseC, 0));
22759 // Canonicalize max and min:
22760 // (x > y) ? x : y -> (x >= y) ? x : y
22761 // (x < y) ? x : y -> (x <= y) ? x : y
22762 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
22763 // the need for an extra compare
22764 // against zero. e.g.
22765 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
22767 // testl %edi, %edi
22769 // cmovgl %edi, %eax
22773 // cmovsl %eax, %edi
22774 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
22775 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22776 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22777 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22782 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
22783 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
22784 Cond.getOperand(0), Cond.getOperand(1), NewCC);
22785 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
22790 // Early exit check
22791 if (!TLI.isTypeLegal(VT))
22794 // Match VSELECTs into subs with unsigned saturation.
22795 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
22796 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
22797 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
22798 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
22799 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22801 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
22802 // left side invert the predicate to simplify logic below.
22804 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
22806 CC = ISD::getSetCCInverse(CC, true);
22807 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
22811 if (Other.getNode() && Other->getNumOperands() == 2 &&
22812 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
22813 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
22814 SDValue CondRHS = Cond->getOperand(1);
22816 // Look for a general sub with unsigned saturation first.
22817 // x >= y ? x-y : 0 --> subus x, y
22818 // x > y ? x-y : 0 --> subus x, y
22819 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
22820 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
22821 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
22823 if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
22824 if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
22825 if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
22826 if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
22827 // If the RHS is a constant we have to reverse the const
22828 // canonicalization.
22829 // x > C-1 ? x+-C : 0 --> subus x, C
22830 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
22831 CondRHSConst->getAPIntValue() ==
22832 (-OpRHSConst->getAPIntValue() - 1))
22833 return DAG.getNode(
22834 X86ISD::SUBUS, DL, VT, OpLHS,
22835 DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
22837 // Another special case: If C was a sign bit, the sub has been
22838 // canonicalized into a xor.
22839 // FIXME: Would it be better to use computeKnownBits to determine
22840 // whether it's safe to decanonicalize the xor?
22841 // x s< 0 ? x^C : 0 --> subus x, C
22842 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
22843 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
22844 OpRHSConst->getAPIntValue().isSignBit())
22845 // Note that we have to rebuild the RHS constant here to ensure we
22846 // don't rely on particular values of undef lanes.
22847 return DAG.getNode(
22848 X86ISD::SUBUS, DL, VT, OpLHS,
22849 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
22854 // Try to match a min/max vector operation.
22855 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
22856 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
22857 unsigned Opc = ret.first;
22858 bool NeedSplit = ret.second;
22860 if (Opc && NeedSplit) {
22861 unsigned NumElems = VT.getVectorNumElements();
22862 // Extract the LHS vectors
22863 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
22864 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
22866 // Extract the RHS vectors
22867 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
22868 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
22870 // Create min/max for each subvector
22871 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
22872 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
22874 // Merge the result
22875 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
22877 return DAG.getNode(Opc, DL, VT, LHS, RHS);
22880 // Simplify vector selection if condition value type matches vselect
22882 if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
22883 assert(Cond.getValueType().isVector() &&
22884 "vector select expects a vector selector!");
22886 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
22887 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
22889 // Try invert the condition if true value is not all 1s and false value
22891 if (!TValIsAllOnes && !FValIsAllZeros &&
22892 // Check if the selector will be produced by CMPP*/PCMP*
22893 Cond.getOpcode() == ISD::SETCC &&
22894 // Check if SETCC has already been promoted
22895 TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
22897 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
22898 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
22900 if (TValIsAllZeros || FValIsAllOnes) {
22901 SDValue CC = Cond.getOperand(2);
22902 ISD::CondCode NewCC =
22903 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
22904 Cond.getOperand(0).getValueType().isInteger());
22905 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
22906 std::swap(LHS, RHS);
22907 TValIsAllOnes = FValIsAllOnes;
22908 FValIsAllZeros = TValIsAllZeros;
22912 if (TValIsAllOnes || FValIsAllZeros) {
22915 if (TValIsAllOnes && FValIsAllZeros)
22917 else if (TValIsAllOnes)
22919 DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
22920 else if (FValIsAllZeros)
22921 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
22922 DAG.getBitcast(CondVT, LHS));
22924 return DAG.getBitcast(VT, Ret);
22928 // We should generate an X86ISD::BLENDI from a vselect if its argument
22929 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
22930 // constants. This specific pattern gets generated when we split a
22931 // selector for a 512 bit vector in a machine without AVX512 (but with
22932 // 256-bit vectors), during legalization:
22934 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
22936 // Iff we find this pattern and the build_vectors are built from
22937 // constants, we translate the vselect into a shuffle_vector that we
22938 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
22939 if ((N->getOpcode() == ISD::VSELECT ||
22940 N->getOpcode() == X86ISD::SHRUNKBLEND) &&
22941 !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
22942 SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
22943 if (Shuffle.getNode())
22947 // If this is a *dynamic* select (non-constant condition) and we can match
22948 // this node with one of the variable blend instructions, restructure the
22949 // condition so that the blends can use the high bit of each element and use
22950 // SimplifyDemandedBits to simplify the condition operand.
22951 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
22952 !DCI.isBeforeLegalize() &&
22953 !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
22954 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
22956 // Don't optimize vector selects that map to mask-registers.
22960 // We can only handle the cases where VSELECT is directly legal on the
22961 // subtarget. We custom lower VSELECT nodes with constant conditions and
22962 // this makes it hard to see whether a dynamic VSELECT will correctly
22963 // lower, so we both check the operation's status and explicitly handle the
22964 // cases where a *dynamic* blend will fail even though a constant-condition
22965 // blend could be custom lowered.
22966 // FIXME: We should find a better way to handle this class of problems.
22967 // Potentially, we should combine constant-condition vselect nodes
22968 // pre-legalization into shuffles and not mark as many types as custom
22970 if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
22972 // FIXME: We don't support i16-element blends currently. We could and
22973 // should support them by making *all* the bits in the condition be set
22974 // rather than just the high bit and using an i8-element blend.
22975 if (VT.getScalarType() == MVT::i16)
22977 // Dynamic blending was only available from SSE4.1 onward.
22978 if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
22980 // Byte blends are only available in AVX2
22981 if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
22982 !Subtarget->hasAVX2())
22985 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
22986 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
22988 APInt KnownZero, KnownOne;
22989 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
22990 DCI.isBeforeLegalizeOps());
22991 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
22992 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
22994 // If we changed the computation somewhere in the DAG, this change
22995 // will affect all users of Cond.
22996 // Make sure it is fine and update all the nodes so that we do not
22997 // use the generic VSELECT anymore. Otherwise, we may perform
22998 // wrong optimizations as we messed up with the actual expectation
22999 // for the vector boolean values.
23000 if (Cond != TLO.Old) {
23001 // Check all uses of that condition operand to check whether it will be
23002 // consumed by non-BLEND instructions, which may depend on all bits are
23004 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23006 if (I->getOpcode() != ISD::VSELECT)
23007 // TODO: Add other opcodes eventually lowered into BLEND.
23010 // Update all the users of the condition, before committing the change,
23011 // so that the VSELECT optimizations that expect the correct vector
23012 // boolean value will not be triggered.
23013 for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
23015 DAG.ReplaceAllUsesOfValueWith(
23017 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
23018 Cond, I->getOperand(1), I->getOperand(2)));
23019 DCI.CommitTargetLoweringOpt(TLO);
23022 // At this point, only Cond is changed. Change the condition
23023 // just for N to keep the opportunity to optimize all other
23024 // users their own way.
23025 DAG.ReplaceAllUsesOfValueWith(
23027 DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
23028 TLO.New, N->getOperand(1), N->getOperand(2)));
23036 // Check whether a boolean test is testing a boolean value generated by
23037 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
23040 // Simplify the following patterns:
23041 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
23042 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
23043 // to (Op EFLAGS Cond)
23045 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
23046 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
23047 // to (Op EFLAGS !Cond)
23049 // where Op could be BRCOND or CMOV.
23051 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
23052 // Quit if not CMP and SUB with its value result used.
23053 if (Cmp.getOpcode() != X86ISD::CMP &&
23054 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
23057 // Quit if not used as a boolean value.
23058 if (CC != X86::COND_E && CC != X86::COND_NE)
23061 // Check CMP operands. One of them should be 0 or 1 and the other should be
23062 // an SetCC or extended from it.
23063 SDValue Op1 = Cmp.getOperand(0);
23064 SDValue Op2 = Cmp.getOperand(1);
23067 const ConstantSDNode* C = nullptr;
23068 bool needOppositeCond = (CC == X86::COND_E);
23069 bool checkAgainstTrue = false; // Is it a comparison against 1?
23071 if ((C = dyn_cast<ConstantSDNode>(Op1)))
23073 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
23075 else // Quit if all operands are not constants.
23078 if (C->getZExtValue() == 1) {
23079 needOppositeCond = !needOppositeCond;
23080 checkAgainstTrue = true;
23081 } else if (C->getZExtValue() != 0)
23082 // Quit if the constant is neither 0 or 1.
23085 bool truncatedToBoolWithAnd = false;
23086 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
23087 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
23088 SetCC.getOpcode() == ISD::TRUNCATE ||
23089 SetCC.getOpcode() == ISD::AND) {
23090 if (SetCC.getOpcode() == ISD::AND) {
23092 ConstantSDNode *CS;
23093 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
23094 CS->getZExtValue() == 1)
23096 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
23097 CS->getZExtValue() == 1)
23101 SetCC = SetCC.getOperand(OpIdx);
23102 truncatedToBoolWithAnd = true;
23104 SetCC = SetCC.getOperand(0);
23107 switch (SetCC.getOpcode()) {
23108 case X86ISD::SETCC_CARRY:
23109 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
23110 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
23111 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
23112 // truncated to i1 using 'and'.
23113 if (checkAgainstTrue && !truncatedToBoolWithAnd)
23115 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
23116 "Invalid use of SETCC_CARRY!");
23118 case X86ISD::SETCC:
23119 // Set the condition code or opposite one if necessary.
23120 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
23121 if (needOppositeCond)
23122 CC = X86::GetOppositeBranchCondition(CC);
23123 return SetCC.getOperand(1);
23124 case X86ISD::CMOV: {
23125 // Check whether false/true value has canonical one, i.e. 0 or 1.
23126 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
23127 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
23128 // Quit if true value is not a constant.
23131 // Quit if false value is not a constant.
23133 SDValue Op = SetCC.getOperand(0);
23134 // Skip 'zext' or 'trunc' node.
23135 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
23136 Op.getOpcode() == ISD::TRUNCATE)
23137 Op = Op.getOperand(0);
23138 // A special case for rdrand/rdseed, where 0 is set if false cond is
23140 if ((Op.getOpcode() != X86ISD::RDRAND &&
23141 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
23144 // Quit if false value is not the constant 0 or 1.
23145 bool FValIsFalse = true;
23146 if (FVal && FVal->getZExtValue() != 0) {
23147 if (FVal->getZExtValue() != 1)
23149 // If FVal is 1, opposite cond is needed.
23150 needOppositeCond = !needOppositeCond;
23151 FValIsFalse = false;
23153 // Quit if TVal is not the constant opposite of FVal.
23154 if (FValIsFalse && TVal->getZExtValue() != 1)
23156 if (!FValIsFalse && TVal->getZExtValue() != 0)
23158 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
23159 if (needOppositeCond)
23160 CC = X86::GetOppositeBranchCondition(CC);
23161 return SetCC.getOperand(3);
23168 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
23170 /// (X86or (X86setcc) (X86setcc))
23171 /// (X86cmp (and (X86setcc) (X86setcc)), 0)
23172 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
23173 X86::CondCode &CC1, SDValue &Flags,
23175 if (Cond->getOpcode() == X86ISD::CMP) {
23176 ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
23177 if (!CondOp1C || !CondOp1C->isNullValue())
23180 Cond = Cond->getOperand(0);
23185 SDValue SetCC0, SetCC1;
23186 switch (Cond->getOpcode()) {
23187 default: return false;
23194 SetCC0 = Cond->getOperand(0);
23195 SetCC1 = Cond->getOperand(1);
23199 // Make sure we have SETCC nodes, using the same flags value.
23200 if (SetCC0.getOpcode() != X86ISD::SETCC ||
23201 SetCC1.getOpcode() != X86ISD::SETCC ||
23202 SetCC0->getOperand(1) != SetCC1->getOperand(1))
23205 CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
23206 CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
23207 Flags = SetCC0->getOperand(1);
23211 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
23212 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
23213 TargetLowering::DAGCombinerInfo &DCI,
23214 const X86Subtarget *Subtarget) {
23217 // If the flag operand isn't dead, don't touch this CMOV.
23218 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
23221 SDValue FalseOp = N->getOperand(0);
23222 SDValue TrueOp = N->getOperand(1);
23223 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
23224 SDValue Cond = N->getOperand(3);
23226 if (CC == X86::COND_E || CC == X86::COND_NE) {
23227 switch (Cond.getOpcode()) {
23231 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
23232 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
23233 return (CC == X86::COND_E) ? FalseOp : TrueOp;
23239 Flags = checkBoolTestSetCCCombine(Cond, CC);
23240 if (Flags.getNode() &&
23241 // Extra check as FCMOV only supports a subset of X86 cond.
23242 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
23243 SDValue Ops[] = { FalseOp, TrueOp,
23244 DAG.getConstant(CC, DL, MVT::i8), Flags };
23245 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23248 // If this is a select between two integer constants, try to do some
23249 // optimizations. Note that the operands are ordered the opposite of SELECT
23251 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
23252 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
23253 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
23254 // larger than FalseC (the false value).
23255 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
23256 CC = X86::GetOppositeBranchCondition(CC);
23257 std::swap(TrueC, FalseC);
23258 std::swap(TrueOp, FalseOp);
23261 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
23262 // This is efficient for any integer data type (including i8/i16) and
23264 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
23265 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23266 DAG.getConstant(CC, DL, MVT::i8), Cond);
23268 // Zero extend the condition if needed.
23269 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
23271 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23272 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
23273 DAG.getConstant(ShAmt, DL, MVT::i8));
23274 if (N->getNumValues() == 2) // Dead flag value?
23275 return DCI.CombineTo(N, Cond, SDValue());
23279 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
23280 // for any integer data type, including i8/i16.
23281 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23282 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23283 DAG.getConstant(CC, DL, MVT::i8), Cond);
23285 // Zero extend the condition if needed.
23286 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23287 FalseC->getValueType(0), Cond);
23288 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23289 SDValue(FalseC, 0));
23291 if (N->getNumValues() == 2) // Dead flag value?
23292 return DCI.CombineTo(N, Cond, SDValue());
23296 // Optimize cases that will turn into an LEA instruction. This requires
23297 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23298 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23299 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23300 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23302 bool isFastMultiplier = false;
23304 switch ((unsigned char)Diff) {
23306 case 1: // result = add base, cond
23307 case 2: // result = lea base( , cond*2)
23308 case 3: // result = lea base(cond, cond*2)
23309 case 4: // result = lea base( , cond*4)
23310 case 5: // result = lea base(cond, cond*4)
23311 case 8: // result = lea base( , cond*8)
23312 case 9: // result = lea base(cond, cond*8)
23313 isFastMultiplier = true;
23318 if (isFastMultiplier) {
23319 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23320 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23321 DAG.getConstant(CC, DL, MVT::i8), Cond);
23322 // Zero extend the condition if needed.
23323 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23325 // Scale the condition by the difference.
23327 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23328 DAG.getConstant(Diff, DL, Cond.getValueType()));
23330 // Add the base if non-zero.
23331 if (FalseC->getAPIntValue() != 0)
23332 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23333 SDValue(FalseC, 0));
23334 if (N->getNumValues() == 2) // Dead flag value?
23335 return DCI.CombineTo(N, Cond, SDValue());
23342 // Handle these cases:
23343 // (select (x != c), e, c) -> select (x != c), e, x),
23344 // (select (x == c), c, e) -> select (x == c), x, e)
23345 // where the c is an integer constant, and the "select" is the combination
23346 // of CMOV and CMP.
23348 // The rationale for this change is that the conditional-move from a constant
23349 // needs two instructions, however, conditional-move from a register needs
23350 // only one instruction.
23352 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
23353 // some instruction-combining opportunities. This opt needs to be
23354 // postponed as late as possible.
23356 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
23357 // the DCI.xxxx conditions are provided to postpone the optimization as
23358 // late as possible.
23360 ConstantSDNode *CmpAgainst = nullptr;
23361 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
23362 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
23363 !isa<ConstantSDNode>(Cond.getOperand(0))) {
23365 if (CC == X86::COND_NE &&
23366 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
23367 CC = X86::GetOppositeBranchCondition(CC);
23368 std::swap(TrueOp, FalseOp);
23371 if (CC == X86::COND_E &&
23372 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
23373 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
23374 DAG.getConstant(CC, DL, MVT::i8), Cond };
23375 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
23380 // Fold and/or of setcc's to double CMOV:
23381 // (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
23382 // (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
23384 // This combine lets us generate:
23385 // cmovcc1 (jcc1 if we don't have CMOV)
23391 // cmovne (jne if we don't have CMOV)
23392 // When we can't use the CMOV instruction, it might increase branch
23394 // When we can use CMOV, or when there is no mispredict, this improves
23395 // throughput and reduces register pressure.
23397 if (CC == X86::COND_NE) {
23399 X86::CondCode CC0, CC1;
23401 if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
23403 std::swap(FalseOp, TrueOp);
23404 CC0 = X86::GetOppositeBranchCondition(CC0);
23405 CC1 = X86::GetOppositeBranchCondition(CC1);
23408 SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
23410 SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
23411 SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
23412 SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23413 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
23421 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
23422 const X86Subtarget *Subtarget) {
23423 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
23425 default: return SDValue();
23426 // SSE/AVX/AVX2 blend intrinsics.
23427 case Intrinsic::x86_avx2_pblendvb:
23428 // Don't try to simplify this intrinsic if we don't have AVX2.
23429 if (!Subtarget->hasAVX2())
23432 case Intrinsic::x86_avx_blendv_pd_256:
23433 case Intrinsic::x86_avx_blendv_ps_256:
23434 // Don't try to simplify this intrinsic if we don't have AVX.
23435 if (!Subtarget->hasAVX())
23438 case Intrinsic::x86_sse41_blendvps:
23439 case Intrinsic::x86_sse41_blendvpd:
23440 case Intrinsic::x86_sse41_pblendvb: {
23441 SDValue Op0 = N->getOperand(1);
23442 SDValue Op1 = N->getOperand(2);
23443 SDValue Mask = N->getOperand(3);
23445 // Don't try to simplify this intrinsic if we don't have SSE4.1.
23446 if (!Subtarget->hasSSE41())
23449 // fold (blend A, A, Mask) -> A
23452 // fold (blend A, B, allZeros) -> A
23453 if (ISD::isBuildVectorAllZeros(Mask.getNode()))
23455 // fold (blend A, B, allOnes) -> B
23456 if (ISD::isBuildVectorAllOnes(Mask.getNode()))
23459 // Simplify the case where the mask is a constant i32 value.
23460 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
23461 if (C->isNullValue())
23463 if (C->isAllOnesValue())
23470 // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
23471 case Intrinsic::x86_sse2_psrai_w:
23472 case Intrinsic::x86_sse2_psrai_d:
23473 case Intrinsic::x86_avx2_psrai_w:
23474 case Intrinsic::x86_avx2_psrai_d:
23475 case Intrinsic::x86_sse2_psra_w:
23476 case Intrinsic::x86_sse2_psra_d:
23477 case Intrinsic::x86_avx2_psra_w:
23478 case Intrinsic::x86_avx2_psra_d: {
23479 SDValue Op0 = N->getOperand(1);
23480 SDValue Op1 = N->getOperand(2);
23481 EVT VT = Op0.getValueType();
23482 assert(VT.isVector() && "Expected a vector type!");
23484 if (isa<BuildVectorSDNode>(Op1))
23485 Op1 = Op1.getOperand(0);
23487 if (!isa<ConstantSDNode>(Op1))
23490 EVT SVT = VT.getVectorElementType();
23491 unsigned SVTBits = SVT.getSizeInBits();
23493 ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
23494 const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
23495 uint64_t ShAmt = C.getZExtValue();
23497 // Don't try to convert this shift into a ISD::SRA if the shift
23498 // count is bigger than or equal to the element size.
23499 if (ShAmt >= SVTBits)
23502 // Trivial case: if the shift count is zero, then fold this
23503 // into the first operand.
23507 // Replace this packed shift intrinsic with a target independent
23510 SDValue Splat = DAG.getConstant(C, DL, VT);
23511 return DAG.getNode(ISD::SRA, DL, VT, Op0, Splat);
23516 /// PerformMulCombine - Optimize a single multiply with constant into two
23517 /// in order to implement it with two cheaper instructions, e.g.
23518 /// LEA + SHL, LEA + LEA.
23519 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
23520 TargetLowering::DAGCombinerInfo &DCI) {
23521 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
23524 EVT VT = N->getValueType(0);
23525 if (VT != MVT::i64 && VT != MVT::i32)
23528 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
23531 uint64_t MulAmt = C->getZExtValue();
23532 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
23535 uint64_t MulAmt1 = 0;
23536 uint64_t MulAmt2 = 0;
23537 if ((MulAmt % 9) == 0) {
23539 MulAmt2 = MulAmt / 9;
23540 } else if ((MulAmt % 5) == 0) {
23542 MulAmt2 = MulAmt / 5;
23543 } else if ((MulAmt % 3) == 0) {
23545 MulAmt2 = MulAmt / 3;
23548 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
23551 if (isPowerOf2_64(MulAmt2) &&
23552 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
23553 // If second multiplifer is pow2, issue it first. We want the multiply by
23554 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
23556 std::swap(MulAmt1, MulAmt2);
23559 if (isPowerOf2_64(MulAmt1))
23560 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
23561 DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
23563 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
23564 DAG.getConstant(MulAmt1, DL, VT));
23566 if (isPowerOf2_64(MulAmt2))
23567 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
23568 DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
23570 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
23571 DAG.getConstant(MulAmt2, DL, VT));
23573 // Do not add new nodes to DAG combiner worklist.
23574 DCI.CombineTo(N, NewMul, false);
23579 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
23580 SDValue N0 = N->getOperand(0);
23581 SDValue N1 = N->getOperand(1);
23582 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
23583 EVT VT = N0.getValueType();
23585 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
23586 // since the result of setcc_c is all zero's or all ones.
23587 if (VT.isInteger() && !VT.isVector() &&
23588 N1C && N0.getOpcode() == ISD::AND &&
23589 N0.getOperand(1).getOpcode() == ISD::Constant) {
23590 SDValue N00 = N0.getOperand(0);
23591 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
23592 ((N00.getOpcode() == ISD::ANY_EXTEND ||
23593 N00.getOpcode() == ISD::ZERO_EXTEND) &&
23594 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
23595 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
23596 APInt ShAmt = N1C->getAPIntValue();
23597 Mask = Mask.shl(ShAmt);
23600 return DAG.getNode(ISD::AND, DL, VT,
23601 N00, DAG.getConstant(Mask, DL, VT));
23606 // Hardware support for vector shifts is sparse which makes us scalarize the
23607 // vector operations in many cases. Also, on sandybridge ADD is faster than
23609 // (shl V, 1) -> add V,V
23610 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
23611 if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
23612 assert(N0.getValueType().isVector() && "Invalid vector shift type");
23613 // We shift all of the values by one. In many cases we do not have
23614 // hardware support for this operation. This is better expressed as an ADD
23616 if (N1SplatC->getAPIntValue() == 1)
23617 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
23623 /// \brief Returns a vector of 0s if the node in input is a vector logical
23624 /// shift by a constant amount which is known to be bigger than or equal
23625 /// to the vector element size in bits.
23626 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
23627 const X86Subtarget *Subtarget) {
23628 EVT VT = N->getValueType(0);
23630 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
23631 (!Subtarget->hasInt256() ||
23632 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
23635 SDValue Amt = N->getOperand(1);
23637 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
23638 if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
23639 APInt ShiftAmt = AmtSplat->getAPIntValue();
23640 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
23642 // SSE2/AVX2 logical shifts always return a vector of 0s
23643 // if the shift amount is bigger than or equal to
23644 // the element size. The constant shift amount will be
23645 // encoded as a 8-bit immediate.
23646 if (ShiftAmt.trunc(8).uge(MaxAmount))
23647 return getZeroVector(VT, Subtarget, DAG, DL);
23653 /// PerformShiftCombine - Combine shifts.
23654 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
23655 TargetLowering::DAGCombinerInfo &DCI,
23656 const X86Subtarget *Subtarget) {
23657 if (N->getOpcode() == ISD::SHL)
23658 if (SDValue V = PerformSHLCombine(N, DAG))
23661 // Try to fold this logical shift into a zero vector.
23662 if (N->getOpcode() != ISD::SRA)
23663 if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
23669 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
23670 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
23671 // and friends. Likewise for OR -> CMPNEQSS.
23672 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
23673 TargetLowering::DAGCombinerInfo &DCI,
23674 const X86Subtarget *Subtarget) {
23677 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
23678 // we're requiring SSE2 for both.
23679 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
23680 SDValue N0 = N->getOperand(0);
23681 SDValue N1 = N->getOperand(1);
23682 SDValue CMP0 = N0->getOperand(1);
23683 SDValue CMP1 = N1->getOperand(1);
23686 // The SETCCs should both refer to the same CMP.
23687 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
23690 SDValue CMP00 = CMP0->getOperand(0);
23691 SDValue CMP01 = CMP0->getOperand(1);
23692 EVT VT = CMP00.getValueType();
23694 if (VT == MVT::f32 || VT == MVT::f64) {
23695 bool ExpectingFlags = false;
23696 // Check for any users that want flags:
23697 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
23698 !ExpectingFlags && UI != UE; ++UI)
23699 switch (UI->getOpcode()) {
23704 ExpectingFlags = true;
23706 case ISD::CopyToReg:
23707 case ISD::SIGN_EXTEND:
23708 case ISD::ZERO_EXTEND:
23709 case ISD::ANY_EXTEND:
23713 if (!ExpectingFlags) {
23714 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
23715 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
23717 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
23718 X86::CondCode tmp = cc0;
23723 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
23724 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
23725 // FIXME: need symbolic constants for these magic numbers.
23726 // See X86ATTInstPrinter.cpp:printSSECC().
23727 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
23728 if (Subtarget->hasAVX512()) {
23729 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
23731 DAG.getConstant(x86cc, DL, MVT::i8));
23732 if (N->getValueType(0) != MVT::i1)
23733 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
23737 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
23738 CMP00.getValueType(), CMP00, CMP01,
23739 DAG.getConstant(x86cc, DL,
23742 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
23743 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
23745 if (is64BitFP && !Subtarget->is64Bit()) {
23746 // On a 32-bit target, we cannot bitcast the 64-bit float to a
23747 // 64-bit integer, since that's not a legal type. Since
23748 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
23749 // bits, but can do this little dance to extract the lowest 32 bits
23750 // and work with those going forward.
23751 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
23753 SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
23754 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
23755 Vector32, DAG.getIntPtrConstant(0, DL));
23759 SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
23760 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
23761 DAG.getConstant(1, DL, IntVT));
23762 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
23764 return OneBitOfTruth;
23772 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
23773 /// so it can be folded inside ANDNP.
23774 static bool CanFoldXORWithAllOnes(const SDNode *N) {
23775 EVT VT = N->getValueType(0);
23777 // Match direct AllOnes for 128 and 256-bit vectors
23778 if (ISD::isBuildVectorAllOnes(N))
23781 // Look through a bit convert.
23782 if (N->getOpcode() == ISD::BITCAST)
23783 N = N->getOperand(0).getNode();
23785 // Sometimes the operand may come from a insert_subvector building a 256-bit
23787 if (VT.is256BitVector() &&
23788 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
23789 SDValue V1 = N->getOperand(0);
23790 SDValue V2 = N->getOperand(1);
23792 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
23793 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
23794 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
23795 ISD::isBuildVectorAllOnes(V2.getNode()))
23802 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
23803 // register. In most cases we actually compare or select YMM-sized registers
23804 // and mixing the two types creates horrible code. This method optimizes
23805 // some of the transition sequences.
23806 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
23807 TargetLowering::DAGCombinerInfo &DCI,
23808 const X86Subtarget *Subtarget) {
23809 EVT VT = N->getValueType(0);
23810 if (!VT.is256BitVector())
23813 assert((N->getOpcode() == ISD::ANY_EXTEND ||
23814 N->getOpcode() == ISD::ZERO_EXTEND ||
23815 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
23817 SDValue Narrow = N->getOperand(0);
23818 EVT NarrowVT = Narrow->getValueType(0);
23819 if (!NarrowVT.is128BitVector())
23822 if (Narrow->getOpcode() != ISD::XOR &&
23823 Narrow->getOpcode() != ISD::AND &&
23824 Narrow->getOpcode() != ISD::OR)
23827 SDValue N0 = Narrow->getOperand(0);
23828 SDValue N1 = Narrow->getOperand(1);
23831 // The Left side has to be a trunc.
23832 if (N0.getOpcode() != ISD::TRUNCATE)
23835 // The type of the truncated inputs.
23836 EVT WideVT = N0->getOperand(0)->getValueType(0);
23840 // The right side has to be a 'trunc' or a constant vector.
23841 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
23842 ConstantSDNode *RHSConstSplat = nullptr;
23843 if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
23844 RHSConstSplat = RHSBV->getConstantSplatNode();
23845 if (!RHSTrunc && !RHSConstSplat)
23848 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23850 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
23853 // Set N0 and N1 to hold the inputs to the new wide operation.
23854 N0 = N0->getOperand(0);
23855 if (RHSConstSplat) {
23856 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
23857 SDValue(RHSConstSplat, 0));
23858 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
23859 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
23860 } else if (RHSTrunc) {
23861 N1 = N1->getOperand(0);
23864 // Generate the wide operation.
23865 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
23866 unsigned Opcode = N->getOpcode();
23868 case ISD::ANY_EXTEND:
23870 case ISD::ZERO_EXTEND: {
23871 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
23872 APInt Mask = APInt::getAllOnesValue(InBits);
23873 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
23874 return DAG.getNode(ISD::AND, DL, VT,
23875 Op, DAG.getConstant(Mask, DL, VT));
23877 case ISD::SIGN_EXTEND:
23878 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
23879 Op, DAG.getValueType(NarrowVT));
23881 llvm_unreachable("Unexpected opcode");
23885 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
23886 TargetLowering::DAGCombinerInfo &DCI,
23887 const X86Subtarget *Subtarget) {
23888 SDValue N0 = N->getOperand(0);
23889 SDValue N1 = N->getOperand(1);
23892 // A vector zext_in_reg may be represented as a shuffle,
23893 // feeding into a bitcast (this represents anyext) feeding into
23894 // an and with a mask.
23895 // We'd like to try to combine that into a shuffle with zero
23896 // plus a bitcast, removing the and.
23897 if (N0.getOpcode() != ISD::BITCAST ||
23898 N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
23901 // The other side of the AND should be a splat of 2^C, where C
23902 // is the number of bits in the source type.
23903 if (N1.getOpcode() == ISD::BITCAST)
23904 N1 = N1.getOperand(0);
23905 if (N1.getOpcode() != ISD::BUILD_VECTOR)
23907 BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
23909 ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
23910 EVT SrcType = Shuffle->getValueType(0);
23912 // We expect a single-source shuffle
23913 if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
23916 unsigned SrcSize = SrcType.getScalarSizeInBits();
23918 APInt SplatValue, SplatUndef;
23919 unsigned SplatBitSize;
23921 if (!Vector->isConstantSplat(SplatValue, SplatUndef,
23922 SplatBitSize, HasAnyUndefs))
23925 unsigned ResSize = N1.getValueType().getScalarSizeInBits();
23926 // Make sure the splat matches the mask we expect
23927 if (SplatBitSize > ResSize ||
23928 (SplatValue + 1).exactLogBase2() != (int)SrcSize)
23931 // Make sure the input and output size make sense
23932 if (SrcSize >= ResSize || ResSize % SrcSize)
23935 // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
23936 // The number of u's between each two values depends on the ratio between
23937 // the source and dest type.
23938 unsigned ZextRatio = ResSize / SrcSize;
23939 bool IsZext = true;
23940 for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
23941 if (i % ZextRatio) {
23942 if (Shuffle->getMaskElt(i) > 0) {
23948 if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
23949 // Expected element number
23959 // Ok, perform the transformation - replace the shuffle with
23960 // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
23961 // (instead of undef) where the k elements come from the zero vector.
23962 SmallVector<int, 8> Mask;
23963 unsigned NumElems = SrcType.getVectorNumElements();
23964 for (unsigned i = 0; i < NumElems; ++i)
23966 Mask.push_back(NumElems);
23968 Mask.push_back(i / ZextRatio);
23970 SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
23971 Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
23972 return DAG.getBitcast(N0.getValueType(), NewShuffle);
23975 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
23976 TargetLowering::DAGCombinerInfo &DCI,
23977 const X86Subtarget *Subtarget) {
23978 if (DCI.isBeforeLegalizeOps())
23981 if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
23984 if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
23987 EVT VT = N->getValueType(0);
23988 SDValue N0 = N->getOperand(0);
23989 SDValue N1 = N->getOperand(1);
23992 // Create BEXTR instructions
23993 // BEXTR is ((X >> imm) & (2**size-1))
23994 if (VT == MVT::i32 || VT == MVT::i64) {
23995 // Check for BEXTR.
23996 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
23997 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
23998 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
23999 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
24000 if (MaskNode && ShiftNode) {
24001 uint64_t Mask = MaskNode->getZExtValue();
24002 uint64_t Shift = ShiftNode->getZExtValue();
24003 if (isMask_64(Mask)) {
24004 uint64_t MaskSize = countPopulation(Mask);
24005 if (Shift + MaskSize <= VT.getSizeInBits())
24006 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
24007 DAG.getConstant(Shift | (MaskSize << 8), DL,
24016 // Want to form ANDNP nodes:
24017 // 1) In the hopes of then easily combining them with OR and AND nodes
24018 // to form PBLEND/PSIGN.
24019 // 2) To match ANDN packed intrinsics
24020 if (VT != MVT::v2i64 && VT != MVT::v4i64)
24023 // Check LHS for vnot
24024 if (N0.getOpcode() == ISD::XOR &&
24025 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
24026 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
24027 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
24029 // Check RHS for vnot
24030 if (N1.getOpcode() == ISD::XOR &&
24031 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
24032 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
24033 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
24038 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
24039 TargetLowering::DAGCombinerInfo &DCI,
24040 const X86Subtarget *Subtarget) {
24041 if (DCI.isBeforeLegalizeOps())
24044 if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
24047 SDValue N0 = N->getOperand(0);
24048 SDValue N1 = N->getOperand(1);
24049 EVT VT = N->getValueType(0);
24051 // look for psign/blend
24052 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
24053 if (!Subtarget->hasSSSE3() ||
24054 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
24057 // Canonicalize pandn to RHS
24058 if (N0.getOpcode() == X86ISD::ANDNP)
24060 // or (and (m, y), (pandn m, x))
24061 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
24062 SDValue Mask = N1.getOperand(0);
24063 SDValue X = N1.getOperand(1);
24065 if (N0.getOperand(0) == Mask)
24066 Y = N0.getOperand(1);
24067 if (N0.getOperand(1) == Mask)
24068 Y = N0.getOperand(0);
24070 // Check to see if the mask appeared in both the AND and ANDNP and
24074 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
24075 // Look through mask bitcast.
24076 if (Mask.getOpcode() == ISD::BITCAST)
24077 Mask = Mask.getOperand(0);
24078 if (X.getOpcode() == ISD::BITCAST)
24079 X = X.getOperand(0);
24080 if (Y.getOpcode() == ISD::BITCAST)
24081 Y = Y.getOperand(0);
24083 EVT MaskVT = Mask.getValueType();
24085 // Validate that the Mask operand is a vector sra node.
24086 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
24087 // there is no psrai.b
24088 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
24089 unsigned SraAmt = ~0;
24090 if (Mask.getOpcode() == ISD::SRA) {
24091 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
24092 if (auto *AmtConst = AmtBV->getConstantSplatNode())
24093 SraAmt = AmtConst->getZExtValue();
24094 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
24095 SDValue SraC = Mask.getOperand(1);
24096 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
24098 if ((SraAmt + 1) != EltBits)
24103 // Now we know we at least have a plendvb with the mask val. See if
24104 // we can form a psignb/w/d.
24105 // psign = x.type == y.type == mask.type && y = sub(0, x);
24106 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
24107 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
24108 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
24109 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
24110 "Unsupported VT for PSIGN");
24111 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
24112 return DAG.getBitcast(VT, Mask);
24114 // PBLENDVB only available on SSE 4.1
24115 if (!Subtarget->hasSSE41())
24118 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
24120 X = DAG.getBitcast(BlendVT, X);
24121 Y = DAG.getBitcast(BlendVT, Y);
24122 Mask = DAG.getBitcast(BlendVT, Mask);
24123 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
24124 return DAG.getBitcast(VT, Mask);
24128 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
24131 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
24132 MachineFunction &MF = DAG.getMachineFunction();
24133 // FIXME: Use Function::optForSize().
24135 MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
24137 // SHLD/SHRD instructions have lower register pressure, but on some
24138 // platforms they have higher latency than the equivalent
24139 // series of shifts/or that would otherwise be generated.
24140 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
24141 // have higher latencies and we are not optimizing for size.
24142 if (!OptForSize && Subtarget->isSHLDSlow())
24145 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
24147 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
24149 if (!N0.hasOneUse() || !N1.hasOneUse())
24152 SDValue ShAmt0 = N0.getOperand(1);
24153 if (ShAmt0.getValueType() != MVT::i8)
24155 SDValue ShAmt1 = N1.getOperand(1);
24156 if (ShAmt1.getValueType() != MVT::i8)
24158 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
24159 ShAmt0 = ShAmt0.getOperand(0);
24160 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
24161 ShAmt1 = ShAmt1.getOperand(0);
24164 unsigned Opc = X86ISD::SHLD;
24165 SDValue Op0 = N0.getOperand(0);
24166 SDValue Op1 = N1.getOperand(0);
24167 if (ShAmt0.getOpcode() == ISD::SUB) {
24168 Opc = X86ISD::SHRD;
24169 std::swap(Op0, Op1);
24170 std::swap(ShAmt0, ShAmt1);
24173 unsigned Bits = VT.getSizeInBits();
24174 if (ShAmt1.getOpcode() == ISD::SUB) {
24175 SDValue Sum = ShAmt1.getOperand(0);
24176 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
24177 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
24178 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
24179 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
24180 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
24181 return DAG.getNode(Opc, DL, VT,
24183 DAG.getNode(ISD::TRUNCATE, DL,
24186 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
24187 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
24189 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
24190 return DAG.getNode(Opc, DL, VT,
24191 N0.getOperand(0), N1.getOperand(0),
24192 DAG.getNode(ISD::TRUNCATE, DL,
24199 // Generate NEG and CMOV for integer abs.
24200 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
24201 EVT VT = N->getValueType(0);
24203 // Since X86 does not have CMOV for 8-bit integer, we don't convert
24204 // 8-bit integer abs to NEG and CMOV.
24205 if (VT.isInteger() && VT.getSizeInBits() == 8)
24208 SDValue N0 = N->getOperand(0);
24209 SDValue N1 = N->getOperand(1);
24212 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
24213 // and change it to SUB and CMOV.
24214 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
24215 N0.getOpcode() == ISD::ADD &&
24216 N0.getOperand(1) == N1 &&
24217 N1.getOpcode() == ISD::SRA &&
24218 N1.getOperand(0) == N0.getOperand(0))
24219 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
24220 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
24221 // Generate SUB & CMOV.
24222 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
24223 DAG.getConstant(0, DL, VT), N0.getOperand(0));
24225 SDValue Ops[] = { N0.getOperand(0), Neg,
24226 DAG.getConstant(X86::COND_GE, DL, MVT::i8),
24227 SDValue(Neg.getNode(), 1) };
24228 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
24233 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
24234 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
24235 TargetLowering::DAGCombinerInfo &DCI,
24236 const X86Subtarget *Subtarget) {
24237 if (DCI.isBeforeLegalizeOps())
24240 if (Subtarget->hasCMov())
24241 if (SDValue RV = performIntegerAbsCombine(N, DAG))
24247 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
24248 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
24249 TargetLowering::DAGCombinerInfo &DCI,
24250 const X86Subtarget *Subtarget) {
24251 LoadSDNode *Ld = cast<LoadSDNode>(N);
24252 EVT RegVT = Ld->getValueType(0);
24253 EVT MemVT = Ld->getMemoryVT();
24255 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24257 // For chips with slow 32-byte unaligned loads, break the 32-byte operation
24258 // into two 16-byte operations.
24259 ISD::LoadExtType Ext = Ld->getExtensionType();
24260 unsigned Alignment = Ld->getAlignment();
24261 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
24262 if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
24263 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
24264 unsigned NumElems = RegVT.getVectorNumElements();
24268 SDValue Ptr = Ld->getBasePtr();
24269 SDValue Increment =
24270 DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24272 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
24274 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24275 Ld->getPointerInfo(), Ld->isVolatile(),
24276 Ld->isNonTemporal(), Ld->isInvariant(),
24278 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24279 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24280 Ld->getPointerInfo(), Ld->isVolatile(),
24281 Ld->isNonTemporal(), Ld->isInvariant(),
24282 std::min(16U, Alignment));
24283 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
24285 Load2.getValue(1));
24287 SDValue NewVec = DAG.getUNDEF(RegVT);
24288 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
24289 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
24290 return DCI.CombineTo(N, NewVec, TF, true);
24296 /// PerformMLOADCombine - Resolve extending loads
24297 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
24298 TargetLowering::DAGCombinerInfo &DCI,
24299 const X86Subtarget *Subtarget) {
24300 MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
24301 if (Mld->getExtensionType() != ISD::SEXTLOAD)
24304 EVT VT = Mld->getValueType(0);
24305 unsigned NumElems = VT.getVectorNumElements();
24306 EVT LdVT = Mld->getMemoryVT();
24309 assert(LdVT != VT && "Cannot extend to the same type");
24310 unsigned ToSz = VT.getVectorElementType().getSizeInBits();
24311 unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
24312 // From, To sizes and ElemCount must be pow of two
24313 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24314 "Unexpected size for extending masked load");
24316 unsigned SizeRatio = ToSz / FromSz;
24317 assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
24319 // Create a type on which we perform the shuffle
24320 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24321 LdVT.getScalarType(), NumElems*SizeRatio);
24322 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24324 // Convert Src0 value
24325 SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
24326 if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
24327 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24328 for (unsigned i = 0; i != NumElems; ++i)
24329 ShuffleVec[i] = i * SizeRatio;
24331 // Can't shuffle using an illegal type.
24332 assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24333 && "WideVecVT should be legal");
24334 WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
24335 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
24337 // Prepare the new mask
24339 SDValue Mask = Mld->getMask();
24340 if (Mask.getValueType() == VT) {
24341 // Mask and original value have the same type
24342 NewMask = DAG.getBitcast(WideVecVT, Mask);
24343 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24344 for (unsigned i = 0; i != NumElems; ++i)
24345 ShuffleVec[i] = i * SizeRatio;
24346 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24347 ShuffleVec[i] = NumElems*SizeRatio;
24348 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24349 DAG.getConstant(0, dl, WideVecVT),
24353 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24354 unsigned WidenNumElts = NumElems*SizeRatio;
24355 unsigned MaskNumElts = VT.getVectorNumElements();
24356 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
24359 unsigned NumConcat = WidenNumElts / MaskNumElts;
24360 SmallVector<SDValue, 16> Ops(NumConcat);
24361 SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24363 for (unsigned i = 1; i != NumConcat; ++i)
24366 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24369 SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
24370 Mld->getBasePtr(), NewMask, WideSrc0,
24371 Mld->getMemoryVT(), Mld->getMemOperand(),
24373 SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
24374 return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
24377 /// PerformMSTORECombine - Resolve truncating stores
24378 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
24379 const X86Subtarget *Subtarget) {
24380 MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
24381 if (!Mst->isTruncatingStore())
24384 EVT VT = Mst->getValue().getValueType();
24385 unsigned NumElems = VT.getVectorNumElements();
24386 EVT StVT = Mst->getMemoryVT();
24389 assert(StVT != VT && "Cannot truncate to the same type");
24390 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24391 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24393 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24395 // The truncating store is legal in some cases. For example
24396 // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
24397 // are designated for truncate store.
24398 // In this case we don't need any further transformations.
24399 if (TLI.isTruncStoreLegal(VT, StVT))
24402 // From, To sizes and ElemCount must be pow of two
24403 assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24404 "Unexpected size for truncating masked store");
24405 // We are going to use the original vector elt for storing.
24406 // Accumulated smaller vector elements must be a multiple of the store size.
24407 assert (((NumElems * FromSz) % ToSz) == 0 &&
24408 "Unexpected ratio for truncating masked store");
24410 unsigned SizeRatio = FromSz / ToSz;
24411 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24413 // Create a type on which we perform the shuffle
24414 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24415 StVT.getScalarType(), NumElems*SizeRatio);
24417 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24419 SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
24420 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24421 for (unsigned i = 0; i != NumElems; ++i)
24422 ShuffleVec[i] = i * SizeRatio;
24424 // Can't shuffle using an illegal type.
24425 assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24426 && "WideVecVT should be legal");
24428 SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24429 DAG.getUNDEF(WideVecVT),
24433 SDValue Mask = Mst->getMask();
24434 if (Mask.getValueType() == VT) {
24435 // Mask and original value have the same type
24436 NewMask = DAG.getBitcast(WideVecVT, Mask);
24437 for (unsigned i = 0; i != NumElems; ++i)
24438 ShuffleVec[i] = i * SizeRatio;
24439 for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24440 ShuffleVec[i] = NumElems*SizeRatio;
24441 NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24442 DAG.getConstant(0, dl, WideVecVT),
24446 assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24447 unsigned WidenNumElts = NumElems*SizeRatio;
24448 unsigned MaskNumElts = VT.getVectorNumElements();
24449 EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
24452 unsigned NumConcat = WidenNumElts / MaskNumElts;
24453 SmallVector<SDValue, 16> Ops(NumConcat);
24454 SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24456 for (unsigned i = 1; i != NumConcat; ++i)
24459 NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24462 return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
24463 NewMask, StVT, Mst->getMemOperand(), false);
24465 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
24466 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
24467 const X86Subtarget *Subtarget) {
24468 StoreSDNode *St = cast<StoreSDNode>(N);
24469 EVT VT = St->getValue().getValueType();
24470 EVT StVT = St->getMemoryVT();
24472 SDValue StoredVal = St->getOperand(1);
24473 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24475 // If we are saving a concatenation of two XMM registers and 32-byte stores
24476 // are slow, such as on Sandy Bridge, perform two 16-byte stores.
24477 unsigned Alignment = St->getAlignment();
24478 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
24479 if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
24480 StVT == VT && !IsAligned) {
24481 unsigned NumElems = VT.getVectorNumElements();
24485 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
24486 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
24489 DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24490 SDValue Ptr0 = St->getBasePtr();
24491 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
24493 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
24494 St->getPointerInfo(), St->isVolatile(),
24495 St->isNonTemporal(), Alignment);
24496 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
24497 St->getPointerInfo(), St->isVolatile(),
24498 St->isNonTemporal(),
24499 std::min(16U, Alignment));
24500 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
24503 // Optimize trunc store (of multiple scalars) to shuffle and store.
24504 // First, pack all of the elements in one place. Next, store to memory
24505 // in fewer chunks.
24506 if (St->isTruncatingStore() && VT.isVector()) {
24507 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24508 unsigned NumElems = VT.getVectorNumElements();
24509 assert(StVT != VT && "Cannot truncate to the same type");
24510 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24511 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24513 // The truncating store is legal in some cases. For example
24514 // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
24515 // are designated for truncate store.
24516 // In this case we don't need any further transformations.
24517 if (TLI.isTruncStoreLegal(VT, StVT))
24520 // From, To sizes and ElemCount must be pow of two
24521 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
24522 // We are going to use the original vector elt for storing.
24523 // Accumulated smaller vector elements must be a multiple of the store size.
24524 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
24526 unsigned SizeRatio = FromSz / ToSz;
24528 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24530 // Create a type on which we perform the shuffle
24531 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24532 StVT.getScalarType(), NumElems*SizeRatio);
24534 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24536 SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
24537 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
24538 for (unsigned i = 0; i != NumElems; ++i)
24539 ShuffleVec[i] = i * SizeRatio;
24541 // Can't shuffle using an illegal type.
24542 if (!TLI.isTypeLegal(WideVecVT))
24545 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24546 DAG.getUNDEF(WideVecVT),
24548 // At this point all of the data is stored at the bottom of the
24549 // register. We now need to save it to mem.
24551 // Find the largest store unit
24552 MVT StoreType = MVT::i8;
24553 for (MVT Tp : MVT::integer_valuetypes()) {
24554 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
24558 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
24559 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
24560 (64 <= NumElems * ToSz))
24561 StoreType = MVT::f64;
24563 // Bitcast the original vector into a vector of store-size units
24564 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
24565 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
24566 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
24567 SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
24568 SmallVector<SDValue, 8> Chains;
24569 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
24570 TLI.getPointerTy(DAG.getDataLayout()));
24571 SDValue Ptr = St->getBasePtr();
24573 // Perform one or more big stores into memory.
24574 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
24575 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
24576 StoreType, ShuffWide,
24577 DAG.getIntPtrConstant(i, dl));
24578 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
24579 St->getPointerInfo(), St->isVolatile(),
24580 St->isNonTemporal(), St->getAlignment());
24581 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24582 Chains.push_back(Ch);
24585 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
24588 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
24589 // the FP state in cases where an emms may be missing.
24590 // A preferable solution to the general problem is to figure out the right
24591 // places to insert EMMS. This qualifies as a quick hack.
24593 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
24594 if (VT.getSizeInBits() != 64)
24597 const Function *F = DAG.getMachineFunction().getFunction();
24598 bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
24600 !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
24601 if ((VT.isVector() ||
24602 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
24603 isa<LoadSDNode>(St->getValue()) &&
24604 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
24605 St->getChain().hasOneUse() && !St->isVolatile()) {
24606 SDNode* LdVal = St->getValue().getNode();
24607 LoadSDNode *Ld = nullptr;
24608 int TokenFactorIndex = -1;
24609 SmallVector<SDValue, 8> Ops;
24610 SDNode* ChainVal = St->getChain().getNode();
24611 // Must be a store of a load. We currently handle two cases: the load
24612 // is a direct child, and it's under an intervening TokenFactor. It is
24613 // possible to dig deeper under nested TokenFactors.
24614 if (ChainVal == LdVal)
24615 Ld = cast<LoadSDNode>(St->getChain());
24616 else if (St->getValue().hasOneUse() &&
24617 ChainVal->getOpcode() == ISD::TokenFactor) {
24618 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
24619 if (ChainVal->getOperand(i).getNode() == LdVal) {
24620 TokenFactorIndex = i;
24621 Ld = cast<LoadSDNode>(St->getValue());
24623 Ops.push_back(ChainVal->getOperand(i));
24627 if (!Ld || !ISD::isNormalLoad(Ld))
24630 // If this is not the MMX case, i.e. we are just turning i64 load/store
24631 // into f64 load/store, avoid the transformation if there are multiple
24632 // uses of the loaded value.
24633 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
24638 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
24639 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
24641 if (Subtarget->is64Bit() || F64IsLegal) {
24642 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
24643 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
24644 Ld->getPointerInfo(), Ld->isVolatile(),
24645 Ld->isNonTemporal(), Ld->isInvariant(),
24646 Ld->getAlignment());
24647 SDValue NewChain = NewLd.getValue(1);
24648 if (TokenFactorIndex != -1) {
24649 Ops.push_back(NewChain);
24650 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24652 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
24653 St->getPointerInfo(),
24654 St->isVolatile(), St->isNonTemporal(),
24655 St->getAlignment());
24658 // Otherwise, lower to two pairs of 32-bit loads / stores.
24659 SDValue LoAddr = Ld->getBasePtr();
24660 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
24661 DAG.getConstant(4, LdDL, MVT::i32));
24663 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
24664 Ld->getPointerInfo(),
24665 Ld->isVolatile(), Ld->isNonTemporal(),
24666 Ld->isInvariant(), Ld->getAlignment());
24667 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
24668 Ld->getPointerInfo().getWithOffset(4),
24669 Ld->isVolatile(), Ld->isNonTemporal(),
24671 MinAlign(Ld->getAlignment(), 4));
24673 SDValue NewChain = LoLd.getValue(1);
24674 if (TokenFactorIndex != -1) {
24675 Ops.push_back(LoLd);
24676 Ops.push_back(HiLd);
24677 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24680 LoAddr = St->getBasePtr();
24681 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
24682 DAG.getConstant(4, StDL, MVT::i32));
24684 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
24685 St->getPointerInfo(),
24686 St->isVolatile(), St->isNonTemporal(),
24687 St->getAlignment());
24688 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
24689 St->getPointerInfo().getWithOffset(4),
24691 St->isNonTemporal(),
24692 MinAlign(St->getAlignment(), 4));
24693 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
24696 // This is similar to the above case, but here we handle a scalar 64-bit
24697 // integer store that is extracted from a vector on a 32-bit target.
24698 // If we have SSE2, then we can treat it like a floating-point double
24699 // to get past legalization. The execution dependencies fixup pass will
24700 // choose the optimal machine instruction for the store if this really is
24701 // an integer or v2f32 rather than an f64.
24702 if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
24703 St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
24704 SDValue OldExtract = St->getOperand(1);
24705 SDValue ExtOp0 = OldExtract.getOperand(0);
24706 unsigned VecSize = ExtOp0.getValueSizeInBits();
24707 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
24708 SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
24709 SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
24710 BitCast, OldExtract.getOperand(1));
24711 return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
24712 St->getPointerInfo(), St->isVolatile(),
24713 St->isNonTemporal(), St->getAlignment());
24719 /// Return 'true' if this vector operation is "horizontal"
24720 /// and return the operands for the horizontal operation in LHS and RHS. A
24721 /// horizontal operation performs the binary operation on successive elements
24722 /// of its first operand, then on successive elements of its second operand,
24723 /// returning the resulting values in a vector. For example, if
24724 /// A = < float a0, float a1, float a2, float a3 >
24726 /// B = < float b0, float b1, float b2, float b3 >
24727 /// then the result of doing a horizontal operation on A and B is
24728 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
24729 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
24730 /// A horizontal-op B, for some already available A and B, and if so then LHS is
24731 /// set to A, RHS to B, and the routine returns 'true'.
24732 /// Note that the binary operation should have the property that if one of the
24733 /// operands is UNDEF then the result is UNDEF.
24734 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
24735 // Look for the following pattern: if
24736 // A = < float a0, float a1, float a2, float a3 >
24737 // B = < float b0, float b1, float b2, float b3 >
24739 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
24740 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
24741 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
24742 // which is A horizontal-op B.
24744 // At least one of the operands should be a vector shuffle.
24745 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
24746 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
24749 MVT VT = LHS.getSimpleValueType();
24751 assert((VT.is128BitVector() || VT.is256BitVector()) &&
24752 "Unsupported vector type for horizontal add/sub");
24754 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
24755 // operate independently on 128-bit lanes.
24756 unsigned NumElts = VT.getVectorNumElements();
24757 unsigned NumLanes = VT.getSizeInBits()/128;
24758 unsigned NumLaneElts = NumElts / NumLanes;
24759 assert((NumLaneElts % 2 == 0) &&
24760 "Vector type should have an even number of elements in each lane");
24761 unsigned HalfLaneElts = NumLaneElts/2;
24763 // View LHS in the form
24764 // LHS = VECTOR_SHUFFLE A, B, LMask
24765 // If LHS is not a shuffle then pretend it is the shuffle
24766 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
24767 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
24770 SmallVector<int, 16> LMask(NumElts);
24771 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24772 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
24773 A = LHS.getOperand(0);
24774 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
24775 B = LHS.getOperand(1);
24776 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
24777 std::copy(Mask.begin(), Mask.end(), LMask.begin());
24779 if (LHS.getOpcode() != ISD::UNDEF)
24781 for (unsigned i = 0; i != NumElts; ++i)
24785 // Likewise, view RHS in the form
24786 // RHS = VECTOR_SHUFFLE C, D, RMask
24788 SmallVector<int, 16> RMask(NumElts);
24789 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24790 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
24791 C = RHS.getOperand(0);
24792 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
24793 D = RHS.getOperand(1);
24794 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
24795 std::copy(Mask.begin(), Mask.end(), RMask.begin());
24797 if (RHS.getOpcode() != ISD::UNDEF)
24799 for (unsigned i = 0; i != NumElts; ++i)
24803 // Check that the shuffles are both shuffling the same vectors.
24804 if (!(A == C && B == D) && !(A == D && B == C))
24807 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
24808 if (!A.getNode() && !B.getNode())
24811 // If A and B occur in reverse order in RHS, then "swap" them (which means
24812 // rewriting the mask).
24814 ShuffleVectorSDNode::commuteMask(RMask);
24816 // At this point LHS and RHS are equivalent to
24817 // LHS = VECTOR_SHUFFLE A, B, LMask
24818 // RHS = VECTOR_SHUFFLE A, B, RMask
24819 // Check that the masks correspond to performing a horizontal operation.
24820 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
24821 for (unsigned i = 0; i != NumLaneElts; ++i) {
24822 int LIdx = LMask[i+l], RIdx = RMask[i+l];
24824 // Ignore any UNDEF components.
24825 if (LIdx < 0 || RIdx < 0 ||
24826 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
24827 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
24830 // Check that successive elements are being operated on. If not, this is
24831 // not a horizontal operation.
24832 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
24833 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
24834 if (!(LIdx == Index && RIdx == Index + 1) &&
24835 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
24840 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
24841 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
24845 /// Do target-specific dag combines on floating point adds.
24846 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
24847 const X86Subtarget *Subtarget) {
24848 EVT VT = N->getValueType(0);
24849 SDValue LHS = N->getOperand(0);
24850 SDValue RHS = N->getOperand(1);
24852 // Try to synthesize horizontal adds from adds of shuffles.
24853 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24854 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24855 isHorizontalBinOp(LHS, RHS, true))
24856 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
24860 /// Do target-specific dag combines on floating point subs.
24861 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
24862 const X86Subtarget *Subtarget) {
24863 EVT VT = N->getValueType(0);
24864 SDValue LHS = N->getOperand(0);
24865 SDValue RHS = N->getOperand(1);
24867 // Try to synthesize horizontal subs from subs of shuffles.
24868 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24869 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24870 isHorizontalBinOp(LHS, RHS, false))
24871 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
24875 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
24876 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
24877 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
24879 // F[X]OR(0.0, x) -> x
24880 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24881 if (C->getValueAPF().isPosZero())
24882 return N->getOperand(1);
24884 // F[X]OR(x, 0.0) -> x
24885 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24886 if (C->getValueAPF().isPosZero())
24887 return N->getOperand(0);
24891 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
24892 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
24893 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
24895 // Only perform optimizations if UnsafeMath is used.
24896 if (!DAG.getTarget().Options.UnsafeFPMath)
24899 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
24900 // into FMINC and FMAXC, which are Commutative operations.
24901 unsigned NewOp = 0;
24902 switch (N->getOpcode()) {
24903 default: llvm_unreachable("unknown opcode");
24904 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
24905 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
24908 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
24909 N->getOperand(0), N->getOperand(1));
24912 /// Do target-specific dag combines on X86ISD::FAND nodes.
24913 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
24914 // FAND(0.0, x) -> 0.0
24915 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24916 if (C->getValueAPF().isPosZero())
24917 return N->getOperand(0);
24919 // FAND(x, 0.0) -> 0.0
24920 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24921 if (C->getValueAPF().isPosZero())
24922 return N->getOperand(1);
24927 /// Do target-specific dag combines on X86ISD::FANDN nodes
24928 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
24929 // FANDN(0.0, x) -> x
24930 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24931 if (C->getValueAPF().isPosZero())
24932 return N->getOperand(1);
24934 // FANDN(x, 0.0) -> 0.0
24935 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24936 if (C->getValueAPF().isPosZero())
24937 return N->getOperand(1);
24942 static SDValue PerformBTCombine(SDNode *N,
24944 TargetLowering::DAGCombinerInfo &DCI) {
24945 // BT ignores high bits in the bit index operand.
24946 SDValue Op1 = N->getOperand(1);
24947 if (Op1.hasOneUse()) {
24948 unsigned BitWidth = Op1.getValueSizeInBits();
24949 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
24950 APInt KnownZero, KnownOne;
24951 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
24952 !DCI.isBeforeLegalizeOps());
24953 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24954 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
24955 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
24956 DCI.CommitTargetLoweringOpt(TLO);
24961 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
24962 SDValue Op = N->getOperand(0);
24963 if (Op.getOpcode() == ISD::BITCAST)
24964 Op = Op.getOperand(0);
24965 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
24966 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
24967 VT.getVectorElementType().getSizeInBits() ==
24968 OpVT.getVectorElementType().getSizeInBits()) {
24969 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
24974 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
24975 const X86Subtarget *Subtarget) {
24976 EVT VT = N->getValueType(0);
24977 if (!VT.isVector())
24980 SDValue N0 = N->getOperand(0);
24981 SDValue N1 = N->getOperand(1);
24982 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
24985 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
24986 // both SSE and AVX2 since there is no sign-extended shift right
24987 // operation on a vector with 64-bit elements.
24988 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
24989 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
24990 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
24991 N0.getOpcode() == ISD::SIGN_EXTEND)) {
24992 SDValue N00 = N0.getOperand(0);
24994 // EXTLOAD has a better solution on AVX2,
24995 // it may be replaced with X86ISD::VSEXT node.
24996 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
24997 if (!ISD::isNormalLoad(N00.getNode()))
25000 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
25001 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
25003 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
25009 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
25010 TargetLowering::DAGCombinerInfo &DCI,
25011 const X86Subtarget *Subtarget) {
25012 SDValue N0 = N->getOperand(0);
25013 EVT VT = N->getValueType(0);
25014 EVT SVT = VT.getScalarType();
25015 EVT InVT = N0.getValueType();
25016 EVT InSVT = InVT.getScalarType();
25019 // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
25020 // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
25021 // This exposes the sext to the sdivrem lowering, so that it directly extends
25022 // from AH (which we otherwise need to do contortions to access).
25023 if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
25024 InVT == MVT::i8 && VT == MVT::i32) {
25025 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25026 SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
25027 N0.getOperand(0), N0.getOperand(1));
25028 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25029 return R.getValue(1);
25032 if (!DCI.isBeforeLegalizeOps()) {
25033 if (InVT == MVT::i1) {
25034 SDValue Zero = DAG.getConstant(0, DL, VT);
25036 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
25037 return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
25042 if (VT.isVector() && Subtarget->hasSSE2()) {
25043 auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
25044 EVT InVT = N.getValueType();
25045 EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
25046 Size / InVT.getScalarSizeInBits());
25047 SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
25048 DAG.getUNDEF(InVT));
25050 return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
25053 // If target-size is less than 128-bits, extend to a type that would extend
25054 // to 128 bits, extend that and extract the original target vector.
25055 if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
25056 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25057 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25058 unsigned Scale = 128 / VT.getSizeInBits();
25060 EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
25061 SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
25062 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
25063 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
25064 DAG.getIntPtrConstant(0, DL));
25067 // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
25068 // which ensures lowering to X86ISD::VSEXT (pmovsx*).
25069 if (VT.getSizeInBits() == 128 &&
25070 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25071 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25072 SDValue ExOp = ExtendVecSize(DL, N0, 128);
25073 return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
25076 // On pre-AVX2 targets, split into 128-bit nodes of
25077 // ISD::SIGN_EXTEND_VECTOR_INREG.
25078 if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
25079 (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
25080 (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
25081 unsigned NumVecs = VT.getSizeInBits() / 128;
25082 unsigned NumSubElts = 128 / SVT.getSizeInBits();
25083 EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
25084 EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
25086 SmallVector<SDValue, 8> Opnds;
25087 for (unsigned i = 0, Offset = 0; i != NumVecs;
25088 ++i, Offset += NumSubElts) {
25089 SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
25090 DAG.getIntPtrConstant(Offset, DL));
25091 SrcVec = ExtendVecSize(DL, SrcVec, 128);
25092 SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
25093 Opnds.push_back(SrcVec);
25095 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
25099 if (!Subtarget->hasFp256())
25102 if (VT.isVector() && VT.getSizeInBits() == 256)
25103 if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
25109 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
25110 const X86Subtarget* Subtarget) {
25112 EVT VT = N->getValueType(0);
25114 // Let legalize expand this if it isn't a legal type yet.
25115 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
25118 EVT ScalarVT = VT.getScalarType();
25119 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
25120 (!Subtarget->hasFMA() && !Subtarget->hasFMA4() &&
25121 !Subtarget->hasAVX512()))
25124 SDValue A = N->getOperand(0);
25125 SDValue B = N->getOperand(1);
25126 SDValue C = N->getOperand(2);
25128 bool NegA = (A.getOpcode() == ISD::FNEG);
25129 bool NegB = (B.getOpcode() == ISD::FNEG);
25130 bool NegC = (C.getOpcode() == ISD::FNEG);
25132 // Negative multiplication when NegA xor NegB
25133 bool NegMul = (NegA != NegB);
25135 A = A.getOperand(0);
25137 B = B.getOperand(0);
25139 C = C.getOperand(0);
25143 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
25145 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
25147 return DAG.getNode(Opcode, dl, VT, A, B, C);
25150 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
25151 TargetLowering::DAGCombinerInfo &DCI,
25152 const X86Subtarget *Subtarget) {
25153 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
25154 // (and (i32 x86isd::setcc_carry), 1)
25155 // This eliminates the zext. This transformation is necessary because
25156 // ISD::SETCC is always legalized to i8.
25158 SDValue N0 = N->getOperand(0);
25159 EVT VT = N->getValueType(0);
25161 if (N0.getOpcode() == ISD::AND &&
25163 N0.getOperand(0).hasOneUse()) {
25164 SDValue N00 = N0.getOperand(0);
25165 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25166 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
25167 if (!C || C->getZExtValue() != 1)
25169 return DAG.getNode(ISD::AND, dl, VT,
25170 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25171 N00.getOperand(0), N00.getOperand(1)),
25172 DAG.getConstant(1, dl, VT));
25176 if (N0.getOpcode() == ISD::TRUNCATE &&
25178 N0.getOperand(0).hasOneUse()) {
25179 SDValue N00 = N0.getOperand(0);
25180 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
25181 return DAG.getNode(ISD::AND, dl, VT,
25182 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
25183 N00.getOperand(0), N00.getOperand(1)),
25184 DAG.getConstant(1, dl, VT));
25188 if (VT.is256BitVector())
25189 if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
25192 // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
25193 // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
25194 // This exposes the zext to the udivrem lowering, so that it directly extends
25195 // from AH (which we otherwise need to do contortions to access).
25196 if (N0.getOpcode() == ISD::UDIVREM &&
25197 N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
25198 (VT == MVT::i32 || VT == MVT::i64)) {
25199 SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
25200 SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
25201 N0.getOperand(0), N0.getOperand(1));
25202 DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
25203 return R.getValue(1);
25209 // Optimize x == -y --> x+y == 0
25210 // x != -y --> x+y != 0
25211 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
25212 const X86Subtarget* Subtarget) {
25213 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
25214 SDValue LHS = N->getOperand(0);
25215 SDValue RHS = N->getOperand(1);
25216 EVT VT = N->getValueType(0);
25219 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
25220 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
25221 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
25222 SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
25223 LHS.getOperand(1));
25224 return DAG.getSetCC(DL, N->getValueType(0), addV,
25225 DAG.getConstant(0, DL, addV.getValueType()), CC);
25227 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
25228 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
25229 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
25230 SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
25231 RHS.getOperand(1));
25232 return DAG.getSetCC(DL, N->getValueType(0), addV,
25233 DAG.getConstant(0, DL, addV.getValueType()), CC);
25236 if (VT.getScalarType() == MVT::i1 &&
25237 (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
25239 (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25240 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25241 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25243 if (!IsSEXT0 || !IsVZero1) {
25244 // Swap the operands and update the condition code.
25245 std::swap(LHS, RHS);
25246 CC = ISD::getSetCCSwappedOperands(CC);
25248 IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25249 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25250 IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25253 if (IsSEXT0 && IsVZero1) {
25254 assert(VT == LHS.getOperand(0).getValueType() &&
25255 "Uexpected operand type");
25256 if (CC == ISD::SETGT)
25257 return DAG.getConstant(0, DL, VT);
25258 if (CC == ISD::SETLE)
25259 return DAG.getConstant(1, DL, VT);
25260 if (CC == ISD::SETEQ || CC == ISD::SETGE)
25261 return DAG.getNOT(DL, LHS.getOperand(0), VT);
25263 assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
25264 "Unexpected condition code!");
25265 return LHS.getOperand(0);
25272 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
25273 SelectionDAG &DAG) {
25275 MVT VT = Load->getSimpleValueType(0);
25276 MVT EVT = VT.getVectorElementType();
25277 SDValue Addr = Load->getOperand(1);
25278 SDValue NewAddr = DAG.getNode(
25279 ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
25280 DAG.getConstant(Index * EVT.getStoreSize(), dl,
25281 Addr.getSimpleValueType()));
25284 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
25285 DAG.getMachineFunction().getMachineMemOperand(
25286 Load->getMemOperand(), 0, EVT.getStoreSize()));
25290 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
25291 const X86Subtarget *Subtarget) {
25293 MVT VT = N->getOperand(1)->getSimpleValueType(0);
25294 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
25295 "X86insertps is only defined for v4x32");
25297 SDValue Ld = N->getOperand(1);
25298 if (MayFoldLoad(Ld)) {
25299 // Extract the countS bits from the immediate so we can get the proper
25300 // address when narrowing the vector load to a specific element.
25301 // When the second source op is a memory address, insertps doesn't use
25302 // countS and just gets an f32 from that address.
25303 unsigned DestIndex =
25304 cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
25306 Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
25308 // Create this as a scalar to vector to match the instruction pattern.
25309 SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
25310 // countS bits are ignored when loading from memory on insertps, which
25311 // means we don't need to explicitly set them to 0.
25312 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
25313 LoadScalarToVector, N->getOperand(2));
25318 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
25319 SDValue V0 = N->getOperand(0);
25320 SDValue V1 = N->getOperand(1);
25322 EVT VT = N->getValueType(0);
25324 // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
25325 // operands and changing the mask to 1. This saves us a bunch of
25326 // pattern-matching possibilities related to scalar math ops in SSE/AVX.
25327 // x86InstrInfo knows how to commute this back after instruction selection
25328 // if it would help register allocation.
25330 // TODO: If optimizing for size or a processor that doesn't suffer from
25331 // partial register update stalls, this should be transformed into a MOVSD
25332 // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
25334 if (VT == MVT::v2f64)
25335 if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
25336 if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
25337 SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
25338 return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
25344 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
25345 // as "sbb reg,reg", since it can be extended without zext and produces
25346 // an all-ones bit which is more useful than 0/1 in some cases.
25347 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
25350 return DAG.getNode(ISD::AND, DL, VT,
25351 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25352 DAG.getConstant(X86::COND_B, DL, MVT::i8),
25354 DAG.getConstant(1, DL, VT));
25355 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
25356 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
25357 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25358 DAG.getConstant(X86::COND_B, DL, MVT::i8),
25362 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
25363 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
25364 TargetLowering::DAGCombinerInfo &DCI,
25365 const X86Subtarget *Subtarget) {
25367 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
25368 SDValue EFLAGS = N->getOperand(1);
25370 if (CC == X86::COND_A) {
25371 // Try to convert COND_A into COND_B in an attempt to facilitate
25372 // materializing "setb reg".
25374 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
25375 // cannot take an immediate as its first operand.
25377 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
25378 EFLAGS.getValueType().isInteger() &&
25379 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
25380 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
25381 EFLAGS.getNode()->getVTList(),
25382 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
25383 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
25384 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
25388 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
25389 // a zext and produces an all-ones bit which is more useful than 0/1 in some
25391 if (CC == X86::COND_B)
25392 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
25394 if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25395 SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25396 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
25402 // Optimize branch condition evaluation.
25404 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
25405 TargetLowering::DAGCombinerInfo &DCI,
25406 const X86Subtarget *Subtarget) {
25408 SDValue Chain = N->getOperand(0);
25409 SDValue Dest = N->getOperand(1);
25410 SDValue EFLAGS = N->getOperand(3);
25411 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
25413 if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25414 SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25415 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
25422 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
25423 SelectionDAG &DAG) {
25424 // Take advantage of vector comparisons producing 0 or -1 in each lane to
25425 // optimize away operation when it's from a constant.
25427 // The general transformation is:
25428 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
25429 // AND(VECTOR_CMP(x,y), constant2)
25430 // constant2 = UNARYOP(constant)
25432 // Early exit if this isn't a vector operation, the operand of the
25433 // unary operation isn't a bitwise AND, or if the sizes of the operations
25434 // aren't the same.
25435 EVT VT = N->getValueType(0);
25436 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
25437 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
25438 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
25441 // Now check that the other operand of the AND is a constant. We could
25442 // make the transformation for non-constant splats as well, but it's unclear
25443 // that would be a benefit as it would not eliminate any operations, just
25444 // perform one more step in scalar code before moving to the vector unit.
25445 if (BuildVectorSDNode *BV =
25446 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
25447 // Bail out if the vector isn't a constant.
25448 if (!BV->isConstant())
25451 // Everything checks out. Build up the new and improved node.
25453 EVT IntVT = BV->getValueType(0);
25454 // Create a new constant of the appropriate type for the transformed
25456 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
25457 // The AND node needs bitcasts to/from an integer vector type around it.
25458 SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
25459 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
25460 N->getOperand(0)->getOperand(0), MaskConst);
25461 SDValue Res = DAG.getBitcast(VT, NewAnd);
25468 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25469 const X86Subtarget *Subtarget) {
25470 SDValue Op0 = N->getOperand(0);
25471 EVT VT = N->getValueType(0);
25472 EVT InVT = Op0.getValueType();
25473 EVT InSVT = InVT.getScalarType();
25474 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25476 // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
25477 // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
25478 if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25480 EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25481 InVT.getVectorNumElements());
25482 SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
25484 if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
25485 return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
25487 return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25493 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25494 const X86Subtarget *Subtarget) {
25495 // First try to optimize away the conversion entirely when it's
25496 // conditionally from a constant. Vectors only.
25497 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
25500 // Now move on to more general possibilities.
25501 SDValue Op0 = N->getOperand(0);
25502 EVT VT = N->getValueType(0);
25503 EVT InVT = Op0.getValueType();
25504 EVT InSVT = InVT.getScalarType();
25506 // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
25507 // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
25508 if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25510 EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25511 InVT.getVectorNumElements());
25512 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
25513 return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25516 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
25517 // a 32-bit target where SSE doesn't support i64->FP operations.
25518 if (Op0.getOpcode() == ISD::LOAD) {
25519 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
25520 EVT LdVT = Ld->getValueType(0);
25522 // This transformation is not supported if the result type is f16
25523 if (VT == MVT::f16)
25526 if (!Ld->isVolatile() && !VT.isVector() &&
25527 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
25528 !Subtarget->is64Bit() && LdVT == MVT::i64) {
25529 SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
25530 SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
25531 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
25538 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
25539 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
25540 X86TargetLowering::DAGCombinerInfo &DCI) {
25541 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
25542 // the result is either zero or one (depending on the input carry bit).
25543 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
25544 if (X86::isZeroNode(N->getOperand(0)) &&
25545 X86::isZeroNode(N->getOperand(1)) &&
25546 // We don't have a good way to replace an EFLAGS use, so only do this when
25548 SDValue(N, 1).use_empty()) {
25550 EVT VT = N->getValueType(0);
25551 SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
25552 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
25553 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
25554 DAG.getConstant(X86::COND_B, DL,
25557 DAG.getConstant(1, DL, VT));
25558 return DCI.CombineTo(N, Res1, CarryOut);
25564 // fold (add Y, (sete X, 0)) -> adc 0, Y
25565 // (add Y, (setne X, 0)) -> sbb -1, Y
25566 // (sub (sete X, 0), Y) -> sbb 0, Y
25567 // (sub (setne X, 0), Y) -> adc -1, Y
25568 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
25571 // Look through ZExts.
25572 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
25573 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
25576 SDValue SetCC = Ext.getOperand(0);
25577 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
25580 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
25581 if (CC != X86::COND_E && CC != X86::COND_NE)
25584 SDValue Cmp = SetCC.getOperand(1);
25585 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
25586 !X86::isZeroNode(Cmp.getOperand(1)) ||
25587 !Cmp.getOperand(0).getValueType().isInteger())
25590 SDValue CmpOp0 = Cmp.getOperand(0);
25591 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
25592 DAG.getConstant(1, DL, CmpOp0.getValueType()));
25594 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
25595 if (CC == X86::COND_NE)
25596 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
25597 DL, OtherVal.getValueType(), OtherVal,
25598 DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
25600 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
25601 DL, OtherVal.getValueType(), OtherVal,
25602 DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
25605 /// PerformADDCombine - Do target-specific dag combines on integer adds.
25606 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
25607 const X86Subtarget *Subtarget) {
25608 EVT VT = N->getValueType(0);
25609 SDValue Op0 = N->getOperand(0);
25610 SDValue Op1 = N->getOperand(1);
25612 // Try to synthesize horizontal adds from adds of shuffles.
25613 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25614 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25615 isHorizontalBinOp(Op0, Op1, true))
25616 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
25618 return OptimizeConditionalInDecrement(N, DAG);
25621 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
25622 const X86Subtarget *Subtarget) {
25623 SDValue Op0 = N->getOperand(0);
25624 SDValue Op1 = N->getOperand(1);
25626 // X86 can't encode an immediate LHS of a sub. See if we can push the
25627 // negation into a preceding instruction.
25628 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
25629 // If the RHS of the sub is a XOR with one use and a constant, invert the
25630 // immediate. Then add one to the LHS of the sub so we can turn
25631 // X-Y -> X+~Y+1, saving one register.
25632 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
25633 isa<ConstantSDNode>(Op1.getOperand(1))) {
25634 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
25635 EVT VT = Op0.getValueType();
25636 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
25638 DAG.getConstant(~XorC, SDLoc(Op1), VT));
25639 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
25640 DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
25644 // Try to synthesize horizontal adds from adds of shuffles.
25645 EVT VT = N->getValueType(0);
25646 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25647 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25648 isHorizontalBinOp(Op0, Op1, true))
25649 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
25651 return OptimizeConditionalInDecrement(N, DAG);
25654 /// performVZEXTCombine - Performs build vector combines
25655 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
25656 TargetLowering::DAGCombinerInfo &DCI,
25657 const X86Subtarget *Subtarget) {
25659 MVT VT = N->getSimpleValueType(0);
25660 SDValue Op = N->getOperand(0);
25661 MVT OpVT = Op.getSimpleValueType();
25662 MVT OpEltVT = OpVT.getVectorElementType();
25663 unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
25665 // (vzext (bitcast (vzext (x)) -> (vzext x)
25667 while (V.getOpcode() == ISD::BITCAST)
25668 V = V.getOperand(0);
25670 if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
25671 MVT InnerVT = V.getSimpleValueType();
25672 MVT InnerEltVT = InnerVT.getVectorElementType();
25674 // If the element sizes match exactly, we can just do one larger vzext. This
25675 // is always an exact type match as vzext operates on integer types.
25676 if (OpEltVT == InnerEltVT) {
25677 assert(OpVT == InnerVT && "Types must match for vzext!");
25678 return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
25681 // The only other way we can combine them is if only a single element of the
25682 // inner vzext is used in the input to the outer vzext.
25683 if (InnerEltVT.getSizeInBits() < InputBits)
25686 // In this case, the inner vzext is completely dead because we're going to
25687 // only look at bits inside of the low element. Just do the outer vzext on
25688 // a bitcast of the input to the inner.
25689 return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
25692 // Check if we can bypass extracting and re-inserting an element of an input
25693 // vector. Essentially:
25694 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
25695 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
25696 V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
25697 V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
25698 SDValue ExtractedV = V.getOperand(0);
25699 SDValue OrigV = ExtractedV.getOperand(0);
25700 if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
25701 if (ExtractIdx->getZExtValue() == 0) {
25702 MVT OrigVT = OrigV.getSimpleValueType();
25703 // Extract a subvector if necessary...
25704 if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
25705 int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
25706 OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
25707 OrigVT.getVectorNumElements() / Ratio);
25708 OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
25709 DAG.getIntPtrConstant(0, DL));
25711 Op = DAG.getBitcast(OpVT, OrigV);
25712 return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
25719 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
25720 DAGCombinerInfo &DCI) const {
25721 SelectionDAG &DAG = DCI.DAG;
25722 switch (N->getOpcode()) {
25724 case ISD::EXTRACT_VECTOR_ELT:
25725 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
25728 case X86ISD::SHRUNKBLEND:
25729 return PerformSELECTCombine(N, DAG, DCI, Subtarget);
25730 case ISD::BITCAST: return PerformBITCASTCombine(N, DAG);
25731 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
25732 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
25733 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
25734 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
25735 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
25738 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
25739 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
25740 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
25741 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
25742 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
25743 case ISD::MLOAD: return PerformMLOADCombine(N, DAG, DCI, Subtarget);
25744 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
25745 case ISD::MSTORE: return PerformMSTORECombine(N, DAG, Subtarget);
25746 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
25747 case ISD::UINT_TO_FP: return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
25748 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
25749 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
25751 case X86ISD::FOR: return PerformFORCombine(N, DAG);
25753 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
25754 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
25755 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
25756 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
25757 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
25758 case ISD::ANY_EXTEND:
25759 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
25760 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
25761 case ISD::SIGN_EXTEND_INREG:
25762 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
25763 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
25764 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
25765 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
25766 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
25767 case X86ISD::SHUFP: // Handle all target specific shuffles
25768 case X86ISD::PALIGNR:
25769 case X86ISD::UNPCKH:
25770 case X86ISD::UNPCKL:
25771 case X86ISD::MOVHLPS:
25772 case X86ISD::MOVLHPS:
25773 case X86ISD::PSHUFB:
25774 case X86ISD::PSHUFD:
25775 case X86ISD::PSHUFHW:
25776 case X86ISD::PSHUFLW:
25777 case X86ISD::MOVSS:
25778 case X86ISD::MOVSD:
25779 case X86ISD::VPERMILPI:
25780 case X86ISD::VPERM2X128:
25781 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
25782 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
25783 case ISD::INTRINSIC_WO_CHAIN:
25784 return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
25785 case X86ISD::INSERTPS: {
25786 if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
25787 return PerformINSERTPSCombine(N, DAG, Subtarget);
25790 case X86ISD::BLENDI: return PerformBLENDICombine(N, DAG);
25796 /// isTypeDesirableForOp - Return true if the target has native support for
25797 /// the specified value type and it is 'desirable' to use the type for the
25798 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
25799 /// instruction encodings are longer and some i16 instructions are slow.
25800 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
25801 if (!isTypeLegal(VT))
25803 if (VT != MVT::i16)
25810 case ISD::SIGN_EXTEND:
25811 case ISD::ZERO_EXTEND:
25812 case ISD::ANY_EXTEND:
25825 /// IsDesirableToPromoteOp - This method query the target whether it is
25826 /// beneficial for dag combiner to promote the specified node. If true, it
25827 /// should return the desired promotion type by reference.
25828 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
25829 EVT VT = Op.getValueType();
25830 if (VT != MVT::i16)
25833 bool Promote = false;
25834 bool Commute = false;
25835 switch (Op.getOpcode()) {
25838 LoadSDNode *LD = cast<LoadSDNode>(Op);
25839 // If the non-extending load has a single use and it's not live out, then it
25840 // might be folded.
25841 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
25842 Op.hasOneUse()*/) {
25843 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
25844 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
25845 // The only case where we'd want to promote LOAD (rather then it being
25846 // promoted as an operand is when it's only use is liveout.
25847 if (UI->getOpcode() != ISD::CopyToReg)
25854 case ISD::SIGN_EXTEND:
25855 case ISD::ZERO_EXTEND:
25856 case ISD::ANY_EXTEND:
25861 SDValue N0 = Op.getOperand(0);
25862 // Look out for (store (shl (load), x)).
25863 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
25876 SDValue N0 = Op.getOperand(0);
25877 SDValue N1 = Op.getOperand(1);
25878 if (!Commute && MayFoldLoad(N1))
25880 // Avoid disabling potential load folding opportunities.
25881 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
25883 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
25893 //===----------------------------------------------------------------------===//
25894 // X86 Inline Assembly Support
25895 //===----------------------------------------------------------------------===//
25897 // Helper to match a string separated by whitespace.
25898 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
25899 S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
25901 for (StringRef Piece : Pieces) {
25902 if (!S.startswith(Piece)) // Check if the piece matches.
25905 S = S.substr(Piece.size());
25906 StringRef::size_type Pos = S.find_first_not_of(" \t");
25907 if (Pos == 0) // We matched a prefix.
25916 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
25918 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
25919 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
25920 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
25921 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
25923 if (AsmPieces.size() == 3)
25925 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
25932 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
25933 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
25935 std::string AsmStr = IA->getAsmString();
25937 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
25938 if (!Ty || Ty->getBitWidth() % 16 != 0)
25941 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
25942 SmallVector<StringRef, 4> AsmPieces;
25943 SplitString(AsmStr, AsmPieces, ";\n");
25945 switch (AsmPieces.size()) {
25946 default: return false;
25948 // FIXME: this should verify that we are targeting a 486 or better. If not,
25949 // we will turn this bswap into something that will be lowered to logical
25950 // ops instead of emitting the bswap asm. For now, we don't support 486 or
25951 // lower so don't worry about this.
25953 if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
25954 matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
25955 matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
25956 matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
25957 matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
25958 matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
25959 // No need to check constraints, nothing other than the equivalent of
25960 // "=r,0" would be valid here.
25961 return IntrinsicLowering::LowerToByteSwap(CI);
25964 // rorw $$8, ${0:w} --> llvm.bswap.i16
25965 if (CI->getType()->isIntegerTy(16) &&
25966 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25967 (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
25968 matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
25970 StringRef ConstraintsStr = IA->getConstraintString();
25971 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25972 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25973 if (clobbersFlagRegisters(AsmPieces))
25974 return IntrinsicLowering::LowerToByteSwap(CI);
25978 if (CI->getType()->isIntegerTy(32) &&
25979 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25980 matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
25981 matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
25982 matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
25984 StringRef ConstraintsStr = IA->getConstraintString();
25985 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25986 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25987 if (clobbersFlagRegisters(AsmPieces))
25988 return IntrinsicLowering::LowerToByteSwap(CI);
25991 if (CI->getType()->isIntegerTy(64)) {
25992 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
25993 if (Constraints.size() >= 2 &&
25994 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
25995 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
25996 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
25997 if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
25998 matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
25999 matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
26000 return IntrinsicLowering::LowerToByteSwap(CI);
26008 /// getConstraintType - Given a constraint letter, return the type of
26009 /// constraint it is for this target.
26010 X86TargetLowering::ConstraintType
26011 X86TargetLowering::getConstraintType(StringRef Constraint) const {
26012 if (Constraint.size() == 1) {
26013 switch (Constraint[0]) {
26024 return C_RegisterClass;
26048 return TargetLowering::getConstraintType(Constraint);
26051 /// Examine constraint type and operand type and determine a weight value.
26052 /// This object must already have been set up with the operand type
26053 /// and the current alternative constraint selected.
26054 TargetLowering::ConstraintWeight
26055 X86TargetLowering::getSingleConstraintMatchWeight(
26056 AsmOperandInfo &info, const char *constraint) const {
26057 ConstraintWeight weight = CW_Invalid;
26058 Value *CallOperandVal = info.CallOperandVal;
26059 // If we don't have a value, we can't do a match,
26060 // but allow it at the lowest weight.
26061 if (!CallOperandVal)
26063 Type *type = CallOperandVal->getType();
26064 // Look at the constraint type.
26065 switch (*constraint) {
26067 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
26078 if (CallOperandVal->getType()->isIntegerTy())
26079 weight = CW_SpecificReg;
26084 if (type->isFloatingPointTy())
26085 weight = CW_SpecificReg;
26088 if (type->isX86_MMXTy() && Subtarget->hasMMX())
26089 weight = CW_SpecificReg;
26093 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
26094 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
26095 weight = CW_Register;
26098 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
26099 if (C->getZExtValue() <= 31)
26100 weight = CW_Constant;
26104 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26105 if (C->getZExtValue() <= 63)
26106 weight = CW_Constant;
26110 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26111 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
26112 weight = CW_Constant;
26116 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26117 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
26118 weight = CW_Constant;
26122 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26123 if (C->getZExtValue() <= 3)
26124 weight = CW_Constant;
26128 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26129 if (C->getZExtValue() <= 0xff)
26130 weight = CW_Constant;
26135 if (isa<ConstantFP>(CallOperandVal)) {
26136 weight = CW_Constant;
26140 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26141 if ((C->getSExtValue() >= -0x80000000LL) &&
26142 (C->getSExtValue() <= 0x7fffffffLL))
26143 weight = CW_Constant;
26147 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
26148 if (C->getZExtValue() <= 0xffffffff)
26149 weight = CW_Constant;
26156 /// LowerXConstraint - try to replace an X constraint, which matches anything,
26157 /// with another that has more specific requirements based on the type of the
26158 /// corresponding operand.
26159 const char *X86TargetLowering::
26160 LowerXConstraint(EVT ConstraintVT) const {
26161 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
26162 // 'f' like normal targets.
26163 if (ConstraintVT.isFloatingPoint()) {
26164 if (Subtarget->hasSSE2())
26166 if (Subtarget->hasSSE1())
26170 return TargetLowering::LowerXConstraint(ConstraintVT);
26173 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
26174 /// vector. If it is invalid, don't add anything to Ops.
26175 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
26176 std::string &Constraint,
26177 std::vector<SDValue>&Ops,
26178 SelectionDAG &DAG) const {
26181 // Only support length 1 constraints for now.
26182 if (Constraint.length() > 1) return;
26184 char ConstraintLetter = Constraint[0];
26185 switch (ConstraintLetter) {
26188 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26189 if (C->getZExtValue() <= 31) {
26190 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26191 Op.getValueType());
26197 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26198 if (C->getZExtValue() <= 63) {
26199 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26200 Op.getValueType());
26206 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26207 if (isInt<8>(C->getSExtValue())) {
26208 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26209 Op.getValueType());
26215 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26216 if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
26217 (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
26218 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
26219 Op.getValueType());
26225 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26226 if (C->getZExtValue() <= 3) {
26227 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26228 Op.getValueType());
26234 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26235 if (C->getZExtValue() <= 255) {
26236 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26237 Op.getValueType());
26243 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26244 if (C->getZExtValue() <= 127) {
26245 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26246 Op.getValueType());
26252 // 32-bit signed value
26253 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26254 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26255 C->getSExtValue())) {
26256 // Widen to 64 bits here to get it sign extended.
26257 Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
26260 // FIXME gcc accepts some relocatable values here too, but only in certain
26261 // memory models; it's complicated.
26266 // 32-bit unsigned value
26267 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26268 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26269 C->getZExtValue())) {
26270 Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26271 Op.getValueType());
26275 // FIXME gcc accepts some relocatable values here too, but only in certain
26276 // memory models; it's complicated.
26280 // Literal immediates are always ok.
26281 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
26282 // Widen to 64 bits here to get it sign extended.
26283 Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
26287 // In any sort of PIC mode addresses need to be computed at runtime by
26288 // adding in a register or some sort of table lookup. These can't
26289 // be used as immediates.
26290 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
26293 // If we are in non-pic codegen mode, we allow the address of a global (with
26294 // an optional displacement) to be used with 'i'.
26295 GlobalAddressSDNode *GA = nullptr;
26296 int64_t Offset = 0;
26298 // Match either (GA), (GA+C), (GA+C1+C2), etc.
26300 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
26301 Offset += GA->getOffset();
26303 } else if (Op.getOpcode() == ISD::ADD) {
26304 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26305 Offset += C->getZExtValue();
26306 Op = Op.getOperand(0);
26309 } else if (Op.getOpcode() == ISD::SUB) {
26310 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26311 Offset += -C->getZExtValue();
26312 Op = Op.getOperand(0);
26317 // Otherwise, this isn't something we can handle, reject it.
26321 const GlobalValue *GV = GA->getGlobal();
26322 // If we require an extra load to get this address, as in PIC mode, we
26323 // can't accept it.
26324 if (isGlobalStubReference(
26325 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
26328 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
26329 GA->getValueType(0), Offset);
26334 if (Result.getNode()) {
26335 Ops.push_back(Result);
26338 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
26341 std::pair<unsigned, const TargetRegisterClass *>
26342 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
26343 StringRef Constraint,
26345 // First, see if this is a constraint that directly corresponds to an LLVM
26347 if (Constraint.size() == 1) {
26348 // GCC Constraint Letters
26349 switch (Constraint[0]) {
26351 // TODO: Slight differences here in allocation order and leaving
26352 // RIP in the class. Do they matter any more here than they do
26353 // in the normal allocation?
26354 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
26355 if (Subtarget->is64Bit()) {
26356 if (VT == MVT::i32 || VT == MVT::f32)
26357 return std::make_pair(0U, &X86::GR32RegClass);
26358 if (VT == MVT::i16)
26359 return std::make_pair(0U, &X86::GR16RegClass);
26360 if (VT == MVT::i8 || VT == MVT::i1)
26361 return std::make_pair(0U, &X86::GR8RegClass);
26362 if (VT == MVT::i64 || VT == MVT::f64)
26363 return std::make_pair(0U, &X86::GR64RegClass);
26366 // 32-bit fallthrough
26367 case 'Q': // Q_REGS
26368 if (VT == MVT::i32 || VT == MVT::f32)
26369 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
26370 if (VT == MVT::i16)
26371 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
26372 if (VT == MVT::i8 || VT == MVT::i1)
26373 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
26374 if (VT == MVT::i64)
26375 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
26377 case 'r': // GENERAL_REGS
26378 case 'l': // INDEX_REGS
26379 if (VT == MVT::i8 || VT == MVT::i1)
26380 return std::make_pair(0U, &X86::GR8RegClass);
26381 if (VT == MVT::i16)
26382 return std::make_pair(0U, &X86::GR16RegClass);
26383 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
26384 return std::make_pair(0U, &X86::GR32RegClass);
26385 return std::make_pair(0U, &X86::GR64RegClass);
26386 case 'R': // LEGACY_REGS
26387 if (VT == MVT::i8 || VT == MVT::i1)
26388 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
26389 if (VT == MVT::i16)
26390 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
26391 if (VT == MVT::i32 || !Subtarget->is64Bit())
26392 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
26393 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
26394 case 'f': // FP Stack registers.
26395 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
26396 // value to the correct fpstack register class.
26397 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
26398 return std::make_pair(0U, &X86::RFP32RegClass);
26399 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
26400 return std::make_pair(0U, &X86::RFP64RegClass);
26401 return std::make_pair(0U, &X86::RFP80RegClass);
26402 case 'y': // MMX_REGS if MMX allowed.
26403 if (!Subtarget->hasMMX()) break;
26404 return std::make_pair(0U, &X86::VR64RegClass);
26405 case 'Y': // SSE_REGS if SSE2 allowed
26406 if (!Subtarget->hasSSE2()) break;
26408 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
26409 if (!Subtarget->hasSSE1()) break;
26411 switch (VT.SimpleTy) {
26413 // Scalar SSE types.
26416 return std::make_pair(0U, &X86::FR32RegClass);
26419 return std::make_pair(0U, &X86::FR64RegClass);
26427 return std::make_pair(0U, &X86::VR128RegClass);
26435 return std::make_pair(0U, &X86::VR256RegClass);
26440 return std::make_pair(0U, &X86::VR512RegClass);
26446 // Use the default implementation in TargetLowering to convert the register
26447 // constraint into a member of a register class.
26448 std::pair<unsigned, const TargetRegisterClass*> Res;
26449 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
26451 // Not found as a standard register?
26453 // Map st(0) -> st(7) -> ST0
26454 if (Constraint.size() == 7 && Constraint[0] == '{' &&
26455 tolower(Constraint[1]) == 's' &&
26456 tolower(Constraint[2]) == 't' &&
26457 Constraint[3] == '(' &&
26458 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
26459 Constraint[5] == ')' &&
26460 Constraint[6] == '}') {
26462 Res.first = X86::FP0+Constraint[4]-'0';
26463 Res.second = &X86::RFP80RegClass;
26467 // GCC allows "st(0)" to be called just plain "st".
26468 if (StringRef("{st}").equals_lower(Constraint)) {
26469 Res.first = X86::FP0;
26470 Res.second = &X86::RFP80RegClass;
26475 if (StringRef("{flags}").equals_lower(Constraint)) {
26476 Res.first = X86::EFLAGS;
26477 Res.second = &X86::CCRRegClass;
26481 // 'A' means EAX + EDX.
26482 if (Constraint == "A") {
26483 Res.first = X86::EAX;
26484 Res.second = &X86::GR32_ADRegClass;
26490 // Otherwise, check to see if this is a register class of the wrong value
26491 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
26492 // turn into {ax},{dx}.
26493 // MVT::Other is used to specify clobber names.
26494 if (Res.second->hasType(VT) || VT == MVT::Other)
26495 return Res; // Correct type already, nothing to do.
26497 // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
26498 // return "eax". This should even work for things like getting 64bit integer
26499 // registers when given an f64 type.
26500 const TargetRegisterClass *Class = Res.second;
26501 if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
26502 Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
26503 unsigned Size = VT.getSizeInBits();
26504 MVT::SimpleValueType SimpleTy = Size == 1 || Size == 8 ? MVT::i8
26505 : Size == 16 ? MVT::i16
26506 : Size == 32 ? MVT::i32
26507 : Size == 64 ? MVT::i64
26509 unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, SimpleTy);
26511 Res.first = DestReg;
26512 Res.second = SimpleTy == MVT::i8 ? &X86::GR8RegClass
26513 : SimpleTy == MVT::i16 ? &X86::GR16RegClass
26514 : SimpleTy == MVT::i32 ? &X86::GR32RegClass
26515 : &X86::GR64RegClass;
26516 assert(Res.second->contains(Res.first) && "Register in register class");
26518 // No register found/type mismatch.
26520 Res.second = nullptr;
26522 } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
26523 Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
26524 Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
26525 Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
26526 Class == &X86::VR512RegClass) {
26527 // Handle references to XMM physical registers that got mapped into the
26528 // wrong class. This can happen with constraints like {xmm0} where the
26529 // target independent register mapper will just pick the first match it can
26530 // find, ignoring the required type.
26532 if (VT == MVT::f32 || VT == MVT::i32)
26533 Res.second = &X86::FR32RegClass;
26534 else if (VT == MVT::f64 || VT == MVT::i64)
26535 Res.second = &X86::FR64RegClass;
26536 else if (X86::VR128RegClass.hasType(VT))
26537 Res.second = &X86::VR128RegClass;
26538 else if (X86::VR256RegClass.hasType(VT))
26539 Res.second = &X86::VR256RegClass;
26540 else if (X86::VR512RegClass.hasType(VT))
26541 Res.second = &X86::VR512RegClass;
26543 // Type mismatch and not a clobber: Return an error;
26545 Res.second = nullptr;
26552 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
26553 const AddrMode &AM, Type *Ty,
26554 unsigned AS) const {
26555 // Scaling factors are not free at all.
26556 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
26557 // will take 2 allocations in the out of order engine instead of 1
26558 // for plain addressing mode, i.e. inst (reg1).
26560 // vaddps (%rsi,%drx), %ymm0, %ymm1
26561 // Requires two allocations (one for the load, one for the computation)
26563 // vaddps (%rsi), %ymm0, %ymm1
26564 // Requires just 1 allocation, i.e., freeing allocations for other operations
26565 // and having less micro operations to execute.
26567 // For some X86 architectures, this is even worse because for instance for
26568 // stores, the complex addressing mode forces the instruction to use the
26569 // "load" ports instead of the dedicated "store" port.
26570 // E.g., on Haswell:
26571 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
26572 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
26573 if (isLegalAddressingMode(DL, AM, Ty, AS))
26574 // Scale represents reg2 * scale, thus account for 1
26575 // as soon as we use a second register.
26576 return AM.Scale != 0;
26580 bool X86TargetLowering::isTargetFTOL() const {
26581 return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();